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