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,
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 PrelNames ( mkUnboundName, rOOT_MAIN, iNTERACTIVE,
55 consDataConKey, forall_tv_RDR )
58 import ErrUtils ( Message )
63 import ListSetOps ( removeDups )
68 import qualified Data.Set as Set
73 thenM :: Monad a => a b -> (b -> a c) -> a c
77 %*********************************************************
81 %*********************************************************
84 newTopSrcBinder :: Located RdrName -> RnM Name
85 newTopSrcBinder (L loc rdr_name)
86 | Just name <- isExact_maybe rdr_name
87 = -- This is here to catch
88 -- (a) Exact-name binders created by Template Haskell
89 -- (b) The PrelBase defn of (say) [] and similar, for which
90 -- the parser reads the special syntax and returns an Exact RdrName
91 -- We are at a binding site for the name, so check first that it
92 -- the current module is the correct one; otherwise GHC can get
93 -- very confused indeed. This test rejects code like
94 -- data T = (,) Int Int
95 -- unless we are in GHC.Tup
96 ASSERT2( isExternalName name, ppr name )
97 do { this_mod <- getModule
98 ; unless (this_mod == nameModule name)
99 (addErrAt loc (badOrigBinding rdr_name))
103 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
104 = do { this_mod <- getModule
105 ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
106 (addErrAt loc (badOrigBinding rdr_name))
107 -- When reading External Core we get Orig names as binders,
108 -- but they should agree with the module gotten from the monad
110 -- We can get built-in syntax showing up here too, sadly. If you type
112 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
113 -- uses setRdrNameSpace to make it into a data constructors. At that point
114 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
115 -- Hence the badOrigBinding error message.
117 -- Except for the ":Main.main = ..." definition inserted into
118 -- the Main module; ugh!
120 -- Because of this latter case, we call newGlobalBinder with a module from
121 -- the RdrName, not from the environment. In principle, it'd be fine to
122 -- have an arbitrary mixture of external core definitions in a single module,
123 -- (apart from module-initialisation issues, perhaps).
124 ; newGlobalBinder rdr_mod rdr_occ loc }
125 --TODO, should pass the whole span
128 = do { unless (not (isQual rdr_name))
129 (addErrAt loc (badQualBndrErr rdr_name))
130 -- Binders should not be qualified; if they are, and with a different
131 -- module name, we we get a confusing "M.T is not in scope" error later
134 ; if isBrackStage stage then
135 -- We are inside a TH bracket, so make an *Internal* name
136 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
137 do { uniq <- newUnique
138 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
141 do { this_mod <- getModule
142 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } }
145 %*********************************************************
147 Source code occurrences
149 %*********************************************************
151 Looking up a name in the RnEnv.
153 Note [Type and class operator definitions]
154 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
155 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
157 class a :*: b where ...
158 data (:*:) a b = ....
159 class (:*:) a b where ...
160 The latter two mean that we are not just looking for a
161 *syntactically-infix* declaration, but one that uses an operator
162 OccName. We use OccName.isSymOcc to detect that case, which isn't
163 terribly efficient, but there seems to be no better way.
166 lookupTopBndrRn :: RdrName -> RnM Name
167 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
170 Nothing -> do traceRn $ text "lookupTopBndrRn"
173 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
174 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
176 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
177 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
178 -- and there may be several imported 'f's too, which must not confuse us.
179 -- For example, this is OK:
181 -- infix 9 f -- The 'f' here does not need to be qualified
182 -- f x = x -- Nor here, of course
183 -- So we have to filter out the non-local ones.
185 -- A separate function (importsFromLocalDecls) reports duplicate top level
186 -- decls, so here it's safe just to choose an arbitrary one.
188 -- There should never be a qualified name in a binding position in Haskell,
189 -- but there can be if we have read in an external-Core file.
190 -- The Haskell parser checks for the illegal qualified name in Haskell
191 -- source files, so we don't need to do so here.
193 lookupTopBndrRn_maybe rdr_name
194 | Just name <- isExact_maybe rdr_name
197 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
198 -- This deals with the case of derived bindings, where
199 -- we don't bother to call newTopSrcBinder first
200 -- We assume there is no "parent" name
201 = do { loc <- getSrcSpanM
202 ; n <- newGlobalBinder rdr_mod rdr_occ loc
206 = do { -- Check for operators in type or class declarations
207 -- See Note [Type and class operator definitions]
208 let occ = rdrNameOcc rdr_name
209 ; when (isTcOcc occ && isSymOcc occ)
210 (do { op_ok <- xoptM Opt_TypeOperators
211 ; unless op_ok (addErr (opDeclErr rdr_name)) })
213 ; mb_gre <- lookupGreLocalRn rdr_name
215 Nothing -> return Nothing
216 Just gre -> return (Just $ gre_name gre) }
219 -----------------------------------------------
220 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
221 -- This is called on the method name on the left-hand side of an
222 -- instance declaration binding. eg. instance Functor T where
224 -- ^^^^ called on this
225 -- Regardless of how many unqualified fmaps are in scope, we want
226 -- the one that comes from the Functor class.
228 -- Furthermore, note that we take no account of whether the
229 -- name is only in scope qualified. I.e. even if method op is
230 -- in scope as M.op, we still allow plain 'op' on the LHS of
232 lookupInstDeclBndr cls rdr
233 = do { when (isQual rdr)
234 (addErr (badQualBndrErr rdr))
235 -- In an instance decl you aren't allowed
236 -- to use a qualified name for the method
237 -- (Although it'd make perfect sense.)
238 ; lookupSubBndr (ParentIs cls) doc rdr }
240 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
242 -----------------------------------------------
243 lookupConstructorFields :: Name -> RnM [Name]
244 -- Look up the fields of a given constructor
245 -- * For constructors from this module, use the record field env,
246 -- which is itself gathered from the (as yet un-typechecked)
249 -- * For constructors from imported modules, use the *type* environment
250 -- since imported modles are already compiled, the info is conveniently
253 lookupConstructorFields con_name
254 = do { this_mod <- getModule
255 ; if nameIsLocalOrFrom this_mod con_name then
256 do { RecFields field_env _ <- getRecFieldEnv
257 ; return (lookupNameEnv field_env con_name `orElse` []) }
259 do { con <- tcLookupDataCon con_name
260 ; return (dataConFieldLabels con) } }
262 -----------------------------------------------
263 -- Used for record construction and pattern matching
264 -- When the -XDisambiguateRecordFields flag is on, take account of the
265 -- constructor name to disambiguate which field to use; it's just the
266 -- same as for instance decls
268 -- NB: Consider this:
269 -- module Foo where { data R = R { fld :: Int } }
270 -- module Odd where { import Foo; fld x = x { fld = 3 } }
271 -- Arguably this should work, because the reference to 'fld' is
272 -- unambiguous because there is only one field id 'fld' in scope.
273 -- But currently it's rejected.
275 lookupSubBndr :: Parent -- NoParent => just look it up as usual
276 -- ParentIs p => use p to disambiguate
279 lookupSubBndr parent doc rdr_name
280 | Just n <- isExact_maybe rdr_name -- This happens in derived code
283 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
284 = lookupOrig rdr_mod rdr_occ
286 | otherwise -- Find all the things the rdr-name maps to
287 = do { -- and pick the one with the right parent name
288 ; env <- getGlobalRdrEnv
289 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
290 ; case pick parent gres of
291 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
292 -- The latter does pickGREs, but we want to allow 'x'
293 -- even if only 'M.x' is in scope
294 [gre] -> do { addUsedRdrNames (used_rdr_names gre)
295 ; return (gre_name gre) }
296 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
297 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> (ppr rdr_name $$ ppr gres))
298 ; return (mkUnboundName rdr_name) }
299 gres -> do { addNameClashErrRn rdr_name gres
300 ; return (gre_name (head gres)) } }
302 pick NoParent gres -- Normal lookup
303 = pickGREs rdr_name gres
304 pick (ParentIs p) gres -- Disambiguating lookup
305 | isUnqual rdr_name = filter (right_parent p) gres
306 | otherwise = filter (right_parent p) (pickGREs rdr_name gres)
308 right_parent p (GRE { gre_par = ParentIs p' }) = p==p'
309 right_parent _ _ = False
311 -- Note [Usage for sub-bndrs]
313 | isQual rdr_name = [rdr_name]
314 | otherwise = case gre_prov gre of
315 LocalDef -> [rdr_name]
316 Imported is -> map mk_qual_rdr is
317 mk_qual_rdr imp_spec = mkRdrQual (is_as (is_decl imp_spec)) rdr_occ
318 rdr_occ = rdrNameOcc rdr_name
320 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
321 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
323 -- If the family is declared locally, it will not yet be in the main
324 -- environment; hence, we pass in an extra one here, which we check first.
325 -- See "Note [Looking up family names in family instances]" in 'RnNames'.
327 lookupFamInstDeclBndr :: GlobalRdrEnv -> Located RdrName -> RnM Name
328 lookupFamInstDeclBndr tyclGroupEnv (L loc rdr_name)
330 case lookupGRE_RdrName rdr_name tyclGroupEnv of
331 (gre:_) -> return $ gre_name gre
332 -- if there is more than one, an error will be raised elsewhere
333 [] -> lookupOccRn rdr_name
336 Note [Usage for sub-bndrs]
337 ~~~~~~~~~~~~~~~~~~~~~~~~~~
339 import qualified M( C( f ) )
342 then is the qualified import M.f used? Obviously yes.
343 But the RdrName used in the instance decl is unqualified. In effect,
344 we fill in the qualification by looking for f's whose class is M.C
345 But when adding to the UsedRdrNames we must make that qualification
346 explicit, otherwise we get "Redundant import of M.C".
348 --------------------------------------------------
350 --------------------------------------------------
353 getLookupOccRn :: RnM (Name -> Maybe Name)
355 = getLocalRdrEnv `thenM` \ local_env ->
356 return (lookupLocalRdrOcc local_env . nameOccName)
358 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
359 lookupLocatedOccRn = wrapLocM lookupOccRn
361 -- lookupOccRn looks up an occurrence of a RdrName
362 lookupOccRn :: RdrName -> RnM Name
364 = getLocalRdrEnv `thenM` \ local_env ->
365 case lookupLocalRdrEnv local_env rdr_name of
366 Just name -> return name
367 Nothing -> lookupGlobalOccRn rdr_name
369 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
370 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
372 lookupGlobalOccRn :: RdrName -> RnM Name
373 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
374 -- environment. Adds an error message if the RdrName is not in scope.
375 -- Also has a special case for GHCi.
377 lookupGlobalOccRn rdr_name
378 = do { -- First look up the name in the normal environment.
379 mb_name <- lookupGlobalOccRn_maybe rdr_name
384 { -- We allow qualified names on the command line to refer to
385 -- *any* name exported by any module in scope, just as if there
386 -- was an "import qualified M" declaration for every module.
387 allow_qual <- doptM Opt_ImplicitImportQualified
389 -- This test is not expensive,
390 -- and only happens for failed lookups
391 ; if isQual rdr_name && allow_qual && mod == iNTERACTIVE
392 then lookupQualifiedName rdr_name
393 else unboundName rdr_name } } }
395 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
396 -- No filter function; does not report an error on failure
398 lookupGlobalOccRn_maybe rdr_name
399 | Just n <- isExact_maybe rdr_name -- This happens in derived code
402 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
403 = do { n <- lookupOrig rdr_mod rdr_occ; return (Just n) }
406 = do { mb_gre <- lookupGreRn_maybe rdr_name
408 Nothing -> return Nothing
409 Just gre -> return (Just (gre_name gre)) }
412 unboundName :: RdrName -> RnM Name
414 = do { addErr (unknownNameErr rdr_name)
415 ; env <- getGlobalRdrEnv;
416 ; traceRn (vcat [unknownNameErr rdr_name,
417 ptext (sLit "Global envt is:"),
418 nest 3 (pprGlobalRdrEnv env)])
419 ; return (mkUnboundName rdr_name) }
421 --------------------------------------------------
422 -- Lookup in the Global RdrEnv of the module
423 --------------------------------------------------
425 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
426 -- Just look up the RdrName in the GlobalRdrEnv
427 lookupGreRn_maybe rdr_name
428 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
430 lookupGreRn :: RdrName -> RnM GlobalRdrElt
431 -- If not found, add error message, and return a fake GRE
433 = do { mb_gre <- lookupGreRn_maybe rdr_name
435 Just gre -> return gre ;
437 { traceRn $ text "lookupGreRn"
438 ; name <- unboundName rdr_name
439 ; return (GRE { gre_name = name, gre_par = NoParent,
440 gre_prov = LocalDef }) }}}
442 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
443 -- Similar, but restricted to locally-defined things
444 lookupGreLocalRn rdr_name
445 = lookupGreRn_help rdr_name lookup_fn
447 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
449 lookupGreRn_help :: RdrName -- Only used in error message
450 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
451 -> RnM (Maybe GlobalRdrElt)
452 -- Checks for exactly one match; reports deprecations
453 -- Returns Nothing, without error, if too few
454 lookupGreRn_help rdr_name lookup
455 = do { env <- getGlobalRdrEnv
458 [gre] -> do { addUsedRdrName gre rdr_name
459 ; return (Just gre) }
460 gres -> do { addNameClashErrRn rdr_name gres
461 ; return (Just (head gres)) } }
463 addUsedRdrName :: GlobalRdrElt -> RdrName -> RnM ()
464 -- Record usage of imported RdrNames
465 addUsedRdrName gre rdr
466 | isLocalGRE gre = return ()
467 | otherwise = do { env <- getGblEnv
468 ; updMutVar (tcg_used_rdrnames env)
469 (\s -> Set.insert rdr s) }
471 addUsedRdrNames :: [RdrName] -> RnM ()
472 -- Record used sub-binders
473 -- We don't check for imported-ness here, because it's inconvenient
474 -- and not stritly necessary.
476 = do { env <- getGblEnv
477 ; updMutVar (tcg_used_rdrnames env)
478 (\s -> foldr Set.insert s rdrs) }
480 ------------------------------
482 ------------------------------
484 -- A qualified name on the command line can refer to any module at all: we
485 -- try to load the interface if we don't already have it.
486 lookupQualifiedName :: RdrName -> RnM Name
487 lookupQualifiedName rdr_name
488 | Just (mod,occ) <- isQual_maybe rdr_name
489 -- Note: we want to behave as we would for a source file import here,
490 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
491 = loadSrcInterface doc mod False Nothing `thenM` \ iface ->
494 (mod,avails) <- mi_exports iface,
496 name <- availNames avail,
498 ((mod,occ):ns) -> ASSERT (null ns)
500 _ -> unboundName rdr_name
503 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
505 doc = ptext (sLit "Need to find") <+> ppr rdr_name
508 Note [Looking up signature names]
509 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
510 lookupSigOccRn is used for type signatures and pragmas
516 It's clear that the 'f' in the signature must refer to A.f
517 The Haskell98 report does not stipulate this, but it will!
518 So we must treat the 'f' in the signature in the same way
519 as the binding occurrence of 'f', using lookupBndrRn
521 However, consider this case:
525 We don't want to say 'f' is out of scope; instead, we want to
526 return the imported 'f', so that later on the reanamer will
527 correctly report "misplaced type sig".
530 lookupSigOccRn :: Maybe NameSet -- Just ns => these are the binders
532 -- Nothing => signatures without
533 -- binders are expected
534 -- (a) top-level (SPECIALISE prags)
538 -> Located RdrName -> RnM (Located Name)
539 lookupSigOccRn mb_bound_names sig
540 = wrapLocM $ \ rdr_name ->
541 do { mb_name <- lookupBindGroupOcc mb_bound_names (hsSigDoc sig) rdr_name
543 Left err -> do { addErr err; return (mkUnboundName rdr_name) }
544 Right name -> return name }
546 lookupBindGroupOcc :: Maybe NameSet -- See notes on the (Maybe NameSet)
547 -> SDoc -- in lookupSigOccRn
548 -> RdrName -> RnM (Either Message Name)
549 -- Looks up the RdrName, expecting it to resolve to one of the
550 -- bound names passed in. If not, return an appropriate error message
552 -- See Note [Looking up signature names]
553 lookupBindGroupOcc mb_bound_names what rdr_name
554 = do { local_env <- getLocalRdrEnv
555 ; case lookupLocalRdrEnv local_env rdr_name of
556 Just n -> check_local_name n
557 Nothing -> do -- Not defined in a nested scope
559 { env <- getGlobalRdrEnv
560 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
561 ; case (filter isLocalGRE gres) of
562 (gre:_) -> check_local_name (gre_name gre)
563 -- If there is more than one local GRE for the
564 -- same OccName 'f', that will be reported separately
565 -- as a duplicate top-level binding for 'f'
566 [] | null gres -> bale_out_with empty
567 | otherwise -> bale_out_with import_msg
570 check_local_name name -- The name is in scope, and not imported
571 = case mb_bound_names of
572 Just bound_names | not (name `elemNameSet` bound_names)
573 -> bale_out_with local_msg
574 _other -> return (Right name)
577 = return (Left (sep [ ptext (sLit "The") <+> what
578 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
579 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
582 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
583 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
585 import_msg = parens $ ptext (sLit "You cannot give a") <+> what
586 <+> ptext (sLit "for an imported value")
589 lookupLocalDataTcNames :: NameSet -> SDoc -> RdrName -> RnM [Name]
590 -- GHC extension: look up both the tycon and data con
591 -- for con-like things
592 -- Complain if neither is in scope
593 lookupLocalDataTcNames bound_names what rdr_name
594 | Just n <- isExact_maybe rdr_name
595 -- Special case for (:), which doesn't get into the GlobalRdrEnv
596 = return [n] -- For this we don't need to try the tycon too
598 = do { mb_gres <- mapM (lookupBindGroupOcc (Just bound_names) what)
599 (dataTcOccs rdr_name)
600 ; let (errs, names) = splitEithers mb_gres
601 ; when (null names) (addErr (head errs)) -- Bleat about one only
604 dataTcOccs :: RdrName -> [RdrName]
605 -- If the input is a data constructor, return both it and a type
606 -- constructor. This is useful when we aren't sure which we are
609 | Just n <- isExact_maybe rdr_name -- Ghastly special case
610 , n `hasKey` consDataConKey = [rdr_name] -- see note below
611 | isDataOcc occ = [rdr_name, rdr_name_tc]
612 | otherwise = [rdr_name]
614 occ = rdrNameOcc rdr_name
615 rdr_name_tc = setRdrNameSpace rdr_name tcName
617 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
618 -- and setRdrNameSpace generates an Orig, which is fine
619 -- But it's not fine for (:), because there *is* no corresponding type
620 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
621 -- appear to be in scope (because Orig's simply allocate a new name-cache
622 -- entry) and then we get an error when we use dataTcOccs in
623 -- TcRnDriver.tcRnGetInfo. Large sigh.
627 %*********************************************************
631 %*********************************************************
634 --------------------------------
635 type FastStringEnv a = UniqFM a -- Keyed by FastString
638 emptyFsEnv :: FastStringEnv a
639 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
640 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
642 emptyFsEnv = emptyUFM
643 lookupFsEnv = lookupUFM
644 extendFsEnv = addToUFM
646 --------------------------------
647 type MiniFixityEnv = FastStringEnv (Located Fixity)
648 -- Mini fixity env for the names we're about
649 -- to bind, in a single binding group
651 -- It is keyed by the *FastString*, not the *OccName*, because
652 -- the single fixity decl infix 3 T
653 -- affects both the data constructor T and the type constrctor T
655 -- We keep the location so that if we find
656 -- a duplicate, we can report it sensibly
658 --------------------------------
659 -- Used for nested fixity decls to bind names along with their fixities.
660 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
662 addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
663 addLocalFixities mini_fix_env names thing_inside
664 = extendFixityEnv (mapCatMaybes find_fixity names) thing_inside
667 = case lookupFsEnv mini_fix_env (occNameFS occ) of
668 Just (L _ fix) -> Just (name, FixItem occ fix)
671 occ = nameOccName name
674 --------------------------------
675 lookupFixity is a bit strange.
677 * Nested local fixity decls are put in the local fixity env, which we
678 find with getFixtyEnv
680 * Imported fixities are found in the HIT or PIT
682 * Top-level fixity decls in this module may be for Names that are
683 either Global (constructors, class operations)
684 or Local/Exported (everything else)
685 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
686 We put them all in the local fixity environment
689 lookupFixityRn :: Name -> RnM Fixity
691 = getModule `thenM` \ this_mod ->
692 if nameIsLocalOrFrom this_mod name
693 then do -- It's defined in this module
694 local_fix_env <- getFixityEnv
695 traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
696 vcat [ppr name, ppr local_fix_env])
697 return $ lookupFixity local_fix_env name
698 else -- It's imported
699 -- For imported names, we have to get their fixities by doing a
700 -- loadInterfaceForName, and consulting the Ifaces that comes back
701 -- from that, because the interface file for the Name might not
702 -- have been loaded yet. Why not? Suppose you import module A,
703 -- which exports a function 'f', thus;
704 -- module CurrentModule where
706 -- module A( f ) where
708 -- Then B isn't loaded right away (after all, it's possible that
709 -- nothing from B will be used). When we come across a use of
710 -- 'f', we need to know its fixity, and it's then, and only
711 -- then, that we load B.hi. That is what's happening here.
713 -- loadInterfaceForName will find B.hi even if B is a hidden module,
714 -- and that's what we want.
715 loadInterfaceForName doc name `thenM` \ iface -> do {
716 traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
717 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
718 return (mi_fix_fn iface (nameOccName name))
721 doc = ptext (sLit "Checking fixity for") <+> ppr name
724 lookupTyFixityRn :: Located Name -> RnM Fixity
725 lookupTyFixityRn (L _ n) = lookupFixityRn n
729 %************************************************************************
732 Dealing with rebindable syntax is driven by the
733 Opt_RebindableSyntax dynamic flag.
735 In "deriving" code we don't want to use rebindable syntax
736 so we switch off the flag locally
739 %************************************************************************
741 Haskell 98 says that when you say "3" you get the "fromInteger" from the
742 Standard Prelude, regardless of what is in scope. However, to experiment
743 with having a language that is less coupled to the standard prelude, we're
744 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
745 happens to be in scope. Then you can
747 import MyPrelude as Prelude
748 to get the desired effect.
750 At the moment this just happens for
751 * fromInteger, fromRational on literals (in expressions and patterns)
752 * negate (in expressions)
753 * minus (arising from n+k patterns)
756 We store the relevant Name in the HsSyn tree, in
757 * HsIntegral/HsFractional/HsIsString
761 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
762 fromRationalName etc), but the renamer changes this to the appropriate user
763 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
765 We treat the orignal (standard) names as free-vars too, because the type checker
766 checks the type of the user thing against the type of the standard thing.
769 lookupSyntaxName :: Name -- The standard name
770 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
771 lookupSyntaxName std_name
772 = xoptM Opt_RebindableSyntax `thenM` \ rebindable_on ->
773 if not rebindable_on then normal_case
775 -- Get the similarly named thing from the local environment
776 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
777 return (HsVar usr_name, unitFV usr_name)
779 normal_case = return (HsVar std_name, emptyFVs)
781 lookupSyntaxTable :: [Name] -- Standard names
782 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
783 lookupSyntaxTable std_names
784 = xoptM Opt_RebindableSyntax `thenM` \ rebindable_on ->
785 if not rebindable_on then normal_case
787 -- Get the similarly named thing from the local environment
788 mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
790 return (std_names `zip` map HsVar usr_names, mkFVs usr_names)
792 normal_case = return (std_names `zip` map HsVar std_names, emptyFVs)
796 %*********************************************************
800 %*********************************************************
803 newLocalBndrRn :: Located RdrName -> RnM Name
804 -- Used for non-top-level binders. These should
805 -- never be qualified.
806 newLocalBndrRn (L loc rdr_name)
807 | Just name <- isExact_maybe rdr_name
808 = return name -- This happens in code generated by Template Haskell
809 -- although I'm not sure why. Perhpas it's the call
810 -- in RnPat.newName LetMk?
812 = do { unless (isUnqual rdr_name)
813 (addErrAt loc (badQualBndrErr rdr_name))
815 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
817 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
818 newLocalBndrsRn = mapM newLocalBndrRn
820 ---------------------
821 bindLocatedLocalsRn :: [Located RdrName]
824 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
825 = do { checkDupAndShadowedRdrNames rdr_names_w_loc
827 -- Make fresh Names and extend the environment
828 ; names <- newLocalBndrsRn rdr_names_w_loc
829 ; bindLocalNames names (enclosed_scope names) }
831 bindLocalNames :: [Name] -> RnM a -> RnM a
832 bindLocalNames names enclosed_scope
833 = do { name_env <- getLocalRdrEnv
834 ; setLocalRdrEnv (extendLocalRdrEnvList name_env names)
837 bindLocalName :: Name -> RnM a -> RnM a
838 bindLocalName name enclosed_scope
839 = do { name_env <- getLocalRdrEnv
840 ; setLocalRdrEnv (extendLocalRdrEnv name_env name)
843 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
844 bindLocalNamesFV names enclosed_scope
845 = do { (result, fvs) <- bindLocalNames names enclosed_scope
846 ; return (result, delFVs names fvs) }
849 -------------------------------------
850 -- binLocalsFVRn is the same as bindLocalsRn
851 -- except that it deals with free vars
852 bindLocatedLocalsFV :: [Located RdrName]
853 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
854 bindLocatedLocalsFV rdr_names enclosed_scope
855 = bindLocatedLocalsRn rdr_names $ \ names ->
856 enclosed_scope names `thenM` \ (thing, fvs) ->
857 return (thing, delFVs names fvs)
859 -------------------------------------
860 bindTyVarsFV :: [LHsTyVarBndr RdrName]
861 -> ([LHsTyVarBndr Name] -> RnM (a, FreeVars))
863 bindTyVarsFV tyvars thing_inside
864 = bindTyVarsRn tyvars $ \ tyvars' ->
865 do { (res, fvs) <- thing_inside tyvars'
866 ; return (res, delFVs (map hsLTyVarName tyvars') fvs) }
868 bindTyVarsRn :: [LHsTyVarBndr RdrName]
869 -> ([LHsTyVarBndr Name] -> RnM a)
871 -- Haskell-98 binding of type variables; e.g. within a data type decl
872 bindTyVarsRn tyvar_names enclosed_scope
873 = bindLocatedLocalsRn located_tyvars $ \ names ->
874 do { kind_sigs_ok <- xoptM Opt_KindSignatures
875 ; unless (null kinded_tyvars || kind_sigs_ok)
876 (mapM_ (addErr . kindSigErr) kinded_tyvars)
877 ; enclosed_scope (zipWith replace tyvar_names names) }
879 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
880 located_tyvars = hsLTyVarLocNames tyvar_names
881 kinded_tyvars = [n | L _ (KindedTyVar n _) <- tyvar_names]
883 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
884 -- Find the type variables in the pattern type
885 -- signatures that must be brought into scope
886 bindPatSigTyVars tys thing_inside
887 = do { scoped_tyvars <- xoptM Opt_ScopedTypeVariables
888 ; if not scoped_tyvars then
891 do { name_env <- getLocalRdrEnv
892 ; let locd_tvs = [ tv | ty <- tys
893 , tv <- extractHsTyRdrTyVars ty
894 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
895 nubbed_tvs = nubBy eqLocated locd_tvs
896 -- The 'nub' is important. For example:
897 -- f (x :: t) (y :: t) = ....
898 -- We don't want to complain about binding t twice!
900 ; bindLocatedLocalsRn nubbed_tvs thing_inside }}
902 bindPatSigTyVarsFV :: [LHsType RdrName]
905 bindPatSigTyVarsFV tys thing_inside
906 = bindPatSigTyVars tys $ \ tvs ->
907 thing_inside `thenM` \ (result,fvs) ->
908 return (result, fvs `delListFromNameSet` tvs)
910 bindSigTyVarsFV :: [Name]
913 bindSigTyVarsFV tvs thing_inside
914 = do { scoped_tyvars <- xoptM Opt_ScopedTypeVariables
915 ; if not scoped_tyvars then
918 bindLocalNamesFV tvs thing_inside }
920 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
921 -- This function is used only in rnSourceDecl on InstDecl
922 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
924 -------------------------------------
925 checkDupRdrNames :: [Located RdrName] -> RnM ()
926 checkDupRdrNames rdr_names_w_loc
927 = -- Check for duplicated names in a binding group
928 mapM_ (dupNamesErr getLoc) dups
930 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
932 checkDupNames :: [Name] -> RnM ()
934 = -- Check for duplicated names in a binding group
935 mapM_ (dupNamesErr nameSrcSpan) dups
937 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
939 ---------------------
940 checkDupAndShadowedRdrNames :: [Located RdrName] -> RnM ()
941 checkDupAndShadowedRdrNames loc_rdr_names
942 = do { checkDupRdrNames loc_rdr_names
944 ; checkShadowedOccs envs loc_occs }
946 loc_occs = [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names]
948 checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
949 checkDupAndShadowedNames envs names
950 = do { checkDupNames names
951 ; checkShadowedOccs envs loc_occs }
953 loc_occs = [(nameSrcSpan name, nameOccName name) | name <- names]
955 -------------------------------------
956 checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
957 checkShadowedOccs (global_env,local_env) loc_occs
958 = ifDOptM Opt_WarnNameShadowing $
959 do { traceRn (text "shadow" <+> ppr loc_occs)
960 ; mapM_ check_shadow loc_occs }
962 check_shadow (loc, occ)
963 | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
965 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
966 | otherwise = do { gres' <- filterM is_shadowed_gre gres
967 ; complain (map pprNameProvenance gres') }
969 complain [] = return ()
970 complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
971 mb_local = lookupLocalRdrOcc local_env occ
972 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
973 -- Make an Unqualified RdrName and look that up, so that
974 -- we don't find any GREs that are in scope qualified-only
976 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
977 -- Returns False for record selectors that are shadowed, when
978 -- punning or wild-cards are on (cf Trac #2723)
979 is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
980 = do { dflags <- getDOpts
981 ; if (xopt Opt_RecordPuns dflags || xopt Opt_RecordWildCards dflags)
982 then do { is_fld <- is_rec_fld gre; return (not is_fld) }
984 is_shadowed_gre _other = return True
986 is_rec_fld gre -- Return True for record selector ids
987 | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
988 ; return (gre_name gre `elemNameSet` fld_set) }
989 | otherwise = do { sel_id <- tcLookupField (gre_name gre)
990 ; return (isRecordSelector sel_id) }
994 %************************************************************************
996 \subsection{Free variable manipulation}
998 %************************************************************************
1002 addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
1003 addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
1004 ; return (res, fvs1 `plusFV` fvs2) }
1006 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
1007 mapFvRn f xs = do stuff <- mapM f xs
1009 (ys, fvs_s) -> return (ys, plusFVs fvs_s)
1011 mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
1012 mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
1013 mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
1015 -- because some of the rename functions are CPSed:
1016 -- maps the function across the list from left to right;
1017 -- collects all the free vars into one set
1018 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
1019 -> [a] -> ([b] -> RnM c) -> RnM c
1021 mapFvRnCPS _ [] cont = cont []
1022 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
1023 mapFvRnCPS f xs $ \ xs' ->
1028 %************************************************************************
1030 \subsection{Envt utility functions}
1032 %************************************************************************
1035 warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1036 warnUnusedTopBinds gres
1037 = ifDOptM Opt_WarnUnusedBinds
1038 $ do isBoot <- tcIsHsBoot
1039 let noParent gre = case gre_par gre of
1042 -- Don't warn about unused bindings with parents in
1043 -- .hs-boot files, as you are sometimes required to give
1044 -- unused bindings (trac #3449).
1045 gres' = if isBoot then filter noParent gres
1047 warnUnusedGREs gres'
1049 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1050 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
1051 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
1053 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
1054 check_unused flag bound_names used_names
1055 = ifDOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1057 -------------------------
1059 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1061 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1063 warnUnusedLocals :: [Name] -> RnM ()
1064 warnUnusedLocals names
1065 = warnUnusedBinds [(n,LocalDef) | n<-names]
1067 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
1068 warnUnusedBinds names = mapM_ warnUnusedName (filter reportable names)
1069 where reportable (name,_)
1070 | isWiredInName name = False -- Don't report unused wired-in names
1071 -- Otherwise we get a zillion warnings
1073 | otherwise = not (startsWithUnderscore (nameOccName name))
1075 -------------------------
1077 warnUnusedName :: (Name, Provenance) -> RnM ()
1078 warnUnusedName (name, LocalDef)
1079 = addUnusedWarning name (nameSrcSpan name)
1080 (ptext (sLit "Defined but not used"))
1082 warnUnusedName (name, Imported is)
1085 warn spec = addUnusedWarning name span msg
1087 span = importSpecLoc spec
1088 pp_mod = quotes (ppr (importSpecModule spec))
1089 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1091 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1092 addUnusedWarning name span msg
1095 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1096 <+> quotes (ppr name)]
1100 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1101 addNameClashErrRn rdr_name names
1102 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1103 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1106 msg1 = ptext (sLit "either") <+> mk_ref np1
1107 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
1108 mk_ref gre = sep [quotes (ppr (gre_name gre)) <> comma, pprNameProvenance gre]
1110 shadowedNameWarn :: OccName -> [SDoc] -> SDoc
1111 shadowedNameWarn occ shadowed_locs
1112 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1113 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1114 nest 2 (vcat shadowed_locs)]
1116 unknownNameErr :: RdrName -> SDoc
1117 unknownNameErr rdr_name
1118 = vcat [ hang (ptext (sLit "Not in scope:"))
1119 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1120 <+> quotes (ppr rdr_name))
1123 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1126 perhapsForallMsg :: SDoc
1128 = vcat [ ptext (sLit "Perhaps you intended to use -XExplicitForAll or similar flag")
1129 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1131 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1132 unknownSubordinateErr doc op -- Doc is "method of class" or
1133 -- "field of constructor"
1134 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1136 badOrigBinding :: RdrName -> SDoc
1138 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1139 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1141 dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
1142 dupNamesErr get_loc names
1143 = addErrAt big_loc $
1144 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1147 locs = map get_loc names
1148 big_loc = foldr1 combineSrcSpans locs
1149 locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sortLe (<=) locs))
1151 kindSigErr :: Outputable a => a -> SDoc
1153 = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
1154 2 (ptext (sLit "Perhaps you intended to use -XKindSignatures"))
1157 badQualBndrErr :: RdrName -> SDoc
1158 badQualBndrErr rdr_name
1159 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
1161 opDeclErr :: RdrName -> SDoc
1163 = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
1164 2 (ptext (sLit "Use -XTypeOperators to declare operators in type and declarations"))