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