2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
4 \section[RnEnv]{Environment manipulation for the renamer monad}
8 newTopSrcBinder, lookupFamInstDeclBndr,
9 lookupLocatedTopBndrRn, lookupTopBndrRn,
10 lookupLocatedOccRn, lookupOccRn,
11 lookupLocatedGlobalOccRn,
12 lookupGlobalOccRn, lookupGlobalOccRn_maybe,
13 lookupLocalDataTcNames, lookupSigOccRn,
14 lookupFixityRn, lookupTyFixityRn,
15 lookupInstDeclBndr, lookupSubBndr, lookupConstructorFields,
16 lookupSyntaxName, lookupSyntaxTable,
17 lookupGreRn, lookupGreLocalRn, lookupGreRn_maybe,
18 getLookupOccRn, addUsedRdrNames,
20 newLocalBndrRn, newLocalBndrsRn, newIPNameRn,
21 bindLocalName, bindLocalNames, bindLocalNamesFV,
22 MiniFixityEnv, emptyFsEnv, extendFsEnv, lookupFsEnv,
24 bindLocatedLocalsFV, bindLocatedLocalsRn,
25 bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
26 bindTyVarsRn, bindTyVarsFV, extendTyVarEnvFVRn,
28 checkDupRdrNames, checkDupAndShadowedRdrNames,
29 checkDupNames, checkDupAndShadowedNames,
30 addFvRn, mapFvRn, mapMaybeFvRn, mapFvRnCPS,
31 warnUnusedMatches, warnUnusedModules, warnUnusedImports,
32 warnUnusedTopBinds, warnUnusedLocalBinds,
33 dataTcOccs, unknownNameErr, kindSigErr, perhapsForallMsg
36 #include "HsVersions.h"
38 import LoadIface ( loadInterfaceForName, loadSrcInterface )
39 import IfaceEnv ( lookupOrig, newGlobalBinder, newIPName )
41 import RdrHsSyn ( extractHsTyRdrTyVars )
43 import HscTypes ( availNames, ModIface(..), FixItem(..), lookupFixity)
44 import TcEnv ( tcLookupDataCon, tcLookupField, isBrackStage )
46 import Id ( isRecordSelector )
47 import Name ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
48 nameSrcLoc, nameSrcSpan, nameOccName, nameModule, isExternalName )
52 import DataCon ( dataConFieldLabels )
54 import Module ( ModuleName )
55 import PrelNames ( mkUnboundName, rOOT_MAIN, iNTERACTIVE,
56 consDataConKey, forall_tv_RDR )
59 import ErrUtils ( Message )
64 import ListSetOps ( removeDups )
69 import qualified Data.Set as Set
74 thenM :: Monad a => a b -> (b -> a c) -> a c
78 %*********************************************************
82 %*********************************************************
85 newTopSrcBinder :: Located RdrName -> RnM Name
86 newTopSrcBinder (L loc rdr_name)
87 | Just name <- isExact_maybe rdr_name
88 = -- This is here to catch
89 -- (a) Exact-name binders created by Template Haskell
90 -- (b) The PrelBase defn of (say) [] and similar, for which
91 -- the parser reads the special syntax and returns an Exact RdrName
92 -- We are at a binding site for the name, so check first that it
93 -- the current module is the correct one; otherwise GHC can get
94 -- very confused indeed. This test rejects code like
95 -- data T = (,) Int Int
96 -- unless we are in GHC.Tup
97 ASSERT2( isExternalName name, ppr name )
98 do { this_mod <- getModule
99 ; unless (this_mod == nameModule name)
100 (addErrAt loc (badOrigBinding rdr_name))
104 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
105 = do { this_mod <- getModule
106 ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
107 (addErrAt loc (badOrigBinding rdr_name))
108 -- When reading External Core we get Orig names as binders,
109 -- but they should agree with the module gotten from the monad
111 -- We can get built-in syntax showing up here too, sadly. If you type
113 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
114 -- uses setRdrNameSpace to make it into a data constructors. At that point
115 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
116 -- Hence the badOrigBinding error message.
118 -- Except for the ":Main.main = ..." definition inserted into
119 -- the Main module; ugh!
121 -- Because of this latter case, we call newGlobalBinder with a module from
122 -- the RdrName, not from the environment. In principle, it'd be fine to
123 -- have an arbitrary mixture of external core definitions in a single module,
124 -- (apart from module-initialisation issues, perhaps).
125 ; newGlobalBinder rdr_mod rdr_occ loc }
126 --TODO, should pass the whole span
129 = do { unless (not (isQual rdr_name))
130 (addErrAt loc (badQualBndrErr rdr_name))
131 -- Binders should not be qualified; if they are, and with a different
132 -- module name, we we get a confusing "M.T is not in scope" error later
135 ; if isBrackStage stage then
136 -- We are inside a TH bracket, so make an *Internal* name
137 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
138 do { uniq <- newUnique
139 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
142 do { this_mod <- getModule
143 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } }
146 %*********************************************************
148 Source code occurrences
150 %*********************************************************
152 Looking up a name in the RnEnv.
154 Note [Type and class operator definitions]
155 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
156 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
158 class a :*: b where ...
159 data (:*:) a b = ....
160 class (:*:) a b where ...
161 The latter two mean that we are not just looking for a
162 *syntactically-infix* declaration, but one that uses an operator
163 OccName. We use OccName.isSymOcc to detect that case, which isn't
164 terribly efficient, but there seems to be no better way.
167 lookupTopBndrRn :: RdrName -> RnM Name
168 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
171 Nothing -> do traceRn $ text "lookupTopBndrRn"
174 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
175 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
177 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
178 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
179 -- and there may be several imported 'f's too, which must not confuse us.
180 -- For example, this is OK:
182 -- infix 9 f -- The 'f' here does not need to be qualified
183 -- f x = x -- Nor here, of course
184 -- So we have to filter out the non-local ones.
186 -- A separate function (importsFromLocalDecls) reports duplicate top level
187 -- decls, so here it's safe just to choose an arbitrary one.
189 -- There should never be a qualified name in a binding position in Haskell,
190 -- but there can be if we have read in an external-Core file.
191 -- The Haskell parser checks for the illegal qualified name in Haskell
192 -- source files, so we don't need to do so here.
194 lookupTopBndrRn_maybe rdr_name
195 | Just name <- isExact_maybe rdr_name
198 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
199 -- This deals with the case of derived bindings, where
200 -- we don't bother to call newTopSrcBinder first
201 -- We assume there is no "parent" name
202 = do { loc <- getSrcSpanM
203 ; n <- newGlobalBinder rdr_mod rdr_occ loc
207 = do { -- Check for operators in type or class declarations
208 -- See Note [Type and class operator definitions]
209 let occ = rdrNameOcc rdr_name
210 ; when (isTcOcc occ && isSymOcc occ)
211 (do { op_ok <- doptM Opt_TypeOperators
212 ; unless op_ok (addErr (opDeclErr rdr_name)) })
214 ; mb_gre <- lookupGreLocalRn rdr_name
216 Nothing -> return Nothing
217 Just gre -> return (Just $ gre_name gre) }
220 -----------------------------------------------
221 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
222 -- This is called on the method name on the left-hand side of an
223 -- instance declaration binding. eg. instance Functor T where
225 -- ^^^^ called on this
226 -- Regardless of how many unqualified fmaps are in scope, we want
227 -- the one that comes from the Functor class.
229 -- Furthermore, note that we take no account of whether the
230 -- name is only in scope qualified. I.e. even if method op is
231 -- in scope as M.op, we still allow plain 'op' on the LHS of
233 lookupInstDeclBndr cls rdr
234 = do { when (isQual rdr)
235 (addErr (badQualBndrErr rdr))
236 -- In an instance decl you aren't allowed
237 -- to use a qualified name for the method
238 -- (Although it'd make perfect sense.)
239 ; lookupSubBndr (ParentIs cls) doc rdr }
241 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
243 -----------------------------------------------
244 lookupConstructorFields :: Name -> RnM [Name]
245 -- Look up the fields of a given constructor
246 -- * For constructors from this module, use the record field env,
247 -- which is itself gathered from the (as yet un-typechecked)
250 -- * For constructors from imported modules, use the *type* environment
251 -- since imported modles are already compiled, the info is conveniently
254 lookupConstructorFields con_name
255 = do { this_mod <- getModule
256 ; if nameIsLocalOrFrom this_mod con_name then
257 do { RecFields field_env _ <- getRecFieldEnv
258 ; return (lookupNameEnv field_env con_name `orElse` []) }
260 do { con <- tcLookupDataCon con_name
261 ; return (dataConFieldLabels con) } }
263 -----------------------------------------------
264 -- Used for record construction and pattern matching
265 -- When the -XDisambiguateRecordFields flag is on, take account of the
266 -- constructor name to disambiguate which field to use; it's just the
267 -- same as for instance decls
269 -- NB: Consider this:
270 -- module Foo where { data R = R { fld :: Int } }
271 -- module Odd where { import Foo; fld x = x { fld = 3 } }
272 -- Arguably this should work, because the reference to 'fld' is
273 -- unambiguous because there is only one field id 'fld' in scope.
274 -- But currently it's rejected.
276 lookupSubBndr :: Parent -- NoParent => just look it up as usual
277 -- ParentIs p => use p to disambiguate
280 lookupSubBndr parent doc rdr_name
281 | Just n <- isExact_maybe rdr_name -- This happens in derived code
284 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
285 = lookupOrig rdr_mod rdr_occ
287 | otherwise -- Find all the things the rdr-name maps to
288 = do { -- and pick the one with the right parent name
289 ; env <- getGlobalRdrEnv
290 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
291 ; case pick parent gres of
292 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
293 -- The latter does pickGREs, but we want to allow 'x'
294 -- even if only 'M.x' is in scope
295 [gre] -> do { addUsedRdrNames (used_rdr_names gre)
296 ; return (gre_name gre) }
297 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
298 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> (ppr rdr_name $$ ppr gres))
299 ; return (mkUnboundName rdr_name) }
300 gres -> do { addNameClashErrRn rdr_name gres
301 ; return (gre_name (head gres)) } }
303 pick NoParent gres -- Normal lookup
304 = pickGREs rdr_name gres
305 pick (ParentIs p) gres -- Disambiguating lookup
306 | isUnqual rdr_name = filter (right_parent p) gres
307 | otherwise = filter (right_parent p) (pickGREs rdr_name gres)
309 right_parent p (GRE { gre_par = ParentIs p' }) = p==p'
310 right_parent _ _ = False
312 -- Note [Usage for sub-bndrs]
314 | isQual rdr_name = [rdr_name]
315 | otherwise = case gre_prov gre of
316 LocalDef -> [rdr_name]
317 Imported is -> map mk_qual_rdr is
318 mk_qual_rdr imp_spec = mkRdrQual (is_as (is_decl imp_spec)) rdr_occ
319 rdr_occ = rdrNameOcc rdr_name
321 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
322 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
324 -- If the family is declared locally, it will not yet be in the main
325 -- environment; hence, we pass in an extra one here, which we check first.
326 -- See "Note [Looking up family names in family instances]" in 'RnNames'.
328 lookupFamInstDeclBndr :: GlobalRdrEnv -> Located RdrName -> RnM Name
329 lookupFamInstDeclBndr tyclGroupEnv (L loc rdr_name)
331 case lookupGRE_RdrName rdr_name tyclGroupEnv of
332 (gre:_) -> return $ gre_name gre
333 -- if there is more than one, an error will be raised elsewhere
334 [] -> lookupOccRn rdr_name
337 Note [Usage for sub-bndrs]
338 ~~~~~~~~~~~~~~~~~~~~~~~~~~
340 import qualified M( C( f ) )
343 then is the qualified import M.f used? Obviously yes.
344 But the RdrName used in the instance decl is unqualified. In effect,
345 we fill in the qualification by looking for f's whose class is M.C
346 But when adding to the UsedRdrNames we must make that qualification
347 explicit, otherwise we get "Redundant import of M.C".
349 --------------------------------------------------
351 --------------------------------------------------
354 getLookupOccRn :: RnM (Name -> Maybe Name)
356 = getLocalRdrEnv `thenM` \ local_env ->
357 return (lookupLocalRdrOcc local_env . nameOccName)
359 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
360 lookupLocatedOccRn = wrapLocM lookupOccRn
362 -- lookupOccRn looks up an occurrence of a RdrName
363 lookupOccRn :: RdrName -> RnM Name
365 = getLocalRdrEnv `thenM` \ local_env ->
366 case lookupLocalRdrEnv local_env rdr_name of
367 Just name -> return name
368 Nothing -> lookupGlobalOccRn rdr_name
370 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
371 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
373 lookupGlobalOccRn :: RdrName -> RnM Name
374 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
375 -- environment. Adds an error message if the RdrName is not in scope.
376 -- Also has a special case for GHCi.
378 lookupGlobalOccRn rdr_name
379 = do { -- First look up the name in the normal environment.
380 mb_name <- lookupGlobalOccRn_maybe rdr_name
385 { -- We allow qualified names on the command line to refer to
386 -- *any* name exported by any module in scope, just as if there
387 -- was an "import qualified M" declaration for every module.
388 allow_qual <- doptM Opt_ImplicitImportQualified
390 -- This test is not expensive,
391 -- and only happens for failed lookups
392 ; if isQual rdr_name && allow_qual && mod == iNTERACTIVE
393 then lookupQualifiedName rdr_name
394 else unboundName rdr_name } } }
396 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
397 -- No filter function; does not report an error on failure
399 lookupGlobalOccRn_maybe rdr_name
400 | Just n <- isExact_maybe rdr_name -- This happens in derived code
403 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
404 = do { n <- lookupOrig rdr_mod rdr_occ; return (Just n) }
407 = do { mb_gre <- lookupGreRn_maybe rdr_name
409 Nothing -> return Nothing
410 Just gre -> return (Just (gre_name gre)) }
413 unboundName :: RdrName -> RnM Name
415 = do { addErr (unknownNameErr rdr_name)
416 ; env <- getGlobalRdrEnv;
417 ; traceRn (vcat [unknownNameErr rdr_name,
418 ptext (sLit "Global envt is:"),
419 nest 3 (pprGlobalRdrEnv env)])
420 ; return (mkUnboundName rdr_name) }
422 --------------------------------------------------
423 -- Lookup in the Global RdrEnv of the module
424 --------------------------------------------------
426 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
427 -- Just look up the RdrName in the GlobalRdrEnv
428 lookupGreRn_maybe rdr_name
429 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
431 lookupGreRn :: RdrName -> RnM GlobalRdrElt
432 -- If not found, add error message, and return a fake GRE
434 = do { mb_gre <- lookupGreRn_maybe rdr_name
436 Just gre -> return gre ;
438 { traceRn $ text "lookupGreRn"
439 ; name <- unboundName rdr_name
440 ; return (GRE { gre_name = name, gre_par = NoParent,
441 gre_prov = LocalDef }) }}}
443 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
444 -- Similar, but restricted to locally-defined things
445 lookupGreLocalRn rdr_name
446 = lookupGreRn_help rdr_name lookup_fn
448 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
450 lookupGreRn_help :: RdrName -- Only used in error message
451 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
452 -> RnM (Maybe GlobalRdrElt)
453 -- Checks for exactly one match; reports deprecations
454 -- Returns Nothing, without error, if too few
455 lookupGreRn_help rdr_name lookup
456 = do { env <- getGlobalRdrEnv
459 [gre] -> do { addUsedRdrName gre rdr_name
460 ; return (Just gre) }
461 gres -> do { addNameClashErrRn rdr_name gres
462 ; return (Just (head gres)) } }
464 addUsedRdrName :: GlobalRdrElt -> RdrName -> RnM ()
465 -- Record usage of imported RdrNames
466 addUsedRdrName gre rdr
467 | isLocalGRE gre = return ()
468 | otherwise = do { env <- getGblEnv
469 ; updMutVar (tcg_used_rdrnames env)
470 (\s -> Set.insert rdr s) }
472 addUsedRdrNames :: [RdrName] -> RnM ()
473 -- Record used sub-binders
474 -- We don't check for imported-ness here, because it's inconvenient
475 -- and not stritly necessary.
477 = do { env <- getGblEnv
478 ; updMutVar (tcg_used_rdrnames env)
479 (\s -> foldr Set.insert s rdrs) }
481 ------------------------------
483 ------------------------------
485 -- A qualified name on the command line can refer to any module at all: we
486 -- try to load the interface if we don't already have it.
487 lookupQualifiedName :: RdrName -> RnM Name
488 lookupQualifiedName rdr_name
489 | Just (mod,occ) <- isQual_maybe rdr_name
490 -- Note: we want to behave as we would for a source file import here,
491 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
492 = loadSrcInterface doc mod False Nothing `thenM` \ iface ->
495 (mod,avails) <- mi_exports iface,
497 name <- availNames avail,
499 ((mod,occ):ns) -> ASSERT (null ns)
501 _ -> unboundName rdr_name
504 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
506 doc = ptext (sLit "Need to find") <+> ppr rdr_name
509 lookupSigOccRn is used for type signatures and pragmas
515 It's clear that the 'f' in the signature must refer to A.f
516 The Haskell98 report does not stipulate this, but it will!
517 So we must treat the 'f' in the signature in the same way
518 as the binding occurrence of 'f', using lookupBndrRn
520 However, consider this case:
524 We don't want to say 'f' is out of scope; instead, we want to
525 return the imported 'f', so that later on the reanamer will
526 correctly report "misplaced type sig".
529 lookupSigOccRn :: Maybe NameSet -- Just ns => source file; these are the binders
531 -- Nothing => hs-boot file; signatures without
532 -- binders are expected
534 -> Located RdrName -> RnM (Located Name)
535 lookupSigOccRn mb_bound_names sig
536 = wrapLocM $ \ rdr_name ->
537 do { mb_name <- lookupBindGroupOcc mb_bound_names (hsSigDoc sig) rdr_name
539 Left err -> do { addErr err; return (mkUnboundName rdr_name) }
540 Right name -> return name }
542 lookupBindGroupOcc :: Maybe NameSet -- Just ns => source file; these are the binders
544 -- Nothing => hs-boot file; signatures without
545 -- binders are expected
547 -> RdrName -> RnM (Either Message Name)
548 -- Looks up the RdrName, expecting it to resolve to one of the
549 -- bound names passed in. If not, return an appropriate error message
550 lookupBindGroupOcc mb_bound_names what rdr_name
551 = do { local_env <- getLocalRdrEnv
552 ; case lookupLocalRdrEnv local_env rdr_name of
553 Just n -> check_local_name n
554 Nothing -> do -- Not defined in a nested scope
556 { env <- getGlobalRdrEnv
557 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
558 ; case (filter isLocalGRE gres) of
559 (gre:_) -> check_local_name (gre_name gre)
560 -- If there is more than one local GRE for the
561 -- same OccName, that will be reported separately
562 [] | null gres -> bale_out_with empty
563 | otherwise -> bale_out_with import_msg
566 check_local_name name -- The name is in scope, and not imported
567 = case mb_bound_names of
568 Just bound_names | not (name `elemNameSet` bound_names)
569 -> bale_out_with local_msg
570 _other -> return (Right name)
573 = return (Left (sep [ ptext (sLit "The") <+> what
574 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
575 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
578 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
579 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
581 import_msg = parens $ ptext (sLit "You cannot give a") <+> what
582 <+> ptext (sLit "for an imported value")
585 lookupLocalDataTcNames :: NameSet -> SDoc -> RdrName -> RnM [Name]
586 -- GHC extension: look up both the tycon and data con
587 -- for con-like things
588 -- Complain if neither is in scope
589 lookupLocalDataTcNames bound_names what rdr_name
590 | Just n <- isExact_maybe rdr_name
591 -- Special case for (:), which doesn't get into the GlobalRdrEnv
592 = return [n] -- For this we don't need to try the tycon too
594 = do { mb_gres <- mapM (lookupBindGroupOcc (Just bound_names) what)
595 (dataTcOccs rdr_name)
596 ; let (errs, names) = splitEithers mb_gres
597 ; when (null names) (addErr (head errs)) -- Bleat about one only
600 dataTcOccs :: RdrName -> [RdrName]
601 -- If the input is a data constructor, return both it and a type
602 -- constructor. This is useful when we aren't sure which we are
605 | Just n <- isExact_maybe rdr_name -- Ghastly special case
606 , n `hasKey` consDataConKey = [rdr_name] -- see note below
607 | isDataOcc occ = [rdr_name, rdr_name_tc]
608 | otherwise = [rdr_name]
610 occ = rdrNameOcc rdr_name
611 rdr_name_tc = setRdrNameSpace rdr_name tcName
613 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
614 -- and setRdrNameSpace generates an Orig, which is fine
615 -- But it's not fine for (:), because there *is* no corresponding type
616 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
617 -- appear to be in scope (because Orig's simply allocate a new name-cache
618 -- entry) and then we get an error when we use dataTcOccs in
619 -- TcRnDriver.tcRnGetInfo. Large sigh.
623 %*********************************************************
627 %*********************************************************
630 --------------------------------
631 type FastStringEnv a = UniqFM a -- Keyed by FastString
634 emptyFsEnv :: FastStringEnv a
635 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
636 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
638 emptyFsEnv = emptyUFM
639 lookupFsEnv = lookupUFM
640 extendFsEnv = addToUFM
642 --------------------------------
643 type MiniFixityEnv = FastStringEnv (Located Fixity)
644 -- Mini fixity env for the names we're about
645 -- to bind, in a single binding group
647 -- It is keyed by the *FastString*, not the *OccName*, because
648 -- the single fixity decl infix 3 T
649 -- affects both the data constructor T and the type constrctor T
651 -- We keep the location so that if we find
652 -- a duplicate, we can report it sensibly
654 --------------------------------
655 -- Used for nested fixity decls to bind names along with their fixities.
656 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
658 addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
659 addLocalFixities mini_fix_env names thing_inside
660 = extendFixityEnv (mapCatMaybes find_fixity names) thing_inside
663 = case lookupFsEnv mini_fix_env (occNameFS occ) of
664 Just (L _ fix) -> Just (name, FixItem occ fix)
667 occ = nameOccName name
670 --------------------------------
671 lookupFixity is a bit strange.
673 * Nested local fixity decls are put in the local fixity env, which we
674 find with getFixtyEnv
676 * Imported fixities are found in the HIT or PIT
678 * Top-level fixity decls in this module may be for Names that are
679 either Global (constructors, class operations)
680 or Local/Exported (everything else)
681 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
682 We put them all in the local fixity environment
685 lookupFixityRn :: Name -> RnM Fixity
687 = getModule `thenM` \ this_mod ->
688 if nameIsLocalOrFrom this_mod name
689 then do -- It's defined in this module
690 local_fix_env <- getFixityEnv
691 traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
692 vcat [ppr name, ppr local_fix_env])
693 return $ lookupFixity local_fix_env name
694 else -- It's imported
695 -- For imported names, we have to get their fixities by doing a
696 -- loadInterfaceForName, and consulting the Ifaces that comes back
697 -- from that, because the interface file for the Name might not
698 -- have been loaded yet. Why not? Suppose you import module A,
699 -- which exports a function 'f', thus;
700 -- module CurrentModule where
702 -- module A( f ) where
704 -- Then B isn't loaded right away (after all, it's possible that
705 -- nothing from B will be used). When we come across a use of
706 -- 'f', we need to know its fixity, and it's then, and only
707 -- then, that we load B.hi. That is what's happening here.
709 -- loadInterfaceForName will find B.hi even if B is a hidden module,
710 -- and that's what we want.
711 loadInterfaceForName doc name `thenM` \ iface -> do {
712 traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
713 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
714 return (mi_fix_fn iface (nameOccName name))
717 doc = ptext (sLit "Checking fixity for") <+> ppr name
720 lookupTyFixityRn :: Located Name -> RnM Fixity
721 lookupTyFixityRn (L _ n) = lookupFixityRn n
725 %************************************************************************
728 Dealing with rebindable syntax is driven by the
729 Opt_NoImplicitPrelude dynamic flag.
731 In "deriving" code we don't want to use rebindable syntax
732 so we switch off the flag locally
735 %************************************************************************
737 Haskell 98 says that when you say "3" you get the "fromInteger" from the
738 Standard Prelude, regardless of what is in scope. However, to experiment
739 with having a language that is less coupled to the standard prelude, we're
740 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
741 happens to be in scope. Then you can
743 import MyPrelude as Prelude
744 to get the desired effect.
746 At the moment this just happens for
747 * fromInteger, fromRational on literals (in expressions and patterns)
748 * negate (in expressions)
749 * minus (arising from n+k patterns)
752 We store the relevant Name in the HsSyn tree, in
753 * HsIntegral/HsFractional/HsIsString
757 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
758 fromRationalName etc), but the renamer changes this to the appropriate user
759 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
761 We treat the orignal (standard) names as free-vars too, because the type checker
762 checks the type of the user thing against the type of the standard thing.
765 lookupSyntaxName :: Name -- The standard name
766 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
767 lookupSyntaxName std_name
768 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
769 if implicit_prelude then normal_case
771 -- Get the similarly named thing from the local environment
772 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
773 return (HsVar usr_name, unitFV usr_name)
775 normal_case = return (HsVar std_name, emptyFVs)
777 lookupSyntaxTable :: [Name] -- Standard names
778 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
779 lookupSyntaxTable std_names
780 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
781 if implicit_prelude then normal_case
783 -- Get the similarly named thing from the local environment
784 mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
786 return (std_names `zip` map HsVar usr_names, mkFVs usr_names)
788 normal_case = return (std_names `zip` map HsVar std_names, emptyFVs)
792 %*********************************************************
796 %*********************************************************
799 newLocalBndrRn :: Located RdrName -> RnM Name
800 -- Used for non-top-level binders. These should
801 -- never be qualified.
802 newLocalBndrRn (L loc rdr_name)
803 | Just name <- isExact_maybe rdr_name
804 = return name -- This happens in code generated by Template Haskell
805 -- although I'm not sure why. Perhpas it's the call
806 -- in RnPat.newName LetMk?
808 = do { unless (isUnqual rdr_name)
809 (addErrAt loc (badQualBndrErr rdr_name))
811 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
813 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
814 newLocalBndrsRn = mapM newLocalBndrRn
816 ---------------------
817 bindLocatedLocalsRn :: [Located RdrName]
820 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
821 = do { checkDupAndShadowedRdrNames rdr_names_w_loc
823 -- Make fresh Names and extend the environment
824 ; names <- newLocalBndrsRn rdr_names_w_loc
825 ; bindLocalNames names (enclosed_scope names) }
827 bindLocalNames :: [Name] -> RnM a -> RnM a
828 bindLocalNames names enclosed_scope
829 = do { name_env <- getLocalRdrEnv
830 ; setLocalRdrEnv (extendLocalRdrEnvList name_env names)
833 bindLocalName :: Name -> RnM a -> RnM a
834 bindLocalName name enclosed_scope
835 = do { name_env <- getLocalRdrEnv
836 ; setLocalRdrEnv (extendLocalRdrEnv name_env name)
839 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
840 bindLocalNamesFV names enclosed_scope
841 = do { (result, fvs) <- bindLocalNames names enclosed_scope
842 ; return (result, delFVs names fvs) }
845 -------------------------------------
846 -- binLocalsFVRn is the same as bindLocalsRn
847 -- except that it deals with free vars
848 bindLocatedLocalsFV :: [Located RdrName]
849 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
850 bindLocatedLocalsFV rdr_names enclosed_scope
851 = bindLocatedLocalsRn rdr_names $ \ names ->
852 enclosed_scope names `thenM` \ (thing, fvs) ->
853 return (thing, delFVs names fvs)
855 -------------------------------------
856 bindTyVarsFV :: [LHsTyVarBndr RdrName]
857 -> ([LHsTyVarBndr Name] -> RnM (a, FreeVars))
859 bindTyVarsFV tyvars thing_inside
860 = bindTyVarsRn tyvars $ \ tyvars' ->
861 do { (res, fvs) <- thing_inside tyvars'
862 ; return (res, delFVs (map hsLTyVarName tyvars') fvs) }
864 bindTyVarsRn :: [LHsTyVarBndr RdrName]
865 -> ([LHsTyVarBndr Name] -> RnM a)
867 -- Haskell-98 binding of type variables; e.g. within a data type decl
868 bindTyVarsRn tyvar_names enclosed_scope
869 = bindLocatedLocalsRn located_tyvars $ \ names ->
870 do { kind_sigs_ok <- doptM Opt_KindSignatures
871 ; unless (null kinded_tyvars || kind_sigs_ok)
872 (mapM_ (addErr . kindSigErr) kinded_tyvars)
873 ; enclosed_scope (zipWith replace tyvar_names names) }
875 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
876 located_tyvars = hsLTyVarLocNames tyvar_names
877 kinded_tyvars = [n | L _ (KindedTyVar n _) <- tyvar_names]
879 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
880 -- Find the type variables in the pattern type
881 -- signatures that must be brought into scope
882 bindPatSigTyVars tys thing_inside
883 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
884 ; if not scoped_tyvars then
887 do { name_env <- getLocalRdrEnv
888 ; let locd_tvs = [ tv | ty <- tys
889 , tv <- extractHsTyRdrTyVars ty
890 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
891 nubbed_tvs = nubBy eqLocated locd_tvs
892 -- The 'nub' is important. For example:
893 -- f (x :: t) (y :: t) = ....
894 -- We don't want to complain about binding t twice!
896 ; bindLocatedLocalsRn nubbed_tvs thing_inside }}
898 bindPatSigTyVarsFV :: [LHsType RdrName]
901 bindPatSigTyVarsFV tys thing_inside
902 = bindPatSigTyVars tys $ \ tvs ->
903 thing_inside `thenM` \ (result,fvs) ->
904 return (result, fvs `delListFromNameSet` tvs)
906 bindSigTyVarsFV :: [Name]
909 bindSigTyVarsFV tvs thing_inside
910 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
911 ; if not scoped_tyvars then
914 bindLocalNamesFV tvs thing_inside }
916 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
917 -- This function is used only in rnSourceDecl on InstDecl
918 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
920 -------------------------------------
921 checkDupRdrNames :: [Located RdrName] -> RnM ()
922 checkDupRdrNames rdr_names_w_loc
923 = -- Check for duplicated names in a binding group
924 mapM_ (dupNamesErr getLoc) dups
926 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
928 checkDupNames :: [Name] -> RnM ()
930 = -- Check for duplicated names in a binding group
931 mapM_ (dupNamesErr nameSrcSpan) dups
933 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
935 ---------------------
936 checkDupAndShadowedRdrNames :: [Located RdrName] -> RnM ()
937 checkDupAndShadowedRdrNames loc_rdr_names
938 = do { checkDupRdrNames loc_rdr_names
940 ; checkShadowedOccs envs loc_occs }
942 loc_occs = [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names]
944 checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
945 checkDupAndShadowedNames envs names
946 = do { checkDupNames names
947 ; checkShadowedOccs envs loc_occs }
949 loc_occs = [(nameSrcSpan name, nameOccName name) | name <- names]
951 -------------------------------------
952 checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
953 checkShadowedOccs (global_env,local_env) loc_occs
954 = ifOptM Opt_WarnNameShadowing $
955 do { traceRn (text "shadow" <+> ppr loc_occs)
956 ; mapM_ check_shadow loc_occs }
958 check_shadow (loc, occ)
959 | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
961 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
962 | otherwise = do { gres' <- filterM is_shadowed_gre gres
963 ; complain (map pprNameProvenance gres') }
965 complain [] = return ()
966 complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
967 mb_local = lookupLocalRdrOcc local_env occ
968 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
969 -- Make an Unqualified RdrName and look that up, so that
970 -- we don't find any GREs that are in scope qualified-only
972 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
973 -- Returns False for record selectors that are shadowed, when
974 -- punning or wild-cards are on (cf Trac #2723)
975 is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
976 = do { dflags <- getDOpts
977 ; if (dopt Opt_RecordPuns dflags || dopt Opt_RecordWildCards dflags)
978 then do { is_fld <- is_rec_fld gre; return (not is_fld) }
980 is_shadowed_gre _other = return True
982 is_rec_fld gre -- Return True for record selector ids
983 | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
984 ; return (gre_name gre `elemNameSet` fld_set) }
985 | otherwise = do { sel_id <- tcLookupField (gre_name gre)
986 ; return (isRecordSelector sel_id) }
990 %************************************************************************
992 \subsection{Free variable manipulation}
994 %************************************************************************
998 addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
999 addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
1000 ; return (res, fvs1 `plusFV` fvs2) }
1002 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
1003 mapFvRn f xs = do stuff <- mapM f xs
1005 (ys, fvs_s) -> return (ys, plusFVs fvs_s)
1007 mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
1008 mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
1009 mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
1011 -- because some of the rename functions are CPSed:
1012 -- maps the function across the list from left to right;
1013 -- collects all the free vars into one set
1014 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
1015 -> [a] -> ([b] -> RnM c) -> RnM c
1017 mapFvRnCPS _ [] cont = cont []
1018 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
1019 mapFvRnCPS f xs $ \ xs' ->
1024 %************************************************************************
1026 \subsection{Envt utility functions}
1028 %************************************************************************
1031 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
1032 warnUnusedModules mods
1033 = ifOptM Opt_WarnUnusedImports (mapM_ bleat mods)
1035 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
1036 mk_warn m = vcat [ptext (sLit "Module") <+> quotes (ppr m)
1037 <+> text "is imported, but nothing from it is used,",
1038 nest 2 (ptext (sLit "except perhaps instances visible in")
1039 <+> quotes (ppr m)),
1040 ptext (sLit "To suppress this warning, use:")
1041 <+> ptext (sLit "import") <+> ppr m <> parens empty ]
1044 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1045 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
1046 warnUnusedTopBinds gres
1047 = ifOptM Opt_WarnUnusedBinds
1048 $ do isBoot <- tcIsHsBoot
1049 let noParent gre = case gre_par gre of
1052 -- Don't warn about unused bindings with parents in
1053 -- .hs-boot files, as you are sometimes required to give
1054 -- unused bindings (trac #3449).
1055 gres' = if isBoot then filter noParent gres
1057 warnUnusedGREs gres'
1059 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1060 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
1061 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
1063 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
1064 check_unused flag bound_names used_names
1065 = ifOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1067 -------------------------
1069 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1071 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1073 warnUnusedLocals :: [Name] -> RnM ()
1074 warnUnusedLocals names
1075 = warnUnusedBinds [(n,LocalDef) | n<-names]
1077 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
1078 warnUnusedBinds names = mapM_ warnUnusedName (filter reportable names)
1079 where reportable (name,_)
1080 | isWiredInName name = False -- Don't report unused wired-in names
1081 -- Otherwise we get a zillion warnings
1083 | otherwise = not (startsWithUnderscore (nameOccName name))
1085 -------------------------
1087 warnUnusedName :: (Name, Provenance) -> RnM ()
1088 warnUnusedName (name, LocalDef)
1089 = addUnusedWarning name (nameSrcSpan name)
1090 (ptext (sLit "Defined but not used"))
1092 warnUnusedName (name, Imported is)
1095 warn spec = addUnusedWarning name span msg
1097 span = importSpecLoc spec
1098 pp_mod = quotes (ppr (importSpecModule spec))
1099 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1101 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1102 addUnusedWarning name span msg
1105 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1106 <+> quotes (ppr name)]
1110 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1111 addNameClashErrRn rdr_name names
1112 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1113 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1116 msg1 = ptext (sLit "either") <+> mk_ref np1
1117 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
1118 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1120 shadowedNameWarn :: OccName -> [SDoc] -> SDoc
1121 shadowedNameWarn occ shadowed_locs
1122 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1123 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1124 nest 2 (vcat shadowed_locs)]
1126 unknownNameErr :: RdrName -> SDoc
1127 unknownNameErr rdr_name
1128 = vcat [ hang (ptext (sLit "Not in scope:"))
1129 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1130 <+> quotes (ppr rdr_name))
1133 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1136 perhapsForallMsg :: SDoc
1138 = vcat [ ptext (sLit "Perhaps you intended to use -XExplicitForAll or similar flag")
1139 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1141 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1142 unknownSubordinateErr doc op -- Doc is "method of class" or
1143 -- "field of constructor"
1144 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1146 badOrigBinding :: RdrName -> SDoc
1148 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1149 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1151 dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
1152 dupNamesErr get_loc names
1153 = addErrAt big_loc $
1154 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1157 locs = map get_loc names
1158 big_loc = foldr1 combineSrcSpans locs
1159 locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sortLe (<=) locs))
1161 kindSigErr :: Outputable a => a -> SDoc
1163 = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
1164 2 (ptext (sLit "Perhaps you intended to use -XKindSignatures"))
1167 badQualBndrErr :: RdrName -> SDoc
1168 badQualBndrErr rdr_name
1169 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
1171 opDeclErr :: RdrName -> SDoc
1173 = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
1174 2 (ptext (sLit "Use -XTypeOperators to declare operators in type and declarations"))