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, lookupRecordBndr, lookupConstructorFields,
16 lookupSyntaxName, lookupSyntaxTable,
17 lookupGreRn, lookupGreLocalRn, lookupGreRn_maybe,
20 newLocalsRn, newIPNameRn,
21 bindLocalNames, bindLocalNamesFV,
22 MiniFixityEnv, emptyFsEnv, extendFsEnv, lookupFsEnv,
23 bindLocalNamesFV_WithFixities,
24 bindLocatedLocalsFV, bindLocatedLocalsRn,
25 bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
26 bindTyVarsRn, extendTyVarEnvFVRn,
28 checkDupRdrNames, checkDupNames, checkShadowedNames,
29 checkDupAndShadowedRdrNames,
31 warnUnusedMatches, warnUnusedModules, warnUnusedImports,
32 warnUnusedTopBinds, warnUnusedLocalBinds,
33 dataTcOccs, unknownNameErr, kindSigErr, perhapsForallMsg,
38 #include "HsVersions.h"
40 import LoadIface ( loadInterfaceForName, loadSrcInterface )
41 import IfaceEnv ( lookupOrig, newGlobalBinder, newIPName )
43 import RdrHsSyn ( extractHsTyRdrTyVars )
45 import HscTypes ( availNames, ModIface(..), FixItem(..), lookupFixity)
46 import TcEnv ( tcLookupDataCon, tcLookupField, isBrackStage )
48 import Id ( isRecordSelector )
49 import Name ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
50 nameSrcLoc, nameSrcSpan, nameOccName, nameModule, isExternalName )
54 import DataCon ( dataConFieldLabels )
56 import Module ( Module, ModuleName )
57 import PrelNames ( mkUnboundName, rOOT_MAIN, iNTERACTIVE,
58 consDataConKey, hasKey, forall_tv_RDR )
60 import BasicTypes ( IPName, mapIPName, Fixity )
61 import ErrUtils ( Message )
66 import ListSetOps ( removeDups )
75 thenM :: Monad a => a b -> (b -> a c) -> a c
78 thenM_ :: Monad a => a b -> a c -> a c
81 returnM :: Monad m => a -> m a
84 mappM :: (Monad m) => (a -> m b) -> [a] -> m [b]
87 mappM_ :: (Monad m) => (a -> m b) -> [a] -> m ()
90 checkM :: Monad m => Bool -> m () -> m ()
94 %*********************************************************
98 %*********************************************************
101 newTopSrcBinder :: Module -> Located RdrName -> RnM Name
102 newTopSrcBinder this_mod (L loc rdr_name)
103 | Just name <- isExact_maybe rdr_name
104 = -- This is here to catch
105 -- (a) Exact-name binders created by Template Haskell
106 -- (b) The PrelBase defn of (say) [] and similar, for which
107 -- the parser reads the special syntax and returns an Exact RdrName
108 -- We are at a binding site for the name, so check first that it
109 -- the current module is the correct one; otherwise GHC can get
110 -- very confused indeed. This test rejects code like
111 -- data T = (,) Int Int
112 -- unless we are in GHC.Tup
113 ASSERT2( isExternalName name, ppr name )
114 do { checkM (this_mod == nameModule name)
115 (addErrAt loc (badOrigBinding rdr_name))
119 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
120 = do { checkM (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
121 (addErrAt loc (badOrigBinding rdr_name))
122 -- When reading External Core we get Orig names as binders,
123 -- but they should agree with the module gotten from the monad
125 -- We can get built-in syntax showing up here too, sadly. If you type
127 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
128 -- uses setRdrNameSpace to make it into a data constructors. At that point
129 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
130 -- Hence the badOrigBinding error message.
132 -- Except for the ":Main.main = ..." definition inserted into
133 -- the Main module; ugh!
135 -- Because of this latter case, we call newGlobalBinder with a module from
136 -- the RdrName, not from the environment. In principle, it'd be fine to
137 -- have an arbitrary mixture of external core definitions in a single module,
138 -- (apart from module-initialisation issues, perhaps).
139 ; newGlobalBinder rdr_mod rdr_occ loc }
140 --TODO, should pass the whole span
143 = do { checkM (not (isQual rdr_name))
144 (addErrAt loc (badQualBndrErr rdr_name))
145 -- Binders should not be qualified; if they are, and with a different
146 -- module name, we we get a confusing "M.T is not in scope" error later
149 ; if isBrackStage stage then
150 -- We are inside a TH bracket, so make an *Internal* name
151 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
152 do { uniq <- newUnique
153 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
156 newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
159 %*********************************************************
161 Source code occurrences
163 %*********************************************************
165 Looking up a name in the RnEnv.
167 Note [Type and class operator definitions]
168 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
169 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
171 class a :*: b where ...
172 data (:*:) a b = ....
173 class (:*:) a b where ...
174 The latter two mean that we are not just looking for a
175 *syntactically-infix* declaration, but one that uses an operator
176 OccName. We use OccName.isSymOcc to detect that case, which isn't
177 terribly efficient, but there seems to be no better way.
180 lookupTopBndrRn :: RdrName -> RnM Name
181 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
184 Nothing -> do traceRn $ text "lookupTopBndrRn"
187 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
188 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
190 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
191 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
192 -- and there may be several imported 'f's too, which must not confuse us.
193 -- For example, this is OK:
195 -- infix 9 f -- The 'f' here does not need to be qualified
196 -- f x = x -- Nor here, of course
197 -- So we have to filter out the non-local ones.
199 -- A separate function (importsFromLocalDecls) reports duplicate top level
200 -- decls, so here it's safe just to choose an arbitrary one.
202 -- There should never be a qualified name in a binding position in Haskell,
203 -- but there can be if we have read in an external-Core file.
204 -- The Haskell parser checks for the illegal qualified name in Haskell
205 -- source files, so we don't need to do so here.
207 lookupTopBndrRn_maybe rdr_name
208 | Just name <- isExact_maybe rdr_name
209 = returnM (Just name)
211 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
212 -- This deals with the case of derived bindings, where
213 -- we don't bother to call newTopSrcBinder first
214 -- We assume there is no "parent" name
215 = do { loc <- getSrcSpanM
216 ; n <- newGlobalBinder rdr_mod rdr_occ loc
220 = do { -- Check for operators in type or class declarations
221 -- See Note [Type and class operator definitions]
222 let occ = rdrNameOcc rdr_name
223 ; when (isTcOcc occ && isSymOcc occ)
224 (do { op_ok <- doptM Opt_TypeOperators
225 ; checkM op_ok (addErr (opDeclErr rdr_name)) })
227 ; mb_gre <- lookupGreLocalRn rdr_name
229 Nothing -> returnM Nothing
230 Just gre -> returnM (Just $ gre_name gre) }
233 -----------------------------------------------
234 lookupInstDeclBndr :: Name -> Located RdrName -> RnM (Located Name)
235 -- This is called on the method name on the left-hand side of an
236 -- instance declaration binding. eg. instance Functor T where
238 -- ^^^^ called on this
239 -- Regardless of how many unqualified fmaps are in scope, we want
240 -- the one that comes from the Functor class.
242 -- Furthermore, note that we take no account of whether the
243 -- name is only in scope qualified. I.e. even if method op is
244 -- in scope as M.op, we still allow plain 'op' on the LHS of
246 lookupInstDeclBndr cls rdr = lookup_located_sub_bndr is_op doc rdr
248 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
249 is_op (GRE {gre_par = ParentIs n}) = n == cls
252 -----------------------------------------------
253 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
254 -- Used for record construction and pattern matching
255 -- When the -XDisambiguateRecordFields flag is on, take account of the
256 -- constructor name to disambiguate which field to use; it's just the
257 -- same as for instance decls
259 -- NB: Consider this:
260 -- module Foo where { data R = R { fld :: Int } }
261 -- module Odd where { import Foo; fld x = x { fld = 3 } }
262 -- Arguably this should work, because the reference to 'fld' is
263 -- unambiguous because there is only one field id 'fld' in scope.
264 -- But currently it's rejected.
265 lookupRecordBndr Nothing rdr_name
266 = lookupLocatedGlobalOccRn rdr_name
267 lookupRecordBndr (Just (L _ data_con)) rdr_name
268 = do { flag_on <- doptM Opt_DisambiguateRecordFields
270 then lookupLocatedGlobalOccRn rdr_name
272 fields <- lookupConstructorFields data_con
273 ; let is_field gre = gre_name gre `elem` fields
274 ; lookup_located_sub_bndr is_field doc rdr_name
277 doc = ptext (sLit "field of constructor") <+> quotes (ppr data_con)
280 lookupConstructorFields :: Name -> RnM [Name]
281 -- Look up the fields of a given constructor
282 -- * For constructors from this module, use the record field env,
283 -- which is itself gathered from the (as yet un-typechecked)
286 -- * For constructors from imported modules, use the *type* environment
287 -- since imported modles are already compiled, the info is conveniently
290 lookupConstructorFields con_name
291 = do { this_mod <- getModule
292 ; if nameIsLocalOrFrom this_mod con_name then
293 do { RecFields field_env _ <- getRecFieldEnv
294 ; return (lookupNameEnv field_env con_name `orElse` []) }
296 do { con <- tcLookupDataCon con_name
297 ; return (dataConFieldLabels con) } }
299 -----------------------------------------------
300 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
301 -> SDoc -> Located RdrName
302 -> RnM (Located Name)
303 lookup_located_sub_bndr is_good doc rdr_name
304 = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
306 lookup_sub_bndr :: (GlobalRdrElt -> Bool) -> SDoc -> RdrName -> RnM Name
307 lookup_sub_bndr is_good doc rdr_name
308 | isUnqual rdr_name -- Find all the things the rdr-name maps to
309 = do { -- and pick the one with the right parent name
310 ; env <- getGlobalRdrEnv
311 ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) of
312 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
313 -- The latter does pickGREs, but we want to allow 'x'
314 -- even if only 'M.x' is in scope
315 [gre] -> return (gre_name gre)
316 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
317 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
318 ; return (mkUnboundName rdr_name) }
319 gres -> do { addNameClashErrRn rdr_name gres
320 ; return (gre_name (head gres)) }
323 | otherwise -- Occurs in derived instances, where we just
324 -- refer directly to the right method with an Orig
325 -- And record fields can be Quals: C { F.f = x }
326 = lookupGlobalOccRn rdr_name
328 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
329 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
331 -- Looking up family names in type instances is a subtle affair. The family
332 -- may be imported, in which case we need to lookup the occurence of a global
333 -- name. Alternatively, the family may be in the same binding group (and in
334 -- fact in a declaration processed later), and we need to create a new top
337 -- So, also this is strictly speaking an occurence, we cannot raise an error
338 -- message yet for instances without a family declaration. This will happen
339 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
341 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
342 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
343 = do { mb_gre <- lookupGreRn_maybe rdr_name
345 Just gre -> returnM (gre_name gre)
346 Nothing -> newTopSrcBinder mod lrdr_name }
348 --------------------------------------------------
350 --------------------------------------------------
352 getLookupOccRn :: RnM (Name -> Maybe Name)
354 = getLocalRdrEnv `thenM` \ local_env ->
355 return (lookupLocalRdrOcc local_env . nameOccName)
357 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
358 lookupLocatedOccRn = wrapLocM lookupOccRn
360 -- lookupOccRn looks up an occurrence of a RdrName
361 lookupOccRn :: RdrName -> RnM Name
363 = getLocalRdrEnv `thenM` \ local_env ->
364 case lookupLocalRdrEnv local_env rdr_name of
365 Just name -> returnM name
366 Nothing -> lookupGlobalOccRn rdr_name
368 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
369 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
371 lookupGlobalOccRn :: RdrName -> RnM Name
372 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
373 -- environment. Adds an error message if the RdrName is not in scope.
374 -- Also has a special case for GHCi.
376 lookupGlobalOccRn rdr_name
377 = do { -- First look up the name in the normal environment.
378 mb_name <- lookupGlobalOccRn_maybe rdr_name
383 { -- We allow qualified names on the command line to refer to
384 -- *any* name exported by any module in scope, just as if there
385 -- was an "import qualified M" declaration for every module.
386 allow_qual <- doptM Opt_ImplicitImportQualified
388 -- This test is not expensive,
389 -- and only happens for failed lookups
390 ; if isQual rdr_name && allow_qual && mod == iNTERACTIVE
391 then lookupQualifiedName rdr_name
392 else unboundName rdr_name } } }
394 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
395 -- No filter function; does not report an error on failure
397 lookupGlobalOccRn_maybe rdr_name
398 | Just n <- isExact_maybe rdr_name -- This happens in derived code
401 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
402 = do { n <- lookupOrig rdr_mod rdr_occ; return (Just n) }
405 = do { mb_gre <- lookupGreRn_maybe rdr_name
407 Nothing -> return Nothing
408 Just gre -> return (Just (gre_name gre)) }
411 unboundName :: RdrName -> RnM Name
413 = do { addErr (unknownNameErr rdr_name)
414 ; env <- getGlobalRdrEnv;
415 ; traceRn (vcat [unknownNameErr rdr_name,
416 ptext (sLit "Global envt is:"),
417 nest 3 (pprGlobalRdrEnv env)])
418 ; returnM (mkUnboundName rdr_name) }
420 --------------------------------------------------
421 -- Lookup in the Global RdrEnv of the module
422 --------------------------------------------------
424 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
425 -- Just look up the RdrName in the GlobalRdrEnv
426 lookupGreRn_maybe rdr_name
427 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
429 lookupGreRn :: RdrName -> RnM GlobalRdrElt
430 -- If not found, add error message, and return a fake GRE
432 = do { mb_gre <- lookupGreRn_maybe rdr_name
434 Just gre -> return gre ;
436 { traceRn $ text "lookupGreRn"
437 ; name <- unboundName rdr_name
438 ; return (GRE { gre_name = name, gre_par = NoParent,
439 gre_prov = LocalDef }) }}}
441 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
442 -- Similar, but restricted to locally-defined things
443 lookupGreLocalRn rdr_name
444 = lookupGreRn_help rdr_name lookup_fn
446 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
448 lookupGreRn_help :: RdrName -- Only used in error message
449 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
450 -> RnM (Maybe GlobalRdrElt)
451 -- Checks for exactly one match; reports deprecations
452 -- Returns Nothing, without error, if too few
453 lookupGreRn_help rdr_name lookup
454 = do { env <- getGlobalRdrEnv
456 [] -> returnM Nothing
457 [gre] -> returnM (Just gre)
458 gres -> do { addNameClashErrRn rdr_name gres
459 ; returnM (Just (head gres)) } }
461 ------------------------------
463 ------------------------------
465 -- A qualified name on the command line can refer to any module at all: we
466 -- try to load the interface if we don't already have it.
467 lookupQualifiedName :: RdrName -> RnM Name
468 lookupQualifiedName rdr_name
469 | Just (mod,occ) <- isQual_maybe rdr_name
470 -- Note: we want to behave as we would for a source file import here,
471 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
472 = loadSrcInterface doc mod False Nothing `thenM` \ iface ->
475 (mod,avails) <- mi_exports iface,
477 name <- availNames avail,
479 ((mod,occ):ns) -> ASSERT (null ns)
481 _ -> unboundName rdr_name
484 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
486 doc = ptext (sLit "Need to find") <+> ppr rdr_name
489 lookupSigOccRn is used for type signatures and pragmas
495 It's clear that the 'f' in the signature must refer to A.f
496 The Haskell98 report does not stipulate this, but it will!
497 So we must treat the 'f' in the signature in the same way
498 as the binding occurrence of 'f', using lookupBndrRn
500 However, consider this case:
504 We don't want to say 'f' is out of scope; instead, we want to
505 return the imported 'f', so that later on the reanamer will
506 correctly report "misplaced type sig".
509 lookupSigOccRn :: Maybe NameSet -- Just ns => source file; these are the binders
511 -- Nothing => hs-boot file; signatures without
512 -- binders are expected
514 -> Located RdrName -> RnM (Located Name)
515 lookupSigOccRn mb_bound_names sig
516 = wrapLocM $ \ rdr_name ->
517 do { mb_name <- lookupBindGroupOcc mb_bound_names (hsSigDoc sig) rdr_name
519 Left err -> do { addErr err; return (mkUnboundName rdr_name) }
520 Right name -> return name }
522 lookupBindGroupOcc :: Maybe NameSet -- Just ns => source file; these are the binders
524 -- Nothing => hs-boot file; signatures without
525 -- binders are expected
527 -> RdrName -> RnM (Either Message Name)
528 -- Looks up the RdrName, expecting it to resolve to one of the
529 -- bound names passed in. If not, return an appropriate error message
530 lookupBindGroupOcc mb_bound_names what rdr_name
531 = do { local_env <- getLocalRdrEnv
532 ; case lookupLocalRdrEnv local_env rdr_name of
533 Just n -> check_local_name n
534 Nothing -> do -- Not defined in a nested scope
536 { env <- getGlobalRdrEnv
537 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
538 ; case (filter isLocalGRE gres) of
539 (gre:_) -> check_local_name (gre_name gre)
540 -- If there is more than one local GRE for the
541 -- same OccName, that will be reported separately
542 [] | null gres -> bale_out_with empty
543 | otherwise -> bale_out_with import_msg
546 check_local_name name -- The name is in scope, and not imported
547 = case mb_bound_names of
548 Just bound_names | not (name `elemNameSet` bound_names)
549 -> bale_out_with local_msg
550 _other -> return (Right name)
553 = return (Left (sep [ ptext (sLit "The") <+> what
554 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
555 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
558 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
559 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
561 import_msg = parens $ ptext (sLit "You cannot give a") <+> what
562 <+> ptext (sLit "for an imported value")
565 lookupLocalDataTcNames :: NameSet -> SDoc -> RdrName -> RnM [Name]
566 -- GHC extension: look up both the tycon and data con
567 -- for con-like things
568 -- Complain if neither is in scope
569 lookupLocalDataTcNames bound_names what rdr_name
570 | Just n <- isExact_maybe rdr_name
571 -- Special case for (:), which doesn't get into the GlobalRdrEnv
572 = return [n] -- For this we don't need to try the tycon too
574 = do { mb_gres <- mapM (lookupBindGroupOcc (Just bound_names) what)
575 (dataTcOccs rdr_name)
576 ; let (errs, names) = splitEithers mb_gres
577 ; when (null names) (addErr (head errs)) -- Bleat about one only
580 dataTcOccs :: RdrName -> [RdrName]
581 -- If the input is a data constructor, return both it and a type
582 -- constructor. This is useful when we aren't sure which we are
585 | Just n <- isExact_maybe rdr_name -- Ghastly special case
586 , n `hasKey` consDataConKey = [rdr_name] -- see note below
587 | isDataOcc occ = [rdr_name, rdr_name_tc]
588 | otherwise = [rdr_name]
590 occ = rdrNameOcc rdr_name
591 rdr_name_tc = setRdrNameSpace rdr_name tcName
593 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
594 -- and setRdrNameSpace generates an Orig, which is fine
595 -- But it's not fine for (:), because there *is* no corresponding type
596 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
597 -- appear to be in scope (because Orig's simply allocate a new name-cache
598 -- entry) and then we get an error when we use dataTcOccs in
599 -- TcRnDriver.tcRnGetInfo. Large sigh.
603 %*********************************************************
607 %*********************************************************
610 --------------------------------
611 type FastStringEnv a = UniqFM a -- Keyed by FastString
614 emptyFsEnv :: FastStringEnv a
615 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
616 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
618 emptyFsEnv = emptyUFM
619 lookupFsEnv = lookupUFM
620 extendFsEnv = addToUFM
622 --------------------------------
623 type MiniFixityEnv = FastStringEnv (Located Fixity)
624 -- Mini fixity env for the names we're about
625 -- to bind, in a single binding group
627 -- It is keyed by the *FastString*, not the *OccName*, because
628 -- the single fixity decl infix 3 T
629 -- affects both the data constructor T and the type constrctor T
631 -- We keep the location so that if we find
632 -- a duplicate, we can report it sensibly
634 --------------------------------
635 -- Used for nested fixity decls to bind names along with their fixities.
636 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
637 -- Also check for unused binders
638 bindLocalNamesFV_WithFixities :: [Name]
640 -> RnM (a, FreeVars) -> RnM (a, FreeVars)
641 bindLocalNamesFV_WithFixities names fixities thing_inside
642 = bindLocalNamesFV names $
643 extendFixityEnv boundFixities $
646 -- find the names that have fixity decls
647 boundFixities = foldr
649 -- check whether this name has a fixity decl
650 case lookupFsEnv fixities (occNameFS (nameOccName name)) of
651 Just (L _ fix) -> (name, FixItem (nameOccName name) fix) : acc
652 Nothing -> acc) [] names
653 -- bind the names; extend the fixity env; do the thing inside
656 --------------------------------
657 lookupFixity is a bit strange.
659 * Nested local fixity decls are put in the local fixity env, which we
660 find with getFixtyEnv
662 * Imported fixities are found in the HIT or PIT
664 * Top-level fixity decls in this module may be for Names that are
665 either Global (constructors, class operations)
666 or Local/Exported (everything else)
667 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
668 We put them all in the local fixity environment
671 lookupFixityRn :: Name -> RnM Fixity
673 = getModule `thenM` \ this_mod ->
674 if nameIsLocalOrFrom this_mod name
675 then do -- It's defined in this module
676 local_fix_env <- getFixityEnv
677 traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
678 vcat [ppr name, ppr local_fix_env])
679 return $ lookupFixity local_fix_env name
680 else -- It's imported
681 -- For imported names, we have to get their fixities by doing a
682 -- loadInterfaceForName, and consulting the Ifaces that comes back
683 -- from that, because the interface file for the Name might not
684 -- have been loaded yet. Why not? Suppose you import module A,
685 -- which exports a function 'f', thus;
686 -- module CurrentModule where
688 -- module A( f ) where
690 -- Then B isn't loaded right away (after all, it's possible that
691 -- nothing from B will be used). When we come across a use of
692 -- 'f', we need to know its fixity, and it's then, and only
693 -- then, that we load B.hi. That is what's happening here.
695 -- loadInterfaceForName will find B.hi even if B is a hidden module,
696 -- and that's what we want.
697 loadInterfaceForName doc name `thenM` \ iface -> do {
698 traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
699 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
700 returnM (mi_fix_fn iface (nameOccName name))
703 doc = ptext (sLit "Checking fixity for") <+> ppr name
706 lookupTyFixityRn :: Located Name -> RnM Fixity
707 lookupTyFixityRn (L _ n) = lookupFixityRn n
711 %************************************************************************
714 Dealing with rebindable syntax is driven by the
715 Opt_NoImplicitPrelude dynamic flag.
717 In "deriving" code we don't want to use rebindable syntax
718 so we switch off the flag locally
721 %************************************************************************
723 Haskell 98 says that when you say "3" you get the "fromInteger" from the
724 Standard Prelude, regardless of what is in scope. However, to experiment
725 with having a language that is less coupled to the standard prelude, we're
726 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
727 happens to be in scope. Then you can
729 import MyPrelude as Prelude
730 to get the desired effect.
732 At the moment this just happens for
733 * fromInteger, fromRational on literals (in expressions and patterns)
734 * negate (in expressions)
735 * minus (arising from n+k patterns)
738 We store the relevant Name in the HsSyn tree, in
739 * HsIntegral/HsFractional/HsIsString
743 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
744 fromRationalName etc), but the renamer changes this to the appropriate user
745 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
747 We treat the orignal (standard) names as free-vars too, because the type checker
748 checks the type of the user thing against the type of the standard thing.
751 lookupSyntaxName :: Name -- The standard name
752 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
753 lookupSyntaxName std_name
754 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
755 if implicit_prelude then normal_case
757 -- Get the similarly named thing from the local environment
758 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
759 returnM (HsVar usr_name, unitFV usr_name)
761 normal_case = returnM (HsVar std_name, emptyFVs)
763 lookupSyntaxTable :: [Name] -- Standard names
764 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
765 lookupSyntaxTable std_names
766 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
767 if implicit_prelude then normal_case
769 -- Get the similarly named thing from the local environment
770 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
772 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
774 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
778 %*********************************************************
782 %*********************************************************
785 newLocalsRn :: [Located RdrName] -> RnM [Name]
786 newLocalsRn rdr_names_w_loc
787 = newUniqueSupply `thenM` \ us ->
788 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
790 mk (L loc rdr_name) uniq
791 | Just name <- isExact_maybe rdr_name = name
792 -- This happens in code generated by Template Haskell
793 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
794 -- We only bind unqualified names here
795 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
796 mkInternalName uniq (rdrNameOcc rdr_name) loc
798 ---------------------
799 checkDupAndShadowedRdrNames :: SDoc -> [Located RdrName] -> RnM ()
800 checkDupAndShadowedRdrNames doc loc_rdr_names
801 = do { checkDupRdrNames doc loc_rdr_names
803 ; checkShadowedNames doc envs
804 [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names] }
806 ---------------------
807 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
811 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
812 = checkDupAndShadowedRdrNames doc_str rdr_names_w_loc `thenM_`
814 -- Make fresh Names and extend the environment
815 newLocalsRn rdr_names_w_loc `thenM` \names ->
816 bindLocalNames names (enclosed_scope names)
818 bindLocalNames :: [Name] -> RnM a -> RnM a
819 bindLocalNames names enclosed_scope
820 = getLocalRdrEnv `thenM` \ name_env ->
821 setLocalRdrEnv (extendLocalRdrEnv name_env names)
824 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
825 bindLocalNamesFV names enclosed_scope
826 = do { (result, fvs) <- bindLocalNames names enclosed_scope
827 ; returnM (result, delListFromNameSet fvs names) }
830 -------------------------------------
831 -- binLocalsFVRn is the same as bindLocalsRn
832 -- except that it deals with free vars
833 bindLocatedLocalsFV :: SDoc -> [Located RdrName]
834 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
835 bindLocatedLocalsFV doc rdr_names enclosed_scope
836 = bindLocatedLocalsRn doc rdr_names $ \ names ->
837 enclosed_scope names `thenM` \ (thing, fvs) ->
838 returnM (thing, delListFromNameSet fvs names)
840 -------------------------------------
841 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
842 -> ([LHsTyVarBndr Name] -> RnM a)
844 -- Haskell-98 binding of type variables; e.g. within a data type decl
845 bindTyVarsRn doc_str tyvar_names enclosed_scope
846 = bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
847 do { kind_sigs_ok <- doptM Opt_KindSignatures
848 ; checkM (null kinded_tyvars || kind_sigs_ok)
849 (mapM_ (addErr . kindSigErr) kinded_tyvars)
850 ; enclosed_scope (zipWith replace tyvar_names names) }
852 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
853 located_tyvars = hsLTyVarLocNames tyvar_names
854 kinded_tyvars = [n | L _ (KindedTyVar n _) <- tyvar_names]
856 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
857 -- Find the type variables in the pattern type
858 -- signatures that must be brought into scope
859 bindPatSigTyVars tys thing_inside
860 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
861 ; if not scoped_tyvars then
864 do { name_env <- getLocalRdrEnv
865 ; let locd_tvs = [ tv | ty <- tys
866 , tv <- extractHsTyRdrTyVars ty
867 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
868 nubbed_tvs = nubBy eqLocated locd_tvs
869 -- The 'nub' is important. For example:
870 -- f (x :: t) (y :: t) = ....
871 -- We don't want to complain about binding t twice!
873 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
875 doc_sig = text "In a pattern type-signature"
877 bindPatSigTyVarsFV :: [LHsType RdrName]
880 bindPatSigTyVarsFV tys thing_inside
881 = bindPatSigTyVars tys $ \ tvs ->
882 thing_inside `thenM` \ (result,fvs) ->
883 returnM (result, fvs `delListFromNameSet` tvs)
885 bindSigTyVarsFV :: [Name]
888 bindSigTyVarsFV tvs thing_inside
889 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
890 ; if not scoped_tyvars then
893 bindLocalNamesFV tvs thing_inside }
895 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
896 -- This function is used only in rnSourceDecl on InstDecl
897 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
899 -------------------------------------
900 checkDupRdrNames :: SDoc
903 checkDupRdrNames doc_str rdr_names_w_loc
904 = -- Check for duplicated names in a binding group
905 mappM_ (dupNamesErr getLoc doc_str) dups
907 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
909 checkDupNames :: SDoc
912 checkDupNames doc_str names
913 = -- Check for duplicated names in a binding group
914 mappM_ (dupNamesErr nameSrcSpan doc_str) dups
916 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
918 -------------------------------------
919 checkShadowedNames :: SDoc -> (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
920 checkShadowedNames doc_str (global_env,local_env) loc_rdr_names
921 = ifOptM Opt_WarnNameShadowing $
922 do { traceRn (text "shadow" <+> ppr loc_rdr_names)
923 ; mappM_ check_shadow loc_rdr_names }
925 check_shadow (loc, occ)
926 | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
928 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
929 | otherwise = do { gres' <- filterM is_shadowed_gre gres
930 ; complain (map pprNameProvenance gres') }
932 complain [] = return ()
933 complain pp_locs = addWarnAt loc (shadowedNameWarn doc_str occ pp_locs)
934 mb_local = lookupLocalRdrOcc local_env occ
935 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
936 -- Make an Unqualified RdrName and look that up, so that
937 -- we don't find any GREs that are in scope qualified-only
939 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
940 -- Returns False for record selectors that are shadowed, when
941 -- punning or wild-cards are on (cf Trac #2723)
942 is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
943 = do { dflags <- getDOpts
944 ; if (dopt Opt_RecordPuns dflags || dopt Opt_RecordWildCards dflags)
945 then do { is_fld <- is_rec_fld gre; return (not is_fld) }
947 is_shadowed_gre _other = return True
949 is_rec_fld gre -- Return True for record selector ids
950 | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
951 ; return (gre_name gre `elemNameSet` fld_set) }
952 | otherwise = do { sel_id <- tcLookupField (gre_name gre)
953 ; return (isRecordSelector sel_id) }
957 %************************************************************************
959 \subsection{Free variable manipulation}
961 %************************************************************************
965 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
966 mapFvRn f xs = do stuff <- mappM f xs
968 (ys, fvs_s) -> returnM (ys, plusFVs fvs_s)
970 -- because some of the rename functions are CPSed:
971 -- maps the function across the list from left to right;
972 -- collects all the free vars into one set
973 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
974 -> [a] -> ([b] -> RnM c) -> RnM c
976 mapFvRnCPS _ [] cont = cont []
977 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
978 mapFvRnCPS f xs $ \ xs' ->
983 %************************************************************************
985 \subsection{Envt utility functions}
987 %************************************************************************
990 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
991 warnUnusedModules mods
992 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
994 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
995 mk_warn m = vcat [ptext (sLit "Module") <+> quotes (ppr m)
996 <+> text "is imported, but nothing from it is used,",
997 nest 2 (ptext (sLit "except perhaps instances visible in")
999 ptext (sLit "To suppress this warning, use:")
1000 <+> ptext (sLit "import") <+> ppr m <> parens empty ]
1003 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1004 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
1005 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
1007 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1008 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
1009 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
1011 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
1012 check_unused flag bound_names used_names
1013 = ifOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1015 -------------------------
1017 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1019 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1021 warnUnusedLocals :: [Name] -> RnM ()
1022 warnUnusedLocals names
1023 = warnUnusedBinds [(n,LocalDef) | n<-names]
1025 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
1026 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
1027 where reportable (name,_)
1028 | isWiredInName name = False -- Don't report unused wired-in names
1029 -- Otherwise we get a zillion warnings
1031 | otherwise = not (startsWithUnderscore (nameOccName name))
1033 -------------------------
1035 warnUnusedName :: (Name, Provenance) -> RnM ()
1036 warnUnusedName (name, LocalDef)
1037 = addUnusedWarning name (nameSrcSpan name)
1038 (ptext (sLit "Defined but not used"))
1040 warnUnusedName (name, Imported is)
1043 warn spec = addUnusedWarning name span msg
1045 span = importSpecLoc spec
1046 pp_mod = quotes (ppr (importSpecModule spec))
1047 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1049 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1050 addUnusedWarning name span msg
1053 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1054 <+> quotes (ppr name)]
1058 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1059 addNameClashErrRn rdr_name names
1060 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1061 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1064 msg1 = ptext (sLit "either") <+> mk_ref np1
1065 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
1066 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1068 shadowedNameWarn :: SDoc -> OccName -> [SDoc] -> SDoc
1069 shadowedNameWarn doc occ shadowed_locs
1070 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1071 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1072 nest 2 (vcat shadowed_locs)]
1075 unknownNameErr :: RdrName -> SDoc
1076 unknownNameErr rdr_name
1077 = vcat [ hang (ptext (sLit "Not in scope:"))
1078 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1079 <+> quotes (ppr rdr_name))
1082 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1085 perhapsForallMsg :: SDoc
1087 = vcat [ ptext (sLit "Perhaps you intended to use -XRankNTypes or similar flag")
1088 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1090 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1091 unknownSubordinateErr doc op -- Doc is "method of class" or
1092 -- "field of constructor"
1093 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1095 badOrigBinding :: RdrName -> SDoc
1097 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1098 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1100 dupNamesErr :: Outputable n => (n -> SrcSpan) -> SDoc -> [n] -> RnM ()
1101 dupNamesErr get_loc descriptor names
1102 = addErrAt big_loc $
1103 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1104 locations, descriptor]
1106 locs = map get_loc names
1107 big_loc = foldr1 combineSrcSpans locs
1108 one_line = isOneLineSpan big_loc
1109 locations | one_line = empty
1110 | otherwise = ptext (sLit "Bound at:") <+>
1111 vcat (map ppr (sortLe (<=) locs))
1113 kindSigErr :: Outputable a => a -> SDoc
1115 = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
1116 2 (ptext (sLit "Perhaps you intended to use -XKindSignatures"))
1119 badQualBndrErr :: RdrName -> SDoc
1120 badQualBndrErr rdr_name
1121 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
1123 opDeclErr :: RdrName -> SDoc
1125 = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
1126 2 (ptext (sLit "Use -XTypeOperators to declare operators in type and declarations"))