Give helpful advice when a fully qualified name is not in scope
[ghc.git] / compiler / rename / RnEnv.hs
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
3
4 \section[RnEnv]{Environment manipulation for the renamer monad}
5 -}
6
7 {-# LANGUAGE CPP #-}
8
9 module RnEnv (
10 newTopSrcBinder,
11 lookupLocatedTopBndrRn, lookupTopBndrRn,
12 lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe,
13 lookupLocalOccRn_maybe, lookupInfoOccRn,
14 lookupLocalOccThLvl_maybe,
15 lookupTypeOccRn, lookupKindOccRn,
16 lookupGlobalOccRn, lookupGlobalOccRn_maybe,
17 lookupOccRn_overloaded, lookupGlobalOccRn_overloaded,
18 reportUnboundName, unknownNameSuggestions,
19 addNameClashErrRn,
20
21 HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn,
22 lookupSigCtxtOccRn,
23
24 lookupFixityRn, lookupTyFixityRn,
25 lookupInstDeclBndr, lookupSubBndrOcc, lookupFamInstName,
26 lookupSubBndrGREs, lookupConstructorFields,
27 lookupSyntaxName, lookupSyntaxNames, lookupIfThenElse,
28 lookupGreAvailRn,
29 getLookupOccRn,
30 addUsedGRE, addUsedGREs, addUsedDataCons,
31
32 newLocalBndrRn, newLocalBndrsRn,
33 bindLocalNames, bindLocalNamesFV,
34 MiniFixityEnv,
35 addLocalFixities,
36 bindLocatedLocalsFV, bindLocatedLocalsRn,
37 extendTyVarEnvFVRn,
38
39 checkDupRdrNames, checkShadowedRdrNames,
40 checkDupNames, checkDupAndShadowedNames, checkTupSize,
41 addFvRn, mapFvRn, mapMaybeFvRn, mapFvRnCPS,
42 warnUnusedMatches,
43 warnUnusedTopBinds, warnUnusedLocalBinds,
44 mkFieldEnv,
45 dataTcOccs, kindSigErr, perhapsForallMsg, unknownSubordinateErr,
46 HsDocContext(..), docOfHsDocContext
47 ) where
48
49 #include "HsVersions.h"
50
51 import LoadIface ( loadInterfaceForName, loadSrcInterface_maybe )
52 import IfaceEnv
53 import HsSyn
54 import RdrName
55 import HscTypes
56 import TcEnv
57 import TcRnMonad
58 import RdrHsSyn ( setRdrNameSpace )
59 import Name
60 import NameSet
61 import NameEnv
62 import Avail
63 import Module
64 import ConLike
65 import DataCon
66 import TyCon
67 import PrelNames ( mkUnboundName, isUnboundName, rOOT_MAIN, forall_tv_RDR )
68 import ErrUtils ( MsgDoc )
69 import BasicTypes ( Fixity(..), FixityDirection(..), minPrecedence, defaultFixity )
70 import SrcLoc
71 import Outputable
72 import Util
73 import Maybes
74 import BasicTypes ( TopLevelFlag(..) )
75 import ListSetOps ( removeDups )
76 import DynFlags
77 import FastString
78 import Control.Monad
79 import Data.List
80 import Data.Function ( on )
81 import ListSetOps ( minusList )
82 import Constants ( mAX_TUPLE_SIZE )
83
84 {-
85 *********************************************************
86 * *
87 Source-code binders
88 * *
89 *********************************************************
90
91 Note [Signature lazy interface loading]
92 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
93
94 GHC's lazy interface loading can be a bit confusing, so this Note is an
95 empirical description of what happens in one interesting case. When
96 compiling a signature module against an its implementation, we do NOT
97 load interface files associated with its names until after the type
98 checking phase. For example:
99
100 module ASig where
101 data T
102 f :: T -> T
103
104 Suppose we compile this with -sig-of "A is ASig":
105
106 module B where
107 data T = T
108 f T = T
109
110 module A(module B) where
111 import B
112
113 During type checking, we'll load A.hi because we need to know what the
114 RdrEnv for the module is, but we DO NOT load the interface for B.hi!
115 It's wholly unnecessary: our local definition 'data T' in ASig is all
116 the information we need to finish type checking. This is contrast to
117 type checking of ordinary Haskell files, in which we would not have the
118 local definition "data T" and would need to consult B.hi immediately.
119 (Also, this situation never occurs for hs-boot files, since you're not
120 allowed to reexport from another module.)
121
122 After type checking, we then check that the types we provided are
123 consistent with the backing implementation (in checkHiBootOrHsigIface).
124 At this point, B.hi is loaded, because we need something to compare
125 against.
126
127 I discovered this behavior when trying to figure out why type class
128 instances for Data.Map weren't in the EPS when I was type checking a
129 test very much like ASig (sigof02dm): the associated interface hadn't
130 been loaded yet! (The larger issue is a moot point, since an instance
131 declared in a signature can never be a duplicate.)
132
133 This behavior might change in the future. Consider this
134 alternate module B:
135
136 module B where
137 {-# DEPRECATED T, f "Don't use" #-}
138 data T = T
139 f T = T
140
141 One might conceivably want to report deprecation warnings when compiling
142 ASig with -sig-of B, in which case we need to look at B.hi to find the
143 deprecation warnings during renaming. At the moment, you don't get any
144 warning until you use the identifier further downstream. This would
145 require adjusting addUsedGRE so that during signature compilation,
146 we do not report deprecation warnings for LocalDef. See also
147 Note [Handling of deprecations]
148 -}
149
150 newTopSrcBinder :: Located RdrName -> RnM Name
151 newTopSrcBinder (L loc rdr_name)
152 | Just name <- isExact_maybe rdr_name
153 = -- This is here to catch
154 -- (a) Exact-name binders created by Template Haskell
155 -- (b) The PrelBase defn of (say) [] and similar, for which
156 -- the parser reads the special syntax and returns an Exact RdrName
157 -- We are at a binding site for the name, so check first that it
158 -- the current module is the correct one; otherwise GHC can get
159 -- very confused indeed. This test rejects code like
160 -- data T = (,) Int Int
161 -- unless we are in GHC.Tup
162 if isExternalName name then
163 do { this_mod <- getModule
164 ; unless (this_mod == nameModule name)
165 (addErrAt loc (badOrigBinding rdr_name))
166 ; return name }
167 else -- See Note [Binders in Template Haskell] in Convert.hs
168 do { this_mod <- getModule
169 ; externaliseName this_mod name }
170
171 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
172 = do { this_mod <- getModule
173 ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
174 (addErrAt loc (badOrigBinding rdr_name))
175 -- When reading External Core we get Orig names as binders,
176 -- but they should agree with the module gotten from the monad
177 --
178 -- We can get built-in syntax showing up here too, sadly. If you type
179 -- data T = (,,,)
180 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
181 -- uses setRdrNameSpace to make it into a data constructors. At that point
182 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
183 -- Hence the badOrigBinding error message.
184 --
185 -- Except for the ":Main.main = ..." definition inserted into
186 -- the Main module; ugh!
187
188 -- Because of this latter case, we call newGlobalBinder with a module from
189 -- the RdrName, not from the environment. In principle, it'd be fine to
190 -- have an arbitrary mixture of external core definitions in a single module,
191 -- (apart from module-initialisation issues, perhaps).
192 ; newGlobalBinder rdr_mod rdr_occ loc }
193
194 | otherwise
195 = do { unless (not (isQual rdr_name))
196 (addErrAt loc (badQualBndrErr rdr_name))
197 -- Binders should not be qualified; if they are, and with a different
198 -- module name, we we get a confusing "M.T is not in scope" error later
199
200 ; stage <- getStage
201 ; env <- getGblEnv
202 ; if isBrackStage stage then
203 -- We are inside a TH bracket, so make an *Internal* name
204 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
205 do { uniq <- newUnique
206 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
207 else case tcg_impl_rdr_env env of
208 Just gr ->
209 -- We're compiling --sig-of, so resolve with respect to this
210 -- module.
211 -- See Note [Signature parameters in TcGblEnv and DynFlags]
212 do { case lookupGlobalRdrEnv gr (rdrNameOcc rdr_name) of
213 -- Be sure to override the loc so that we get accurate
214 -- information later
215 [GRE{ gre_name = n }] -> do
216 -- NB: Just adding this line will not work:
217 -- addUsedGRE True gre
218 -- see Note [Signature lazy interface loading] for
219 -- more details.
220 return (setNameLoc n loc)
221 _ -> do
222 { -- NB: cannot use reportUnboundName rdr_name
223 -- because it looks up in the wrong RdrEnv
224 -- ToDo: more helpful error messages
225 ; addErr (unknownNameErr (pprNonVarNameSpace
226 (occNameSpace (rdrNameOcc rdr_name))) rdr_name)
227 ; return (mkUnboundName rdr_name)
228 }
229 }
230 Nothing ->
231 -- Normal case
232 do { this_mod <- getModule
233 ; traceRn (text "newTopSrcBinder" <+> (ppr this_mod $$ ppr rdr_name $$ ppr loc))
234 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } }
235
236 {-
237 *********************************************************
238 * *
239 Source code occurrences
240 * *
241 *********************************************************
242
243 Looking up a name in the RnEnv.
244
245 Note [Type and class operator definitions]
246 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
247 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
248 data a :*: b = ...
249 class a :*: b where ...
250 data (:*:) a b = ....
251 class (:*:) a b where ...
252 The latter two mean that we are not just looking for a
253 *syntactically-infix* declaration, but one that uses an operator
254 OccName. We use OccName.isSymOcc to detect that case, which isn't
255 terribly efficient, but there seems to be no better way.
256 -}
257
258 lookupTopBndrRn :: RdrName -> RnM Name
259 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
260 case nopt of
261 Just n' -> return n'
262 Nothing -> do traceRn $ (text "lookupTopBndrRn fail" <+> ppr n)
263 unboundName WL_LocalTop n
264
265 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
266 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
267
268 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
269 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
270 -- and there may be several imported 'f's too, which must not confuse us.
271 -- For example, this is OK:
272 -- import Foo( f )
273 -- infix 9 f -- The 'f' here does not need to be qualified
274 -- f x = x -- Nor here, of course
275 -- So we have to filter out the non-local ones.
276 --
277 -- A separate function (importsFromLocalDecls) reports duplicate top level
278 -- decls, so here it's safe just to choose an arbitrary one.
279 --
280 -- There should never be a qualified name in a binding position in Haskell,
281 -- but there can be if we have read in an external-Core file.
282 -- The Haskell parser checks for the illegal qualified name in Haskell
283 -- source files, so we don't need to do so here.
284
285 lookupTopBndrRn_maybe rdr_name
286 | Just name <- isExact_maybe rdr_name
287 = do { name' <- lookupExactOcc name; return (Just name') }
288
289 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
290 -- This deals with the case of derived bindings, where
291 -- we don't bother to call newTopSrcBinder first
292 -- We assume there is no "parent" name
293 = do { loc <- getSrcSpanM
294 ; n <- newGlobalBinder rdr_mod rdr_occ loc
295 ; return (Just n)}
296
297 | otherwise
298 = do { -- Check for operators in type or class declarations
299 -- See Note [Type and class operator definitions]
300 let occ = rdrNameOcc rdr_name
301 ; when (isTcOcc occ && isSymOcc occ)
302 (do { op_ok <- xoptM Opt_TypeOperators
303 ; unless op_ok (addErr (opDeclErr rdr_name)) })
304
305 ; env <- getGlobalRdrEnv
306 ; case filter isLocalGRE (lookupGRE_RdrName rdr_name env) of
307 [gre] -> return (Just (gre_name gre))
308 _ -> return Nothing -- Ambiguous (can't happen) or unbound
309 }
310
311 -----------------------------------------------
312 -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
313 -- This adds an error if the name cannot be found.
314 lookupExactOcc :: Name -> RnM Name
315 lookupExactOcc name
316 = do { result <- lookupExactOcc_either name
317 ; case result of
318 Left err -> do { addErr err
319 ; return name }
320 Right name' -> return name' }
321
322 -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
323 -- This never adds an error, but it may return one.
324 lookupExactOcc_either :: Name -> RnM (Either MsgDoc Name)
325 -- See Note [Looking up Exact RdrNames]
326 lookupExactOcc_either name
327 | Just thing <- wiredInNameTyThing_maybe name
328 , Just tycon <- case thing of
329 ATyCon tc -> Just tc
330 AConLike (RealDataCon dc) -> Just (dataConTyCon dc)
331 _ -> Nothing
332 , isTupleTyCon tycon
333 = do { checkTupSize (tyConArity tycon)
334 ; return (Right name) }
335
336 | isExternalName name
337 = return (Right name)
338
339 | otherwise
340 = do { env <- getGlobalRdrEnv
341 ; let -- See Note [Splicing Exact names]
342 main_occ = nameOccName name
343 demoted_occs = case demoteOccName main_occ of
344 Just occ -> [occ]
345 Nothing -> []
346 gres = [ gre | occ <- main_occ : demoted_occs
347 , gre <- lookupGlobalRdrEnv env occ
348 , gre_name gre == name ]
349 ; case gres of
350 [gre] -> return (Right (gre_name gre))
351
352 [] -> -- See Note [Splicing Exact names]
353 do { lcl_env <- getLocalRdrEnv
354 ; if name `inLocalRdrEnvScope` lcl_env
355 then return (Right name)
356 else
357 #ifdef GHCI
358 do { th_topnames_var <- fmap tcg_th_topnames getGblEnv
359 ; th_topnames <- readTcRef th_topnames_var
360 ; if name `elemNameSet` th_topnames
361 then return (Right name)
362 else return (Left exact_nm_err)
363 }
364 #else /* !GHCI */
365 return (Left exact_nm_err)
366 #endif /* !GHCI */
367 }
368 gres -> return (Left (sameNameErr gres)) -- Ugh! See Note [Template Haskell ambiguity]
369 }
370 where
371 exact_nm_err = hang (ptext (sLit "The exact Name") <+> quotes (ppr name) <+> ptext (sLit "is not in scope"))
372 2 (vcat [ ptext (sLit "Probable cause: you used a unique Template Haskell name (NameU), ")
373 , ptext (sLit "perhaps via newName, but did not bind it")
374 , ptext (sLit "If that's it, then -ddump-splices might be useful") ])
375
376 sameNameErr :: [GlobalRdrElt] -> MsgDoc
377 sameNameErr [] = panic "addSameNameErr: empty list"
378 sameNameErr gres@(_ : _)
379 = hang (ptext (sLit "Same exact name in multiple name-spaces:"))
380 2 (vcat (map pp_one sorted_names) $$ th_hint)
381 where
382 sorted_names = sortWith nameSrcLoc (map gre_name gres)
383 pp_one name
384 = hang (pprNameSpace (occNameSpace (getOccName name))
385 <+> quotes (ppr name) <> comma)
386 2 (ptext (sLit "declared at:") <+> ppr (nameSrcLoc name))
387
388 th_hint = vcat [ ptext (sLit "Probable cause: you bound a unique Template Haskell name (NameU),")
389 , ptext (sLit "perhaps via newName, in different name-spaces.")
390 , ptext (sLit "If that's it, then -ddump-splices might be useful") ]
391
392
393 -----------------------------------------------
394 lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name
395 -- This is called on the method name on the left-hand side of an
396 -- instance declaration binding. eg. instance Functor T where
397 -- fmap = ...
398 -- ^^^^ called on this
399 -- Regardless of how many unqualified fmaps are in scope, we want
400 -- the one that comes from the Functor class.
401 --
402 -- Furthermore, note that we take no account of whether the
403 -- name is only in scope qualified. I.e. even if method op is
404 -- in scope as M.op, we still allow plain 'op' on the LHS of
405 -- an instance decl
406 --
407 -- The "what" parameter says "method" or "associated type",
408 -- depending on what we are looking up
409 lookupInstDeclBndr cls what rdr
410 = do { when (isQual rdr)
411 (addErr (badQualBndrErr rdr))
412 -- In an instance decl you aren't allowed
413 -- to use a qualified name for the method
414 -- (Although it'd make perfect sense.)
415 ; lookupSubBndrOcc False -- False => we don't give deprecated
416 -- warnings when a deprecated class
417 -- method is defined. We only warn
418 -- when it's used
419 (Just cls) doc rdr }
420 where
421 doc = what <+> ptext (sLit "of class") <+> quotes (ppr cls)
422
423
424 -----------------------------------------------
425 lookupFamInstName :: Maybe Name -> Located RdrName -> RnM (Located Name)
426 -- Used for TyData and TySynonym family instances only,
427 -- See Note [Family instance binders]
428 lookupFamInstName (Just cls) tc_rdr -- Associated type; c.f RnBinds.rnMethodBind
429 = wrapLocM (lookupInstDeclBndr cls (ptext (sLit "associated type"))) tc_rdr
430 lookupFamInstName Nothing tc_rdr -- Family instance; tc_rdr is an *occurrence*
431 = lookupLocatedOccRn tc_rdr
432
433 -----------------------------------------------
434 lookupConstructorFields :: Name -> RnM [FieldLabel]
435 -- Look up the fields of a given constructor
436 -- * For constructors from this module, use the record field env,
437 -- which is itself gathered from the (as yet un-typechecked)
438 -- data type decls
439 --
440 -- * For constructors from imported modules, use the *type* environment
441 -- since imported modles are already compiled, the info is conveniently
442 -- right there
443
444 lookupConstructorFields con_name
445 = do { this_mod <- getModule
446 ; if nameIsLocalOrFrom this_mod con_name then
447 do { field_env <- getRecFieldEnv
448 ; return (lookupNameEnv field_env con_name `orElse` []) }
449 else
450 do { con <- tcLookupDataCon con_name
451 ; return (dataConFieldLabels con) } }
452
453 -----------------------------------------------
454 -- Used for record construction and pattern matching
455 -- When the -XDisambiguateRecordFields flag is on, take account of the
456 -- constructor name to disambiguate which field to use; it's just the
457 -- same as for instance decls
458 --
459 -- NB: Consider this:
460 -- module Foo where { data R = R { fld :: Int } }
461 -- module Odd where { import Foo; fld x = x { fld = 3 } }
462 -- Arguably this should work, because the reference to 'fld' is
463 -- unambiguous because there is only one field id 'fld' in scope.
464 -- But currently it's rejected.
465 lookupSubBndrOcc :: Bool
466 -> Maybe Name -- Nothing => just look it up as usual
467 -- Just p => use parent p to disambiguate
468 -> SDoc -> RdrName
469 -> RnM Name
470 lookupSubBndrOcc warnIfDeprec parent doc rdr_name
471 | Just n <- isExact_maybe rdr_name -- This happens in derived code
472 = lookupExactOcc n
473
474 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
475 = lookupOrig rdr_mod rdr_occ
476
477 | otherwise -- Find all the things the rdr-name maps to
478 = do { -- and pick the one with the right parent namep
479 env <- getGlobalRdrEnv
480 ; case lookupSubBndrGREs env parent rdr_name of
481 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
482 -- The latter does pickGREs, but we want to allow 'x'
483 -- even if only 'M.x' is in scope
484 [gre] -> do { addUsedGRE warnIfDeprec gre
485 -- Add a usage; this is an *occurrence* site
486 -- Note [Usage for sub-bndrs]
487 ; return (gre_name gre) }
488 [] -> do { ns <- lookupQualifiedNameGHCi rdr_name
489 ; case ns of {
490 (n:_) -> return n ;
491 -- Unlikely to be more than one...?
492 [] -> do
493 { addErr (unknownSubordinateErr doc rdr_name)
494 ; return (mkUnboundName rdr_name) } } }
495 gres -> do { addNameClashErrRn rdr_name gres
496 ; return (gre_name (head gres)) } }
497
498 lookupSubBndrGREs :: GlobalRdrEnv -> Maybe Name -> RdrName -> [GlobalRdrElt]
499 -- If parent = Nothing, just do a normal lookup
500 -- If parent = Just p then find all GREs that
501 -- (a) have parent p
502 -- (b) for Unqual, are in scope qualified or unqualified
503 -- for Qual, are in scope with that qualification
504 lookupSubBndrGREs env parent rdr_name
505 = case parent of
506 Nothing -> pickGREs rdr_name gres
507 Just p
508 | isUnqual rdr_name -> filter (parent_is p) gres
509 | otherwise -> filter (parent_is p) (pickGREs rdr_name gres)
510
511 where
512 gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
513
514 parent_is p (GRE { gre_par = ParentIs p' }) = p == p'
515 parent_is p (GRE { gre_par = FldParent { par_is = p'}}) = p == p'
516 parent_is _ _ = False
517
518 {-
519 Note [Family instance binders]
520 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
521 Consider
522 data family F a
523 data instance F T = X1 | X2
524
525 The 'data instance' decl has an *occurrence* of F (and T), and *binds*
526 X1 and X2. (This is unlike a normal data type declaration which would
527 bind F too.) So we want an AvailTC F [X1,X2].
528
529 Now consider a similar pair:
530 class C a where
531 data G a
532 instance C S where
533 data G S = Y1 | Y2
534
535 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.
536
537 But there is a small complication: in an instance decl, we don't use
538 qualified names on the LHS; instead we use the class to disambiguate.
539 Thus:
540 module M where
541 import Blib( G )
542 class C a where
543 data G a
544 instance C S where
545 data G S = Y1 | Y2
546 Even though there are two G's in scope (M.G and Blib.G), the occurrence
547 of 'G' in the 'instance C S' decl is unambiguous, because C has only
548 one associated type called G. This is exactly what happens for methods,
549 and it is only consistent to do the same thing for types. That's the
550 role of the function lookupTcdName; the (Maybe Name) give the class of
551 the encloseing instance decl, if any.
552
553 Note [Looking up Exact RdrNames]
554 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
555 Exact RdrNames are generated by Template Haskell. See Note [Binders
556 in Template Haskell] in Convert.
557
558 For data types and classes have Exact system Names in the binding
559 positions for constructors, TyCons etc. For example
560 [d| data T = MkT Int |]
561 when we splice in and Convert to HsSyn RdrName, we'll get
562 data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
563 These System names are generated by Convert.thRdrName
564
565 But, constructors and the like need External Names, not System Names!
566 So we do the following
567
568 * In RnEnv.newTopSrcBinder we spot Exact RdrNames that wrap a
569 non-External Name, and make an External name for it. This is
570 the name that goes in the GlobalRdrEnv
571
572 * When looking up an occurrence of an Exact name, done in
573 RnEnv.lookupExactOcc, we find the Name with the right unique in the
574 GlobalRdrEnv, and use the one from the envt -- it will be an
575 External Name in the case of the data type/constructor above.
576
577 * Exact names are also use for purely local binders generated
578 by TH, such as \x_33. x_33
579 Both binder and occurrence are Exact RdrNames. The occurrence
580 gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and
581 misses, because lookupLocalRdrEnv always returns Nothing for
582 an Exact Name. Now we fall through to lookupExactOcc, which
583 will find the Name is not in the GlobalRdrEnv, so we just use
584 the Exact supplied Name.
585
586 Note [Splicing Exact names]
587 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
588 Consider the splice $(do { x <- newName "x"; return (VarE x) })
589 This will generate a (HsExpr RdrName) term that mentions the
590 Exact RdrName "x_56" (or whatever), but does not bind it. So
591 when looking such Exact names we want to check that it's in scope,
592 otherwise the type checker will get confused. To do this we need to
593 keep track of all the Names in scope, and the LocalRdrEnv does just that;
594 we consult it with RdrName.inLocalRdrEnvScope.
595
596 There is another wrinkle. With TH and -XDataKinds, consider
597 $( [d| data Nat = Zero
598 data T = MkT (Proxy 'Zero) |] )
599 After splicing, but before renaming we get this:
600 data Nat_77{tc} = Zero_78{d}
601 data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] )
602 The occurrence of 'Zero in the data type for T has the right unique,
603 but it has a TcClsName name-space in its OccName. (This is set by
604 the ctxt_ns argument of Convert.thRdrName.) When we check that is
605 in scope in the GlobalRdrEnv, we need to look up the DataName namespace
606 too. (An alternative would be to make the GlobalRdrEnv also have
607 a Name -> GRE mapping.)
608
609 Note [Template Haskell ambiguity]
610 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
611 The GlobalRdrEnv invariant says that if
612 occ -> [gre1, ..., gren]
613 then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv).
614 This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre).
615
616 So how can we get multiple gres in lookupExactOcc_maybe? Because in
617 TH we might use the same TH NameU in two different name spaces.
618 eg (Trac #7241):
619 $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
620 Here we generate a type constructor and data constructor with the same
621 unique, but differnt name spaces.
622
623 It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would
624 mean looking up the OccName in every name-space, just in case, and that
625 seems a bit brutal. So it's just done here on lookup. But we might
626 need to revisit that choice.
627
628 Note [Usage for sub-bndrs]
629 ~~~~~~~~~~~~~~~~~~~~~~~~~~
630 If you have this
631 import qualified M( C( f ) )
632 instance M.C T where
633 f x = x
634 then is the qualified import M.f used? Obviously yes.
635 But the RdrName used in the instance decl is unqualified. In effect,
636 we fill in the qualification by looking for f's whose class is M.C
637 But when adding to the UsedRdrNames we must make that qualification
638 explicit (saying "used M.f"), otherwise we get "Redundant import of M.f".
639
640 So we make up a suitable (fake) RdrName. But be careful
641 import qualifed M
642 import M( C(f) )
643 instance C T where
644 f x = x
645 Here we want to record a use of 'f', not of 'M.f', otherwise
646 we'll miss the fact that the qualified import is redundant.
647
648 --------------------------------------------------
649 -- Occurrences
650 --------------------------------------------------
651 -}
652
653 getLookupOccRn :: RnM (Name -> Maybe Name)
654 getLookupOccRn
655 = do local_env <- getLocalRdrEnv
656 return (lookupLocalRdrOcc local_env . nameOccName)
657
658 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
659 lookupLocatedOccRn = wrapLocM lookupOccRn
660
661 lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
662 -- Just look in the local environment
663 lookupLocalOccRn_maybe rdr_name
664 = do { local_env <- getLocalRdrEnv
665 ; return (lookupLocalRdrEnv local_env rdr_name) }
666
667 lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel))
668 -- Just look in the local environment
669 lookupLocalOccThLvl_maybe name
670 = do { lcl_env <- getLclEnv
671 ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) }
672
673 -- lookupOccRn looks up an occurrence of a RdrName
674 lookupOccRn :: RdrName -> RnM Name
675 lookupOccRn rdr_name
676 = do { mb_name <- lookupOccRn_maybe rdr_name
677 ; case mb_name of
678 Just name -> return name
679 Nothing -> reportUnboundName rdr_name }
680
681 lookupKindOccRn :: RdrName -> RnM Name
682 -- Looking up a name occurring in a kind
683 lookupKindOccRn rdr_name
684 = do { mb_name <- lookupOccRn_maybe rdr_name
685 ; case mb_name of
686 Just name -> return name
687 Nothing -> reportUnboundName rdr_name }
688
689 -- lookupPromotedOccRn looks up an optionally promoted RdrName.
690 lookupTypeOccRn :: RdrName -> RnM Name
691 -- see Note [Demotion]
692 lookupTypeOccRn rdr_name
693 = do { mb_name <- lookupOccRn_maybe rdr_name
694 ; case mb_name of {
695 Just name -> return name ;
696 Nothing -> lookup_demoted rdr_name } }
697
698 lookup_demoted :: RdrName -> RnM Name
699 lookup_demoted rdr_name
700 | Just demoted_rdr <- demoteRdrName rdr_name
701 -- Maybe it's the name of a *data* constructor
702 = do { data_kinds <- xoptM Opt_DataKinds
703 ; mb_demoted_name <- lookupOccRn_maybe demoted_rdr
704 ; case mb_demoted_name of
705 Nothing -> reportUnboundName rdr_name
706 Just demoted_name
707 | data_kinds ->
708 do { whenWOptM Opt_WarnUntickedPromotedConstructors $
709 addWarn (untickedPromConstrWarn demoted_name)
710 ; return demoted_name }
711 | otherwise -> unboundNameX WL_Any rdr_name suggest_dk }
712
713 | otherwise
714 = reportUnboundName rdr_name
715
716 where
717 suggest_dk = ptext (sLit "A data constructor of that name is in scope; did you mean DataKinds?")
718 untickedPromConstrWarn name =
719 text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
720 $$
721 hsep [ text "Use"
722 , quotes (char '\'' <> ppr name)
723 , text "instead of"
724 , quotes (ppr name) <> dot ]
725
726 {-
727 Note [Demotion]
728 ~~~~~~~~~~~~~~~
729 When the user writes:
730 data Nat = Zero | Succ Nat
731 foo :: f Zero -> Int
732
733 'Zero' in the type signature of 'foo' is parsed as:
734 HsTyVar ("Zero", TcClsName)
735
736 When the renamer hits this occurrence of 'Zero' it's going to realise
737 that it's not in scope. But because it is renaming a type, it knows
738 that 'Zero' might be a promoted data constructor, so it will demote
739 its namespace to DataName and do a second lookup.
740
741 The final result (after the renamer) will be:
742 HsTyVar ("Zero", DataName)
743 -}
744
745 -- Use this version to get tracing
746 --
747 -- lookupOccRn_maybe, lookupOccRn_maybe' :: RdrName -> RnM (Maybe Name)
748 -- lookupOccRn_maybe rdr_name
749 -- = do { mb_res <- lookupOccRn_maybe' rdr_name
750 -- ; gbl_rdr_env <- getGlobalRdrEnv
751 -- ; local_rdr_env <- getLocalRdrEnv
752 -- ; traceRn $ text "lookupOccRn_maybe" <+>
753 -- vcat [ ppr rdr_name <+> ppr (getUnique (rdrNameOcc rdr_name))
754 -- , ppr mb_res
755 -- , text "Lcl env" <+> ppr local_rdr_env
756 -- , text "Gbl env" <+> ppr [ (getUnique (nameOccName (gre_name (head gres'))),gres') | gres <- occEnvElts gbl_rdr_env
757 -- , let gres' = filter isLocalGRE gres, not (null gres') ] ]
758 -- ; return mb_res }
759
760 lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
761 -- lookupOccRn looks up an occurrence of a RdrName
762 lookupOccRn_maybe rdr_name
763 = do { local_env <- getLocalRdrEnv
764 ; case lookupLocalRdrEnv local_env rdr_name of {
765 Just name -> return (Just name) ;
766 Nothing -> do
767 { mb_name <- lookupGlobalOccRn_maybe rdr_name
768 ; case mb_name of {
769 Just name -> return (Just name) ;
770 Nothing -> do
771 { ns <- lookupQualifiedNameGHCi rdr_name
772 -- This test is not expensive,
773 -- and only happens for failed lookups
774 ; case ns of
775 (n:_) -> return (Just n) -- Unlikely to be more than one...?
776 [] -> return Nothing } } } } }
777
778 lookupGlobalOccRn :: RdrName -> RnM Name
779 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
780 -- environment. Adds an error message if the RdrName is not in scope.
781 lookupGlobalOccRn rdr_name
782 = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
783 ; case mb_name of
784 Just n -> return n
785 Nothing -> do { traceRn (text "lookupGlobalOccRn" <+> ppr rdr_name)
786 ; unboundName WL_Global rdr_name } }
787
788 lookupInfoOccRn :: RdrName -> RnM [Name]
789 -- lookupInfoOccRn is intended for use in GHCi's ":info" command
790 -- It finds all the GREs that RdrName could mean, not complaining
791 -- about ambiguity, but rather returning them all
792 -- C.f. Trac #9881
793 lookupInfoOccRn rdr_name
794 | Just n <- isExact_maybe rdr_name -- e.g. (->)
795 = return [n]
796
797 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
798 = do { n <- lookupOrig rdr_mod rdr_occ
799 ; return [n] }
800
801 | otherwise
802 = do { rdr_env <- getGlobalRdrEnv
803 ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
804 ; qual_ns <- lookupQualifiedNameGHCi rdr_name
805 ; return (ns ++ (qual_ns `minusList` ns)) }
806
807 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
808 -- No filter function; does not report an error on failure
809
810 lookupGlobalOccRn_maybe rdr_name
811 | Just n <- isExact_maybe rdr_name -- This happens in derived code
812 = do { n' <- lookupExactOcc n; return (Just n') }
813
814 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
815 = do { n <- lookupOrig rdr_mod rdr_occ
816 ; return (Just n) }
817
818 | otherwise
819 = do { mb_gre <- lookupGreRn_maybe rdr_name
820 ; case mb_gre of
821 Nothing -> return Nothing
822 Just gre -> return (Just (gre_name gre)) }
823
824
825 -- | Like 'lookupOccRn_maybe', but with a more informative result if
826 -- the 'RdrName' happens to be a record selector:
827 --
828 -- * Nothing -> name not in scope (no error reported)
829 -- * Just (Left x) -> name uniquely refers to x,
830 -- or there is a name clash (reported)
831 -- * Just (Right xs) -> name refers to one or more record selectors;
832 -- if overload_ok was False, this list will be
833 -- a singleton.
834 lookupOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [FieldOcc Name]))
835 lookupOccRn_overloaded overload_ok rdr_name
836 = do { local_env <- getLocalRdrEnv
837 ; case lookupLocalRdrEnv local_env rdr_name of {
838 Just name -> return (Just (Left name)) ;
839 Nothing -> do
840 { mb_name <- lookupGlobalOccRn_overloaded overload_ok rdr_name
841 ; case mb_name of {
842 Just name -> return (Just name) ;
843 Nothing -> do
844 { ns <- lookupQualifiedNameGHCi rdr_name
845 -- This test is not expensive,
846 -- and only happens for failed lookups
847 ; case ns of
848 (n:_) -> return $ Just $ Left n -- Unlikely to be more than one...?
849 [] -> return Nothing } } } } }
850
851 lookupGlobalOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [FieldOcc Name]))
852 lookupGlobalOccRn_overloaded overload_ok rdr_name
853 | Just n <- isExact_maybe rdr_name -- This happens in derived code
854 = do { n' <- lookupExactOcc n; return (Just (Left n')) }
855
856 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
857 = do { n <- lookupOrig rdr_mod rdr_occ
858 ; return (Just (Left n)) }
859
860 | otherwise
861 = do { env <- getGlobalRdrEnv
862 ; case lookupGRE_RdrName rdr_name env of
863 [] -> return Nothing
864 [gre] | isRecFldGRE gre
865 -> do { addUsedGRE True gre
866 ; let fld_occ = FieldOcc rdr_name (gre_name gre)
867 ; return (Just (Right [fld_occ])) }
868 | otherwise
869 -> do { addUsedGRE True gre
870 ; return (Just (Left (gre_name gre))) }
871 gres | all isRecFldGRE gres && overload_ok
872 -- Don't record usage for ambiguous selectors
873 -- until we know which is meant
874 -> return (Just (Right (map (FieldOcc rdr_name . gre_name) gres)))
875 gres -> do { addNameClashErrRn rdr_name gres
876 ; return (Just (Left (gre_name (head gres)))) } }
877
878
879 --------------------------------------------------
880 -- Lookup in the Global RdrEnv of the module
881 --------------------------------------------------
882
883 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
884 -- Look up the RdrName in the GlobalRdrEnv
885 -- Exactly one binding: records it as "used", return (Just gre)
886 -- No bindings: return Nothing
887 -- Many bindings: report "ambiguous", return an arbitrary (Just gre)
888 -- (This API is a bit strange; lookupGRERn2_maybe is simpler.
889 -- But it works and I don't want to fiddle too much.)
890 lookupGreRn_maybe rdr_name
891 = do { env <- getGlobalRdrEnv
892 ; case lookupGRE_RdrName rdr_name env of
893 [] -> return Nothing
894 [gre] -> do { addUsedGRE True gre
895 ; return (Just gre) }
896 gres -> do { addNameClashErrRn rdr_name gres
897 ; traceRn (text "name clash" <+> (ppr rdr_name $$ ppr gres $$ ppr env))
898 ; return (Just (head gres)) } }
899
900 lookupGreRn2_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
901 -- Look up the RdrName in the GlobalRdrEnv
902 -- Exactly one binding: record it as "used", return (Just gre)
903 -- No bindings: report "not in scope", return Nothing
904 -- Many bindings: report "ambiguous", return Nothing
905 lookupGreRn2_maybe rdr_name
906 = do { env <- getGlobalRdrEnv
907 ; case lookupGRE_RdrName rdr_name env of
908 [] -> do { _ <- unboundName WL_Global rdr_name
909 ; return Nothing }
910 [gre] -> do { addUsedGRE True gre
911 ; return (Just gre) }
912 gres -> do { addNameClashErrRn rdr_name gres
913 ; traceRn (text "name clash" <+> (ppr rdr_name $$ ppr gres $$ ppr env))
914 ; return Nothing } }
915
916 lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
917 -- Used in export lists
918 -- If not found or ambiguous, add error message, and fake with UnboundName
919 lookupGreAvailRn rdr_name
920 = do { mb_gre <- lookupGreRn2_maybe rdr_name
921 ; case mb_gre of {
922 Just gre -> return (gre_name gre, availFromGRE gre) ;
923 Nothing ->
924 do { traceRn (text "lookupGreRn" <+> ppr rdr_name)
925 ; let name = mkUnboundName rdr_name
926 ; return (name, avail name) } } }
927
928 {-
929 *********************************************************
930 * *
931 Deprecations
932 * *
933 *********************************************************
934
935 Note [Handling of deprecations]
936 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
937 * We report deprecations at each *occurrence* of the deprecated thing
938 (see Trac #5867)
939
940 * We do not report deprecations for locally-defined names. For a
941 start, we may be exporting a deprecated thing. Also we may use a
942 deprecated thing in the defn of another deprecated things. We may
943 even use a deprecated thing in the defn of a non-deprecated thing,
944 when changing a module's interface.
945
946 * addUsedGREs: we do not report deprecations for sub-binders:
947 - the ".." completion for records
948 - the ".." in an export item 'T(..)'
949 - the things exported by a module export 'module M'
950 -}
951
952 addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM ()
953 -- Remember use of in-scope data constructors (Trac #7969)
954 addUsedDataCons rdr_env tycon
955 = addUsedGREs [ gre
956 | dc <- tyConDataCons tycon
957 , gre : _ <- [lookupGRE_Name rdr_env (dataConName dc) ] ]
958
959 addUsedGRE :: Bool -> GlobalRdrElt -> RnM ()
960 -- Called for both local and imported things
961 -- Add usage *and* warn if deprecated
962 addUsedGRE warn_if_deprec gre
963 = do { when warn_if_deprec (warnIfDeprecated gre)
964 ; unless (isLocalGRE gre) $
965 do { env <- getGblEnv
966 ; traceRn (text "addUsedGRE" <+> ppr gre)
967 ; updMutVar (tcg_used_gres env) (gre :) } }
968
969 addUsedGREs :: [GlobalRdrElt] -> RnM ()
970 -- Record uses of any *imported* GREs
971 -- Used for recording used sub-bndrs
972 -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
973 addUsedGREs gres
974 | null imp_gres = return ()
975 | otherwise = do { env <- getGblEnv
976 ; traceRn (text "addUsedGREs" <+> ppr imp_gres)
977 ; updMutVar (tcg_used_gres env) (imp_gres ++) }
978 where
979 imp_gres = filterOut isLocalGRE gres
980
981 warnIfDeprecated :: GlobalRdrElt -> RnM ()
982 warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss })
983 | (imp_spec : _) <- iss
984 = do { dflags <- getDynFlags
985 ; this_mod <- getModule
986 ; when (wopt Opt_WarnWarningsDeprecations dflags &&
987 not (nameIsLocalOrFrom this_mod name)) $
988 -- See Note [Handling of deprecations]
989 do { iface <- loadInterfaceForName doc name
990 ; case lookupImpDeprec iface gre of
991 Just txt -> addWarn (mk_msg imp_spec txt)
992 Nothing -> return () } }
993 | otherwise
994 = return ()
995 where
996 occ = greOccName gre
997 name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
998 doc = ptext (sLit "The name") <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly")
999
1000 mk_msg imp_spec txt
1001 = sep [ sep [ ptext (sLit "In the use of")
1002 <+> pprNonVarNameSpace (occNameSpace occ)
1003 <+> quotes (ppr occ)
1004 , parens imp_msg <> colon ]
1005 , ppr txt ]
1006 where
1007 imp_mod = importSpecModule imp_spec
1008 imp_msg = ptext (sLit "imported from") <+> ppr imp_mod <> extra
1009 extra | imp_mod == moduleName name_mod = Outputable.empty
1010 | otherwise = ptext (sLit ", but defined in") <+> ppr name_mod
1011
1012 lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
1013 lookupImpDeprec iface gre
1014 = mi_warn_fn iface (gre_name gre) `mplus` -- Bleat if the thing,
1015 case gre_par gre of -- or its parent, is warn'd
1016 ParentIs p -> mi_warn_fn iface p
1017 FldParent { par_is = p } -> mi_warn_fn iface p
1018 NoParent -> Nothing
1019 PatternSynonym -> Nothing
1020
1021 {-
1022 Note [Used names with interface not loaded]
1023 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1024 It's (just) possible to find a used
1025 Name whose interface hasn't been loaded:
1026
1027 a) It might be a WiredInName; in that case we may not load
1028 its interface (although we could).
1029
1030 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1031 These are seen as "used" by the renamer (if -XRebindableSyntax)
1032 is on), but the typechecker may discard their uses
1033 if in fact the in-scope fromRational is GHC.Read.fromRational,
1034 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1035 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1036 In that obscure case it won't force the interface in.
1037
1038 In both cases we simply don't permit deprecations;
1039 this is, after all, wired-in stuff.
1040
1041
1042 *********************************************************
1043 * *
1044 GHCi support
1045 * *
1046 *********************************************************
1047
1048 A qualified name on the command line can refer to any module at
1049 all: we try to load the interface if we don't already have it, just
1050 as if there was an "import qualified M" declaration for every
1051 module.
1052
1053 If we fail we just return Nothing, rather than bleating
1054 about "attempting to use module ā€˜Dā€™ (./D.hs) which is not loaded"
1055 which is what loadSrcInterface does.
1056
1057 Note [Safe Haskell and GHCi]
1058 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1059 We DONT do this Safe Haskell as we need to check imports. We can
1060 and should instead check the qualified import but at the moment
1061 this requires some refactoring so leave as a TODO
1062 -}
1063
1064 lookupQualifiedNameGHCi :: RdrName -> RnM [Name]
1065 lookupQualifiedNameGHCi rdr_name
1066 = -- We want to behave as we would for a source file import here,
1067 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
1068 do { dflags <- getDynFlags
1069 ; is_ghci <- getIsGHCi
1070 ; go_for_it dflags is_ghci }
1071
1072 where
1073 go_for_it dflags is_ghci
1074 | Just (mod,occ) <- isQual_maybe rdr_name
1075 , is_ghci
1076 , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour
1077 , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi]
1078 = do { res <- loadSrcInterface_maybe doc mod False Nothing
1079 ; case res of
1080 Succeeded iface
1081 -> return [ name
1082 | avail <- mi_exports iface
1083 , name <- availNames avail
1084 , nameOccName name == occ ]
1085
1086 _ -> -- Either we couldn't load the interface, or
1087 -- we could but we didn't find the name in it
1088 do { traceRn (text "lookupQualifiedNameGHCi" <+> ppr rdr_name)
1089 ; return [] } }
1090
1091 | otherwise
1092 = return []
1093
1094 doc = ptext (sLit "Need to find") <+> ppr rdr_name
1095
1096 {-
1097 Note [Looking up signature names]
1098 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1099 lookupSigOccRn is used for type signatures and pragmas
1100 Is this valid?
1101 module A
1102 import M( f )
1103 f :: Int -> Int
1104 f x = x
1105 It's clear that the 'f' in the signature must refer to A.f
1106 The Haskell98 report does not stipulate this, but it will!
1107 So we must treat the 'f' in the signature in the same way
1108 as the binding occurrence of 'f', using lookupBndrRn
1109
1110 However, consider this case:
1111 import M( f )
1112 f :: Int -> Int
1113 g x = x
1114 We don't want to say 'f' is out of scope; instead, we want to
1115 return the imported 'f', so that later on the reanamer will
1116 correctly report "misplaced type sig".
1117
1118 Note [Signatures for top level things]
1119 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1120 data HsSigCtxt = ... | TopSigCtxt NameSet | ....
1121
1122 * The NameSet says what is bound in this group of bindings.
1123 We can't use isLocalGRE from the GlobalRdrEnv, because of this:
1124 f x = x
1125 $( ...some TH splice... )
1126 f :: Int -> Int
1127 When we encounter the signature for 'f', the binding for 'f'
1128 will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
1129 signature is mis-placed
1130
1131 * For type signatures the NameSet should be the names bound by the
1132 value bindings; for fixity declarations, the NameSet should also
1133 include class sigs and record selectors
1134
1135 infix 3 `f` -- Yes, ok
1136 f :: C a => a -> a -- No, not ok
1137 class C a where
1138 f :: a -> a
1139 -}
1140
1141 data HsSigCtxt
1142 = TopSigCtxt NameSet -- At top level, binding these names
1143 -- See Note [Signatures for top level things]
1144 | LocalBindCtxt NameSet -- In a local binding, binding these names
1145 | ClsDeclCtxt Name -- Class decl for this class
1146 | InstDeclCtxt NameSet -- Instance decl whose user-written method
1147 -- bindings are for these methods
1148 | HsBootCtxt -- Top level of a hs-boot file
1149 | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types
1150 -- in the group
1151
1152 lookupSigOccRn :: HsSigCtxt
1153 -> Sig RdrName
1154 -> Located RdrName -> RnM (Located Name)
1155 lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
1156
1157 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
1158 lookupSigCtxtOccRn :: HsSigCtxt
1159 -> SDoc -- ^ description of thing we're looking up,
1160 -- like "type family"
1161 -> Located RdrName -> RnM (Located Name)
1162 lookupSigCtxtOccRn ctxt what
1163 = wrapLocM $ \ rdr_name ->
1164 do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
1165 ; case mb_name of
1166 Left err -> do { addErr err; return (mkUnboundName rdr_name) }
1167 Right name -> return name }
1168
1169 lookupBindGroupOcc :: HsSigCtxt
1170 -> SDoc
1171 -> RdrName -> RnM (Either MsgDoc Name)
1172 -- Looks up the RdrName, expecting it to resolve to one of the
1173 -- bound names passed in. If not, return an appropriate error message
1174 --
1175 -- See Note [Looking up signature names]
1176 lookupBindGroupOcc ctxt what rdr_name
1177 | Just n <- isExact_maybe rdr_name
1178 = lookupExactOcc_either n -- allow for the possibility of missing Exacts;
1179 -- see Note [dataTcOccs and Exact Names]
1180 -- Maybe we should check the side conditions
1181 -- but it's a pain, and Exact things only show
1182 -- up when you know what you are doing
1183
1184 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
1185 = do { n' <- lookupOrig rdr_mod rdr_occ
1186 ; return (Right n') }
1187
1188 | otherwise
1189 = case ctxt of
1190 HsBootCtxt -> lookup_top (const True)
1191 TopSigCtxt ns -> lookup_top (`elemNameSet` ns)
1192 RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns)
1193 LocalBindCtxt ns -> lookup_group ns
1194 ClsDeclCtxt cls -> lookup_cls_op cls
1195 InstDeclCtxt ns -> lookup_top (`elemNameSet` ns)
1196 where
1197 lookup_cls_op cls
1198 = do { env <- getGlobalRdrEnv
1199 ; let gres = lookupSubBndrGREs env (Just cls) rdr_name
1200 ; case gres of
1201 [] -> return (Left (unknownSubordinateErr doc rdr_name))
1202 (gre:_) -> return (Right (gre_name gre)) }
1203 -- If there is more than one local GRE for the
1204 -- same OccName 'f', that will be reported separately
1205 -- as a duplicate top-level binding for 'f'
1206 where
1207 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
1208
1209 lookup_top keep_me
1210 = do { env <- getGlobalRdrEnv
1211 ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
1212 ; case filter (keep_me . gre_name) all_gres of
1213 [] | null all_gres -> bale_out_with Outputable.empty
1214 | otherwise -> bale_out_with local_msg
1215 (gre:_) -> return (Right (gre_name gre)) }
1216
1217 lookup_group bound_names -- Look in the local envt (not top level)
1218 = do { local_env <- getLocalRdrEnv
1219 ; case lookupLocalRdrEnv local_env rdr_name of
1220 Just n
1221 | n `elemNameSet` bound_names -> return (Right n)
1222 | otherwise -> bale_out_with local_msg
1223 Nothing -> bale_out_with Outputable.empty }
1224
1225 bale_out_with msg
1226 = return (Left (sep [ ptext (sLit "The") <+> what
1227 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
1228 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
1229 $$ nest 2 msg))
1230
1231 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
1232 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
1233
1234
1235 ---------------
1236 lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [Name]
1237 -- GHC extension: look up both the tycon and data con or variable.
1238 -- Used for top-level fixity signatures and deprecations.
1239 -- Complain if neither is in scope.
1240 -- See Note [Fixity signature lookup]
1241 lookupLocalTcNames ctxt what rdr_name
1242 = do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
1243 ; let (errs, names) = splitEithers mb_gres
1244 ; when (null names) $ addErr (head errs) -- Bleat about one only
1245 ; return names }
1246 where
1247 lookup = lookupBindGroupOcc ctxt what
1248
1249 dataTcOccs :: RdrName -> [RdrName]
1250 -- Return both the given name and the same name promoted to the TcClsName
1251 -- namespace. This is useful when we aren't sure which we are looking at.
1252 -- See also Note [dataTcOccs and Exact Names]
1253 dataTcOccs rdr_name
1254 | isDataOcc occ || isVarOcc occ
1255 = [rdr_name, rdr_name_tc]
1256 | otherwise
1257 = [rdr_name]
1258 where
1259 occ = rdrNameOcc rdr_name
1260 rdr_name_tc = setRdrNameSpace rdr_name tcName
1261
1262 {-
1263 Note [dataTcOccs and Exact Names]
1264 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1265 Exact RdrNames can occur in code generated by Template Haskell, and generally
1266 those references are, well, exact. However, the TH `Name` type isn't expressive
1267 enough to always track the correct namespace information, so we sometimes get
1268 the right Unique but wrong namespace. Thus, we still have to do the double-lookup
1269 for Exact RdrNames.
1270
1271 There is also an awkward situation for built-in syntax. Example in GHCi
1272 :info []
1273 This parses as the Exact RdrName for nilDataCon, but we also want
1274 the list type constructor.
1275
1276 Note that setRdrNameSpace on an Exact name requires the Name to be External,
1277 which it always is for built in syntax.
1278
1279 *********************************************************
1280 * *
1281 Fixities
1282 * *
1283 *********************************************************
1284
1285 Note [Fixity signature lookup]
1286 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1287 A fixity declaration like
1288
1289 infixr 2 ?
1290
1291 can refer to a value-level operator, e.g.:
1292
1293 (?) :: String -> String -> String
1294
1295 or a type-level operator, like:
1296
1297 data (?) a b = A a | B b
1298
1299 so we extend the lookup of the reader name '?' to the TcClsName namespace, as
1300 well as the original namespace.
1301
1302 The extended lookup is also used in other places, like resolution of
1303 deprecation declarations, and lookup of names in GHCi.
1304 -}
1305
1306 --------------------------------
1307 type MiniFixityEnv = FastStringEnv (Located Fixity)
1308 -- Mini fixity env for the names we're about
1309 -- to bind, in a single binding group
1310 --
1311 -- It is keyed by the *FastString*, not the *OccName*, because
1312 -- the single fixity decl infix 3 T
1313 -- affects both the data constructor T and the type constrctor T
1314 --
1315 -- We keep the location so that if we find
1316 -- a duplicate, we can report it sensibly
1317
1318 --------------------------------
1319 -- Used for nested fixity decls to bind names along with their fixities.
1320 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
1321
1322 addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
1323 addLocalFixities mini_fix_env names thing_inside
1324 = extendFixityEnv (mapMaybe find_fixity names) thing_inside
1325 where
1326 find_fixity name
1327 = case lookupFsEnv mini_fix_env (occNameFS occ) of
1328 Just (L _ fix) -> Just (name, FixItem occ fix)
1329 Nothing -> Nothing
1330 where
1331 occ = nameOccName name
1332
1333 {-
1334 --------------------------------
1335 lookupFixity is a bit strange.
1336
1337 * Nested local fixity decls are put in the local fixity env, which we
1338 find with getFixtyEnv
1339
1340 * Imported fixities are found in the HIT or PIT
1341
1342 * Top-level fixity decls in this module may be for Names that are
1343 either Global (constructors, class operations)
1344 or Local/Exported (everything else)
1345 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
1346 We put them all in the local fixity environment
1347 -}
1348
1349 lookupFixityRn :: Name -> RnM Fixity
1350 lookupFixityRn name
1351 | isUnboundName name
1352 = return (Fixity minPrecedence InfixL)
1353 -- Minimise errors from ubound names; eg
1354 -- a>0 `foo` b>0
1355 -- where 'foo' is not in scope, should not give an error (Trac #7937)
1356
1357 | otherwise
1358 = do { local_fix_env <- getFixityEnv
1359 ; case lookupNameEnv local_fix_env name of {
1360 Just (FixItem _ fix) -> return fix ;
1361 Nothing ->
1362
1363 do { this_mod <- getModule
1364 ; if nameIsLocalOrFrom this_mod name
1365 -- Local (and interactive) names are all in the
1366 -- fixity env, and don't have entries in the HPT
1367 then return defaultFixity
1368 else lookup_imported } } }
1369 where
1370 lookup_imported
1371 -- For imported names, we have to get their fixities by doing a
1372 -- loadInterfaceForName, and consulting the Ifaces that comes back
1373 -- from that, because the interface file for the Name might not
1374 -- have been loaded yet. Why not? Suppose you import module A,
1375 -- which exports a function 'f', thus;
1376 -- module CurrentModule where
1377 -- import A( f )
1378 -- module A( f ) where
1379 -- import B( f )
1380 -- Then B isn't loaded right away (after all, it's possible that
1381 -- nothing from B will be used). When we come across a use of
1382 -- 'f', we need to know its fixity, and it's then, and only
1383 -- then, that we load B.hi. That is what's happening here.
1384 --
1385 -- loadInterfaceForName will find B.hi even if B is a hidden module,
1386 -- and that's what we want.
1387 = do { iface <- loadInterfaceForName doc name
1388 ; traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
1389 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)])
1390 ; return (mi_fix_fn iface (nameOccName name)) }
1391
1392 doc = ptext (sLit "Checking fixity for") <+> ppr name
1393
1394 ---------------
1395 lookupTyFixityRn :: Located Name -> RnM Fixity
1396 lookupTyFixityRn (L _ n) = lookupFixityRn n
1397
1398 {-
1399 ************************************************************************
1400 * *
1401 Rebindable names
1402 Dealing with rebindable syntax is driven by the
1403 Opt_RebindableSyntax dynamic flag.
1404
1405 In "deriving" code we don't want to use rebindable syntax
1406 so we switch off the flag locally
1407
1408 * *
1409 ************************************************************************
1410
1411 Haskell 98 says that when you say "3" you get the "fromInteger" from the
1412 Standard Prelude, regardless of what is in scope. However, to experiment
1413 with having a language that is less coupled to the standard prelude, we're
1414 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
1415 happens to be in scope. Then you can
1416 import Prelude ()
1417 import MyPrelude as Prelude
1418 to get the desired effect.
1419
1420 At the moment this just happens for
1421 * fromInteger, fromRational on literals (in expressions and patterns)
1422 * negate (in expressions)
1423 * minus (arising from n+k patterns)
1424 * "do" notation
1425
1426 We store the relevant Name in the HsSyn tree, in
1427 * HsIntegral/HsFractional/HsIsString
1428 * NegApp
1429 * NPlusKPat
1430 * HsDo
1431 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
1432 fromRationalName etc), but the renamer changes this to the appropriate user
1433 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
1434
1435 We treat the orignal (standard) names as free-vars too, because the type checker
1436 checks the type of the user thing against the type of the standard thing.
1437 -}
1438
1439 lookupIfThenElse :: RnM (Maybe (SyntaxExpr Name), FreeVars)
1440 -- Different to lookupSyntaxName because in the non-rebindable
1441 -- case we desugar directly rather than calling an existing function
1442 -- Hence the (Maybe (SyntaxExpr Name)) return type
1443 lookupIfThenElse
1444 = do { rebind <- xoptM Opt_RebindableSyntax
1445 ; if not rebind
1446 then return (Nothing, emptyFVs)
1447 else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
1448 ; return (Just (HsVar ite), unitFV ite) } }
1449
1450 lookupSyntaxName :: Name -- The standard name
1451 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
1452 lookupSyntaxName std_name
1453 = do { rebindable_on <- xoptM Opt_RebindableSyntax
1454 ; if not rebindable_on then
1455 return (HsVar std_name, emptyFVs)
1456 else
1457 -- Get the similarly named thing from the local environment
1458 do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name))
1459 ; return (HsVar usr_name, unitFV usr_name) } }
1460
1461 lookupSyntaxNames :: [Name] -- Standard names
1462 -> RnM ([HsExpr Name], FreeVars) -- See comments with HsExpr.ReboundNames
1463 lookupSyntaxNames std_names
1464 = do { rebindable_on <- xoptM Opt_RebindableSyntax
1465 ; if not rebindable_on then
1466 return (map HsVar std_names, emptyFVs)
1467 else
1468 do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names
1469 ; return (map HsVar usr_names, mkFVs usr_names) } }
1470
1471 {-
1472 *********************************************************
1473 * *
1474 \subsection{Binding}
1475 * *
1476 *********************************************************
1477 -}
1478
1479 newLocalBndrRn :: Located RdrName -> RnM Name
1480 -- Used for non-top-level binders. These should
1481 -- never be qualified.
1482 newLocalBndrRn (L loc rdr_name)
1483 | Just name <- isExact_maybe rdr_name
1484 = return name -- This happens in code generated by Template Haskell
1485 -- See Note [Binders in Template Haskell] in Convert.hs
1486 | otherwise
1487 = do { unless (isUnqual rdr_name)
1488 (addErrAt loc (badQualBndrErr rdr_name))
1489 ; uniq <- newUnique
1490 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
1491
1492 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
1493 newLocalBndrsRn = mapM newLocalBndrRn
1494
1495 ---------------------
1496 bindLocatedLocalsRn :: [Located RdrName]
1497 -> ([Name] -> RnM a)
1498 -> RnM a
1499 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
1500 = do { checkDupRdrNames rdr_names_w_loc
1501 ; checkShadowedRdrNames rdr_names_w_loc
1502
1503 -- Make fresh Names and extend the environment
1504 ; names <- newLocalBndrsRn rdr_names_w_loc
1505 ; bindLocalNames names (enclosed_scope names) }
1506
1507 bindLocalNames :: [Name] -> RnM a -> RnM a
1508 bindLocalNames names enclosed_scope
1509 = do { lcl_env <- getLclEnv
1510 ; let th_level = thLevel (tcl_th_ctxt lcl_env)
1511 th_bndrs' = extendNameEnvList (tcl_th_bndrs lcl_env)
1512 [ (n, (NotTopLevel, th_level)) | n <- names ]
1513 rdr_env' = extendLocalRdrEnvList (tcl_rdr lcl_env) names
1514 ; setLclEnv (lcl_env { tcl_th_bndrs = th_bndrs'
1515 , tcl_rdr = rdr_env' })
1516 enclosed_scope }
1517
1518 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
1519 bindLocalNamesFV names enclosed_scope
1520 = do { (result, fvs) <- bindLocalNames names enclosed_scope
1521 ; return (result, delFVs names fvs) }
1522
1523
1524 -------------------------------------
1525 -- binLocalsFVRn is the same as bindLocalsRn
1526 -- except that it deals with free vars
1527 bindLocatedLocalsFV :: [Located RdrName]
1528 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
1529 bindLocatedLocalsFV rdr_names enclosed_scope
1530 = bindLocatedLocalsRn rdr_names $ \ names ->
1531 do (thing, fvs) <- enclosed_scope names
1532 return (thing, delFVs names fvs)
1533
1534 -------------------------------------
1535
1536 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
1537 -- This function is used only in rnSourceDecl on InstDecl
1538 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
1539
1540 -------------------------------------
1541 checkDupRdrNames :: [Located RdrName] -> RnM ()
1542 -- Check for duplicated names in a binding group
1543 checkDupRdrNames rdr_names_w_loc
1544 = mapM_ (dupNamesErr getLoc) dups
1545 where
1546 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
1547
1548 checkDupNames :: [Name] -> RnM ()
1549 -- Check for duplicated names in a binding group
1550 checkDupNames names = check_dup_names (filterOut isSystemName names)
1551 -- See Note [Binders in Template Haskell] in Convert
1552
1553 check_dup_names :: [Name] -> RnM ()
1554 check_dup_names names
1555 = mapM_ (dupNamesErr nameSrcSpan) dups
1556 where
1557 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
1558
1559 ---------------------
1560 checkShadowedRdrNames :: [Located RdrName] -> RnM ()
1561 checkShadowedRdrNames loc_rdr_names
1562 = do { envs <- getRdrEnvs
1563 ; checkShadowedOccs envs get_loc_occ filtered_rdrs }
1564 where
1565 filtered_rdrs = filterOut (isExact . unLoc) loc_rdr_names
1566 -- See Note [Binders in Template Haskell] in Convert
1567 get_loc_occ (L loc rdr) = (loc,rdrNameOcc rdr)
1568
1569 checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
1570 checkDupAndShadowedNames envs names
1571 = do { check_dup_names filtered_names
1572 ; checkShadowedOccs envs get_loc_occ filtered_names }
1573 where
1574 filtered_names = filterOut isSystemName names
1575 -- See Note [Binders in Template Haskell] in Convert
1576 get_loc_occ name = (nameSrcSpan name, nameOccName name)
1577
1578 -------------------------------------
1579 checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv)
1580 -> (a -> (SrcSpan, OccName))
1581 -> [a] -> RnM ()
1582 checkShadowedOccs (global_env,local_env) get_loc_occ ns
1583 = whenWOptM Opt_WarnNameShadowing $
1584 do { traceRn (text "shadow" <+> ppr (map get_loc_occ ns))
1585 ; mapM_ check_shadow ns }
1586 where
1587 check_shadow n
1588 | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
1589 -- See Trac #3262
1590 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
1591 | otherwise = do { gres' <- filterM is_shadowed_gre gres
1592 ; complain (map pprNameProvenance gres') }
1593 where
1594 (loc,occ) = get_loc_occ n
1595 mb_local = lookupLocalRdrOcc local_env occ
1596 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
1597 -- Make an Unqualified RdrName and look that up, so that
1598 -- we don't find any GREs that are in scope qualified-only
1599
1600 complain [] = return ()
1601 complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
1602
1603 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
1604 -- Returns False for record selectors that are shadowed, when
1605 -- punning or wild-cards are on (cf Trac #2723)
1606 is_shadowed_gre gre | isRecFldGRE gre
1607 = do { dflags <- getDynFlags
1608 ; return $ not (xopt Opt_RecordPuns dflags || xopt Opt_RecordWildCards dflags) }
1609 is_shadowed_gre _other = return True
1610
1611 {-
1612 ************************************************************************
1613 * *
1614 What to do when a lookup fails
1615 * *
1616 ************************************************************************
1617 -}
1618
1619 data WhereLooking = WL_Any -- Any binding
1620 | WL_Global -- Any top-level binding (local or imported)
1621 | WL_LocalTop -- Any top-level binding in this module
1622
1623 reportUnboundName :: RdrName -> RnM Name
1624 reportUnboundName rdr = unboundName WL_Any rdr
1625
1626 unboundName :: WhereLooking -> RdrName -> RnM Name
1627 unboundName wl rdr = unboundNameX wl rdr Outputable.empty
1628
1629 unboundNameX :: WhereLooking -> RdrName -> SDoc -> RnM Name
1630 unboundNameX where_look rdr_name extra
1631 = do { dflags <- getDynFlags
1632 ; let show_helpful_errors = gopt Opt_HelpfulErrors dflags
1633 what = pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1634 err = unknownNameErr what rdr_name $$ extra
1635 ; if not show_helpful_errors
1636 then addErr err
1637 else do { local_env <- getLocalRdrEnv
1638 ; global_env <- getGlobalRdrEnv
1639 ; impInfo <- getImports
1640 ; let suggestions1 = unknownNameSuggestions_ where_look
1641 dflags global_env local_env rdr_name
1642 ; let suggestions2 = importSuggestions dflags impInfo rdr_name
1643 ; addErr (err $$ suggestions1 $$ suggestions2) }
1644 ; return (mkUnboundName rdr_name) }
1645
1646 unknownNameErr :: SDoc -> RdrName -> SDoc
1647 unknownNameErr what rdr_name
1648 = vcat [ hang (ptext (sLit "Not in scope:"))
1649 2 (what <+> quotes (ppr rdr_name))
1650 , extra ]
1651 where
1652 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1653 | otherwise = Outputable.empty
1654
1655 type HowInScope = Either SrcSpan ImpDeclSpec
1656 -- Left loc => locally bound at loc
1657 -- Right ispec => imported as specified by ispec
1658
1659 -- | Generate helpful suggestions if a qualified name Mod.foo is not in scope.
1660 importSuggestions :: DynFlags -> ImportAvails -> RdrName -> SDoc
1661 importSuggestions _dflags imports rdr_name
1662 | not (isQual rdr_name) = Outputable.empty
1663 | null interesting_imports
1664 = hsep
1665 [ ptext (sLit "No module named")
1666 , quotes (ppr mod_name)
1667 , ptext (sLit "is imported.")
1668 ]
1669 | null helpful_imports
1670 , [(mod,_)] <- interesting_imports
1671 = hsep
1672 [ ptext (sLit "Module")
1673 , quotes (ppr mod)
1674 , ptext (sLit "does not export")
1675 , quotes (ppr occ_name) <> dot
1676 ]
1677 | null helpful_imports
1678 , mods <- map fst interesting_imports
1679 = hsep
1680 [ ptext (sLit "Neither")
1681 , quotedListWithNor (map ppr mods)
1682 , ptext (sLit "exports")
1683 , quotes (ppr occ_name) <> dot
1684 ]
1685 | [(mod,(_,_,loc,_,_,_))] <- helpful_imports_non_hiding
1686 = fsep
1687 [ ptext (sLit "Perhaps you want to add")
1688 , quotes (ppr occ_name)
1689 , ptext (sLit "to the import list")
1690 , ptext (sLit "in the import of")
1691 , quotes (ppr mod)
1692 , parens (ppr loc) <> dot
1693 ]
1694 | not (null helpful_imports_non_hiding)
1695 = fsep
1696 [ ptext (sLit "Perhaps you want to add")
1697 , quotes (ppr occ_name)
1698 , ptext (sLit "to one of these import lists:")
1699 ]
1700 $$
1701 nest 2 (vcat
1702 [ quotes (ppr mod) <+> parens (ppr loc)
1703 | (mod,(_,_,loc,_,_,_)) <- helpful_imports_non_hiding
1704 ])
1705 | [(mod,(_,_,loc,_,_,_))] <- helpful_imports_hiding
1706 = fsep
1707 [ ptext (sLit "Perhaps you want to remove")
1708 , quotes (ppr occ_name)
1709 , ptext (sLit "from the explicit hiding list")
1710 , ptext (sLit "in the import of")
1711 , quotes (ppr mod)
1712 , parens (ppr loc) <> dot
1713 ]
1714 | not (null helpful_imports_hiding)
1715 = fsep
1716 [ ptext (sLit "Perhaps you want to remove")
1717 , quotes (ppr occ_name)
1718 , ptext (sLit "from the hiding clauses")
1719 , ptext (sLit "in one of these imports:")
1720 ]
1721 $$
1722 nest 2 (vcat
1723 [ quotes (ppr mod) <+> parens (ppr loc)
1724 | (mod,(_,_,loc,_,_,_)) <- helpful_imports_hiding
1725 ])
1726 | otherwise
1727 = Outputable.empty
1728 where
1729 Just (mod_name, occ_name) = isQual_maybe rdr_name
1730
1731 -- What import statements provide "Mod" at all
1732 interesting_imports = [ (mod, imp)
1733 | (mod, mod_imports) <- moduleEnvToList (imp_mods imports)
1734 , Just imp <- return $ pick mod_imports
1735 ]
1736
1737 -- We want to keep only one for each original module; preferably one with an
1738 -- explicit import list (for no particularly good reason)
1739 pick :: [ImportedModsVal] -> Maybe ImportedModsVal
1740 pick = listToMaybe . sortBy (compare `on` prefer) . filter select
1741 where select (name, _,_,_,_,_) = name == mod_name
1742 prefer (_, _, loc, _, hiding, _) = (hiding, loc)
1743
1744 -- Which of these would export a 'foo'
1745 -- (all of these are restricted imports, because if they were not, we
1746 -- wouldn't have an out-of-scope error in the first place)
1747 helpful_imports = [ (mod, imp)
1748 | (mod, imp@(_, _, _, _, _, all_exports)) <- interesting_imports
1749 , not . null $ lookupGlobalRdrEnv all_exports occ_name
1750 ]
1751
1752 -- Which of these do that because of an explicit import list
1753 helpful_imports_non_hiding = [ (mod, imp)
1754 | (mod, imp@(_, _ , _, _, False, _)) <- helpful_imports
1755 ]
1756
1757 -- Which of these do that because of an explicit hiding list
1758 helpful_imports_hiding = [ (mod, imp)
1759 | (mod, imp@(_, _ , _, _, True, _)) <- helpful_imports
1760 ]
1761
1762 -- | Called from the typechecker (TcErrors) when we find an unbound variable
1763 unknownNameSuggestions :: DynFlags
1764 -> GlobalRdrEnv -> LocalRdrEnv
1765 -> RdrName -> SDoc
1766 unknownNameSuggestions = unknownNameSuggestions_ WL_Any
1767
1768 unknownNameSuggestions_ :: WhereLooking -> DynFlags
1769 -> GlobalRdrEnv -> LocalRdrEnv
1770 -> RdrName -> SDoc
1771 unknownNameSuggestions_ where_look dflags global_env
1772 local_env tried_rdr_name
1773 = case suggest of
1774 [] -> Outputable.empty
1775 [p] -> perhaps <+> pp_item p
1776 ps -> sep [ perhaps <+> ptext (sLit "one of these:")
1777 , nest 2 (pprWithCommas pp_item ps) ]
1778 where
1779 all_possibilities :: [(String, (RdrName, HowInScope))]
1780 all_possibilities
1781 = [ (showPpr dflags r, (r, Left loc))
1782 | (r,loc) <- local_possibilities local_env ]
1783 ++ [ (showPpr dflags r, rp) | (r, rp) <- global_possibilities global_env ]
1784
1785 suggest = fuzzyLookup (showPpr dflags tried_rdr_name) all_possibilities
1786 perhaps = ptext (sLit "Perhaps you meant")
1787
1788 pp_item :: (RdrName, HowInScope) -> SDoc
1789 pp_item (rdr, Left loc) = pp_ns rdr <+> quotes (ppr rdr) <+> loc' -- Locally defined
1790 where loc' = case loc of
1791 UnhelpfulSpan l -> parens (ppr l)
1792 RealSrcSpan l -> parens (ptext (sLit "line") <+> int (srcSpanStartLine l))
1793 pp_item (rdr, Right is) = pp_ns rdr <+> quotes (ppr rdr) <+> -- Imported
1794 parens (ptext (sLit "imported from") <+> ppr (is_mod is))
1795
1796 pp_ns :: RdrName -> SDoc
1797 pp_ns rdr | ns /= tried_ns = pprNameSpace ns
1798 | otherwise = Outputable.empty
1799 where ns = rdrNameSpace rdr
1800
1801 tried_occ = rdrNameOcc tried_rdr_name
1802 tried_is_sym = isSymOcc tried_occ
1803 tried_ns = occNameSpace tried_occ
1804 tried_is_qual = isQual tried_rdr_name
1805
1806 correct_name_space occ = nameSpacesRelated (occNameSpace occ) tried_ns
1807 && isSymOcc occ == tried_is_sym
1808 -- Treat operator and non-operators as non-matching
1809 -- This heuristic avoids things like
1810 -- Not in scope 'f'; perhaps you meant '+' (from Prelude)
1811
1812 local_ok = case where_look of { WL_Any -> True; _ -> False }
1813 local_possibilities :: LocalRdrEnv -> [(RdrName, SrcSpan)]
1814 local_possibilities env
1815 | tried_is_qual = []
1816 | not local_ok = []
1817 | otherwise = [ (mkRdrUnqual occ, nameSrcSpan name)
1818 | name <- localRdrEnvElts env
1819 , let occ = nameOccName name
1820 , correct_name_space occ]
1821
1822 gre_ok :: GlobalRdrElt -> Bool
1823 gre_ok = case where_look of
1824 WL_LocalTop -> isLocalGRE
1825 _ -> \_ -> True
1826
1827 global_possibilities :: GlobalRdrEnv -> [(RdrName, (RdrName, HowInScope))]
1828 global_possibilities global_env
1829 | tried_is_qual = [ (rdr_qual, (rdr_qual, how))
1830 | gre <- globalRdrEnvElts global_env
1831 , gre_ok gre
1832 , let name = gre_name gre
1833 occ = nameOccName name
1834 , correct_name_space occ
1835 , (mod, how) <- quals_in_scope gre
1836 , let rdr_qual = mkRdrQual mod occ ]
1837
1838 | otherwise = [ (rdr_unqual, pair)
1839 | gre <- globalRdrEnvElts global_env
1840 , gre_ok gre
1841 , let name = gre_name gre
1842 occ = nameOccName name
1843 rdr_unqual = mkRdrUnqual occ
1844 , correct_name_space occ
1845 , pair <- case (unquals_in_scope gre, quals_only gre) of
1846 (how:_, _) -> [ (rdr_unqual, how) ]
1847 ([], pr:_) -> [ pr ] -- See Note [Only-quals]
1848 ([], []) -> [] ]
1849
1850 -- Note [Only-quals]
1851 -- The second alternative returns those names with the same
1852 -- OccName as the one we tried, but live in *qualified* imports
1853 -- e.g. if you have:
1854 --
1855 -- > import qualified Data.Map as Map
1856 -- > foo :: Map
1857 --
1858 -- then we suggest @Map.Map@.
1859
1860 --------------------
1861 unquals_in_scope :: GlobalRdrElt -> [HowInScope]
1862 unquals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is })
1863 | lcl = [ Left (nameSrcSpan n) ]
1864 | otherwise = [ Right ispec
1865 | i <- is, let ispec = is_decl i
1866 , not (is_qual ispec) ]
1867
1868 --------------------
1869 quals_in_scope :: GlobalRdrElt -> [(ModuleName, HowInScope)]
1870 -- Ones for which the qualified version is in scope
1871 quals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is })
1872 | lcl = case nameModule_maybe n of
1873 Nothing -> []
1874 Just m -> [(moduleName m, Left (nameSrcSpan n))]
1875 | otherwise = [ (is_as ispec, Right ispec)
1876 | i <- is, let ispec = is_decl i ]
1877
1878 --------------------
1879 quals_only :: GlobalRdrElt -> [(RdrName, HowInScope)]
1880 -- Ones for which *only* the qualified version is in scope
1881 quals_only (GRE { gre_name = n, gre_imp = is })
1882 = [ (mkRdrQual (is_as ispec) (nameOccName n), Right ispec)
1883 | i <- is, let ispec = is_decl i, is_qual ispec ]
1884
1885 {-
1886 ************************************************************************
1887 * *
1888 \subsection{Free variable manipulation}
1889 * *
1890 ************************************************************************
1891 -}
1892
1893 -- A useful utility
1894 addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
1895 addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
1896 ; return (res, fvs1 `plusFV` fvs2) }
1897
1898 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
1899 mapFvRn f xs = do stuff <- mapM f xs
1900 case unzip stuff of
1901 (ys, fvs_s) -> return (ys, plusFVs fvs_s)
1902
1903 mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
1904 mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
1905 mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
1906
1907 -- because some of the rename functions are CPSed:
1908 -- maps the function across the list from left to right;
1909 -- collects all the free vars into one set
1910 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
1911 -> [a] -> ([b] -> RnM c) -> RnM c
1912
1913 mapFvRnCPS _ [] cont = cont []
1914 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
1915 mapFvRnCPS f xs $ \ xs' ->
1916 cont (x':xs')
1917
1918 {-
1919 ************************************************************************
1920 * *
1921 \subsection{Envt utility functions}
1922 * *
1923 ************************************************************************
1924 -}
1925
1926 warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1927 warnUnusedTopBinds gres
1928 = whenWOptM Opt_WarnUnusedTopBinds
1929 $ do env <- getGblEnv
1930 let isBoot = tcg_src env == HsBootFile
1931 let noParent gre = case gre_par gre of
1932 NoParent -> True
1933 PatternSynonym -> True
1934 _ -> False
1935 -- Don't warn about unused bindings with parents in
1936 -- .hs-boot files, as you are sometimes required to give
1937 -- unused bindings (trac #3449).
1938 -- HOWEVER, in a signature file, you are never obligated to put a
1939 -- definition in the main text. Thus, if you define something
1940 -- and forget to export it, we really DO want to warn.
1941 gres' = if isBoot then filter noParent gres
1942 else gres
1943 warnUnusedGREs gres'
1944
1945 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1946 warnUnusedLocalBinds = check_unused Opt_WarnUnusedLocalBinds
1947 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
1948
1949 check_unused :: WarningFlag -> [Name] -> FreeVars -> RnM ()
1950 check_unused flag bound_names used_names
1951 = whenWOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1952
1953 -------------------------
1954 -- Helpers
1955 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1956 warnUnusedGREs gres = mapM_ warnUnusedGRE gres
1957
1958 warnUnusedLocals :: [Name] -> RnM ()
1959 warnUnusedLocals names = do
1960 fld_env <- mkFieldEnv <$> getGlobalRdrEnv
1961 mapM_ (warnUnusedLocal fld_env) names
1962
1963 warnUnusedLocal :: NameEnv (FieldLabelString, Name) -> Name -> RnM ()
1964 warnUnusedLocal fld_env name
1965 = when (reportable name) $
1966 addUnusedWarning occ (nameSrcSpan name)
1967 (ptext (sLit "Defined but not used"))
1968 where
1969 occ = case lookupNameEnv fld_env name of
1970 Just (fl, _) -> mkVarOccFS fl
1971 Nothing -> nameOccName name
1972
1973 warnUnusedGRE :: GlobalRdrElt -> RnM ()
1974 warnUnusedGRE gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = is })
1975 | lcl = do fld_env <- mkFieldEnv <$> getGlobalRdrEnv
1976 warnUnusedLocal fld_env name
1977 | otherwise = when (reportable name) (mapM_ warn is)
1978 where
1979 occ = greOccName gre
1980 warn spec = addUnusedWarning occ span msg
1981 where
1982 span = importSpecLoc spec
1983 pp_mod = quotes (ppr (importSpecModule spec))
1984 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1985
1986 -- | Make a map from selector names to field labels and parent tycon
1987 -- names, to be used when reporting unused record fields.
1988 mkFieldEnv :: GlobalRdrEnv -> NameEnv (FieldLabelString, Name)
1989 mkFieldEnv rdr_env = mkNameEnv [ (gre_name gre, (lbl, par_is (gre_par gre)))
1990 | gres <- occEnvElts rdr_env
1991 , gre <- gres
1992 , Just lbl <- [greLabel gre]
1993 ]
1994
1995 reportable :: Name -> Bool
1996 reportable name
1997 | isWiredInName name = False -- Don't report unused wired-in names
1998 -- Otherwise we get a zillion warnings
1999 -- from Data.Tuple
2000 | otherwise = not (startsWithUnderscore (nameOccName name))
2001
2002 addUnusedWarning :: OccName -> SrcSpan -> SDoc -> RnM ()
2003 addUnusedWarning occ span msg
2004 = addWarnAt span $
2005 sep [msg <> colon,
2006 nest 2 $ pprNonVarNameSpace (occNameSpace occ)
2007 <+> quotes (ppr occ)]
2008
2009 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
2010 addNameClashErrRn rdr_name gres
2011 | all isLocalGRE gres && not (all isRecFldGRE gres)
2012 -- If there are two or more *local* defns, we'll have reported
2013 = return () -- that already, and we don't want an error cascade
2014 | otherwise
2015 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
2016 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
2017 where
2018 (np1:nps) = gres
2019 msg1 = ptext (sLit "either") <+> mk_ref np1
2020 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
2021 mk_ref gre = sep [nom <> comma, pprNameProvenance gre]
2022 where nom = case gre_par gre of
2023 FldParent { par_lbl = Just lbl } -> text "the field" <+> quotes (ppr lbl)
2024 _ -> quotes (ppr (gre_name gre))
2025
2026 shadowedNameWarn :: OccName -> [SDoc] -> SDoc
2027 shadowedNameWarn occ shadowed_locs
2028 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
2029 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
2030 nest 2 (vcat shadowed_locs)]
2031
2032 perhapsForallMsg :: SDoc
2033 perhapsForallMsg
2034 = vcat [ ptext (sLit "Perhaps you intended to use ExplicitForAll or similar flag")
2035 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
2036
2037 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
2038 unknownSubordinateErr doc op -- Doc is "method of class" or
2039 -- "field of constructor"
2040 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
2041
2042 badOrigBinding :: RdrName -> SDoc
2043 badOrigBinding name
2044 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
2045 -- The rdrNameOcc is because we don't want to print Prelude.(,)
2046
2047 dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
2048 dupNamesErr get_loc names
2049 = addErrAt big_loc $
2050 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
2051 locations]
2052 where
2053 locs = map get_loc names
2054 big_loc = foldr1 combineSrcSpans locs
2055 locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sort locs))
2056
2057 kindSigErr :: Outputable a => a -> SDoc
2058 kindSigErr thing
2059 = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
2060 2 (ptext (sLit "Perhaps you intended to use KindSignatures"))
2061
2062 badQualBndrErr :: RdrName -> SDoc
2063 badQualBndrErr rdr_name
2064 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
2065
2066 opDeclErr :: RdrName -> SDoc
2067 opDeclErr n
2068 = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
2069 2 (ptext (sLit "Use TypeOperators to declare operators in type and declarations"))
2070
2071 checkTupSize :: Int -> RnM ()
2072 checkTupSize tup_size
2073 | tup_size <= mAX_TUPLE_SIZE
2074 = return ()
2075 | otherwise
2076 = addErr (sep [ptext (sLit "A") <+> int tup_size <> ptext (sLit "-tuple is too large for GHC"),
2077 nest 2 (parens (ptext (sLit "max size is") <+> int mAX_TUPLE_SIZE)),
2078 nest 2 (ptext (sLit "Workaround: use nested tuples or define a data type"))])
2079
2080 {-
2081 ************************************************************************
2082 * *
2083 \subsection{Contexts for renaming errors}
2084 * *
2085 ************************************************************************
2086 -}
2087
2088 data HsDocContext
2089 = TypeSigCtx SDoc
2090 | PatCtx
2091 | SpecInstSigCtx
2092 | DefaultDeclCtx
2093 | ForeignDeclCtx (Located RdrName)
2094 | DerivDeclCtx
2095 | RuleCtx FastString
2096 | TyDataCtx (Located RdrName)
2097 | TySynCtx (Located RdrName)
2098 | TyFamilyCtx (Located RdrName)
2099 | ConDeclCtx [Located RdrName]
2100 | ClassDeclCtx (Located RdrName)
2101 | ExprWithTySigCtx
2102 | TypBrCtx
2103 | HsTypeCtx
2104 | GHCiCtx
2105 | SpliceTypeCtx (LHsType RdrName)
2106 | ClassInstanceCtx
2107 | VectDeclCtx (Located RdrName)
2108 | GenericCtx SDoc -- Maybe we want to use this more!
2109
2110 docOfHsDocContext :: HsDocContext -> SDoc
2111 docOfHsDocContext (GenericCtx doc) = doc
2112 docOfHsDocContext (TypeSigCtx doc) = text "In the type signature for" <+> doc
2113 docOfHsDocContext PatCtx = text "In a pattern type-signature"
2114 docOfHsDocContext SpecInstSigCtx = text "In a SPECIALISE instance pragma"
2115 docOfHsDocContext DefaultDeclCtx = text "In a `default' declaration"
2116 docOfHsDocContext (ForeignDeclCtx name) = ptext (sLit "In the foreign declaration for") <+> ppr name
2117 docOfHsDocContext DerivDeclCtx = text "In a deriving declaration"
2118 docOfHsDocContext (RuleCtx name) = text "In the transformation rule" <+> ftext name
2119 docOfHsDocContext (TyDataCtx tycon) = text "In the data type declaration for" <+> quotes (ppr tycon)
2120 docOfHsDocContext (TySynCtx name) = text "In the declaration for type synonym" <+> quotes (ppr name)
2121 docOfHsDocContext (TyFamilyCtx name) = text "In the declaration for type family" <+> quotes (ppr name)
2122
2123 docOfHsDocContext (ConDeclCtx [name])
2124 = text "In the definition of data constructor" <+> quotes (ppr name)
2125 docOfHsDocContext (ConDeclCtx names)
2126 = text "In the definition of data constructors" <+> interpp'SP names
2127
2128 docOfHsDocContext (ClassDeclCtx name) = text "In the declaration for class" <+> ppr name
2129 docOfHsDocContext ExprWithTySigCtx = text "In an expression type signature"
2130 docOfHsDocContext TypBrCtx = ptext (sLit "In a Template-Haskell quoted type")
2131 docOfHsDocContext HsTypeCtx = text "In a type argument"
2132 docOfHsDocContext GHCiCtx = ptext (sLit "In GHCi input")
2133 docOfHsDocContext (SpliceTypeCtx hs_ty) = ptext (sLit "In the spliced type") <+> ppr hs_ty
2134 docOfHsDocContext ClassInstanceCtx = ptext (sLit "TcSplice.reifyInstances")
2135 docOfHsDocContext (VectDeclCtx tycon) = ptext (sLit "In the VECTORISE pragma for type constructor") <+> quotes (ppr tycon)