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,
18 getLookupOccRn, addUsedRdrNames,
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 )
61 import ErrUtils ( Message )
66 import ListSetOps ( removeDups )
71 import qualified Data.Set as Set
76 thenM :: Monad a => a b -> (b -> a c) -> a c
79 thenM_ :: Monad a => a b -> a c -> a c
82 returnM :: Monad m => a -> m a
85 mappM :: (Monad m) => (a -> m b) -> [a] -> m [b]
88 mappM_ :: (Monad m) => (a -> m b) -> [a] -> m ()
91 checkM :: Monad m => Bool -> m () -> m ()
95 %*********************************************************
99 %*********************************************************
102 newTopSrcBinder :: Module -> Located RdrName -> RnM Name
103 newTopSrcBinder this_mod (L loc rdr_name)
104 | Just name <- isExact_maybe rdr_name
105 = -- This is here to catch
106 -- (a) Exact-name binders created by Template Haskell
107 -- (b) The PrelBase defn of (say) [] and similar, for which
108 -- the parser reads the special syntax and returns an Exact RdrName
109 -- We are at a binding site for the name, so check first that it
110 -- the current module is the correct one; otherwise GHC can get
111 -- very confused indeed. This test rejects code like
112 -- data T = (,) Int Int
113 -- unless we are in GHC.Tup
114 ASSERT2( isExternalName name, ppr name )
115 do { checkM (this_mod == nameModule name)
116 (addErrAt loc (badOrigBinding rdr_name))
120 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
121 = do { checkM (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
122 (addErrAt loc (badOrigBinding rdr_name))
123 -- When reading External Core we get Orig names as binders,
124 -- but they should agree with the module gotten from the monad
126 -- We can get built-in syntax showing up here too, sadly. If you type
128 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
129 -- uses setRdrNameSpace to make it into a data constructors. At that point
130 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
131 -- Hence the badOrigBinding error message.
133 -- Except for the ":Main.main = ..." definition inserted into
134 -- the Main module; ugh!
136 -- Because of this latter case, we call newGlobalBinder with a module from
137 -- the RdrName, not from the environment. In principle, it'd be fine to
138 -- have an arbitrary mixture of external core definitions in a single module,
139 -- (apart from module-initialisation issues, perhaps).
140 ; newGlobalBinder rdr_mod rdr_occ loc }
141 --TODO, should pass the whole span
144 = do { checkM (not (isQual rdr_name))
145 (addErrAt loc (badQualBndrErr rdr_name))
146 -- Binders should not be qualified; if they are, and with a different
147 -- module name, we we get a confusing "M.T is not in scope" error later
150 ; if isBrackStage stage then
151 -- We are inside a TH bracket, so make an *Internal* name
152 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
153 do { uniq <- newUnique
154 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
157 newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
160 %*********************************************************
162 Source code occurrences
164 %*********************************************************
166 Looking up a name in the RnEnv.
168 Note [Type and class operator definitions]
169 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
170 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
172 class a :*: b where ...
173 data (:*:) a b = ....
174 class (:*:) a b where ...
175 The latter two mean that we are not just looking for a
176 *syntactically-infix* declaration, but one that uses an operator
177 OccName. We use OccName.isSymOcc to detect that case, which isn't
178 terribly efficient, but there seems to be no better way.
181 lookupTopBndrRn :: RdrName -> RnM Name
182 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
185 Nothing -> do traceRn $ text "lookupTopBndrRn"
188 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
189 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
191 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
192 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
193 -- and there may be several imported 'f's too, which must not confuse us.
194 -- For example, this is OK:
196 -- infix 9 f -- The 'f' here does not need to be qualified
197 -- f x = x -- Nor here, of course
198 -- So we have to filter out the non-local ones.
200 -- A separate function (importsFromLocalDecls) reports duplicate top level
201 -- decls, so here it's safe just to choose an arbitrary one.
203 -- There should never be a qualified name in a binding position in Haskell,
204 -- but there can be if we have read in an external-Core file.
205 -- The Haskell parser checks for the illegal qualified name in Haskell
206 -- source files, so we don't need to do so here.
208 lookupTopBndrRn_maybe rdr_name
209 | Just name <- isExact_maybe rdr_name
210 = returnM (Just name)
212 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
213 -- This deals with the case of derived bindings, where
214 -- we don't bother to call newTopSrcBinder first
215 -- We assume there is no "parent" name
216 = do { loc <- getSrcSpanM
217 ; n <- newGlobalBinder rdr_mod rdr_occ loc
221 = do { -- Check for operators in type or class declarations
222 -- See Note [Type and class operator definitions]
223 let occ = rdrNameOcc rdr_name
224 ; when (isTcOcc occ && isSymOcc occ)
225 (do { op_ok <- doptM Opt_TypeOperators
226 ; checkM op_ok (addErr (opDeclErr rdr_name)) })
228 ; mb_gre <- lookupGreLocalRn rdr_name
230 Nothing -> returnM Nothing
231 Just gre -> returnM (Just $ gre_name gre) }
234 -----------------------------------------------
235 lookupInstDeclBndr :: Name -> Located RdrName -> RnM (Located Name)
236 -- This is called on the method name on the left-hand side of an
237 -- instance declaration binding. eg. instance Functor T where
239 -- ^^^^ called on this
240 -- Regardless of how many unqualified fmaps are in scope, we want
241 -- the one that comes from the Functor class.
243 -- Furthermore, note that we take no account of whether the
244 -- name is only in scope qualified. I.e. even if method op is
245 -- in scope as M.op, we still allow plain 'op' on the LHS of
247 lookupInstDeclBndr cls rdr = lookup_located_sub_bndr is_op doc rdr
249 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
250 is_op (GRE {gre_par = ParentIs n}) = n == cls
253 -----------------------------------------------
254 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
255 -- Used for record construction and pattern matching
256 -- When the -XDisambiguateRecordFields flag is on, take account of the
257 -- constructor name to disambiguate which field to use; it's just the
258 -- same as for instance decls
260 -- NB: Consider this:
261 -- module Foo where { data R = R { fld :: Int } }
262 -- module Odd where { import Foo; fld x = x { fld = 3 } }
263 -- Arguably this should work, because the reference to 'fld' is
264 -- unambiguous because there is only one field id 'fld' in scope.
265 -- But currently it's rejected.
266 lookupRecordBndr Nothing rdr_name
267 = lookupLocatedGlobalOccRn rdr_name
268 lookupRecordBndr (Just (L _ data_con)) rdr_name
269 = do { flag_on <- doptM Opt_DisambiguateRecordFields
271 then lookupLocatedGlobalOccRn rdr_name
273 fields <- lookupConstructorFields data_con
274 ; let is_field gre = gre_name gre `elem` fields
275 ; lookup_located_sub_bndr is_field doc rdr_name
278 doc = ptext (sLit "field of constructor") <+> quotes (ppr data_con)
281 lookupConstructorFields :: Name -> RnM [Name]
282 -- Look up the fields of a given constructor
283 -- * For constructors from this module, use the record field env,
284 -- which is itself gathered from the (as yet un-typechecked)
287 -- * For constructors from imported modules, use the *type* environment
288 -- since imported modles are already compiled, the info is conveniently
291 lookupConstructorFields con_name
292 = do { this_mod <- getModule
293 ; if nameIsLocalOrFrom this_mod con_name then
294 do { RecFields field_env _ <- getRecFieldEnv
295 ; return (lookupNameEnv field_env con_name `orElse` []) }
297 do { con <- tcLookupDataCon con_name
298 ; return (dataConFieldLabels con) } }
300 -----------------------------------------------
301 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
302 -> SDoc -> Located RdrName
303 -> RnM (Located Name)
304 lookup_located_sub_bndr is_good doc rdr_name
305 = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
307 lookup_sub_bndr :: (GlobalRdrElt -> Bool) -> SDoc -> RdrName -> RnM Name
308 lookup_sub_bndr is_good doc rdr_name
309 | isUnqual rdr_name -- Find all the things the rdr-name maps to
310 = do { -- and pick the one with the right parent name
311 ; addUsedRdrName rdr_name
312 ; env <- getGlobalRdrEnv
313 ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) of
314 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
315 -- The latter does pickGREs, but we want to allow 'x'
316 -- even if only 'M.x' is in scope
317 [gre] -> return (gre_name gre)
318 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
319 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
320 ; return (mkUnboundName rdr_name) }
321 gres -> do { addNameClashErrRn rdr_name gres
322 ; return (gre_name (head gres)) }
325 | otherwise -- Occurs in derived instances, where we just
326 -- refer directly to the right method with an Orig
327 -- And record fields can be Quals: C { F.f = x }
328 = lookupGlobalOccRn rdr_name
330 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
331 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
333 -- If the family is declared locally, it will not yet be in the main
334 -- environment; hence, we pass in an extra one here, which we check first.
335 -- See "Note [Looking up family names in family instances]" in 'RnNames'.
337 lookupFamInstDeclBndr :: GlobalRdrEnv -> Located RdrName -> RnM Name
338 lookupFamInstDeclBndr tyclGroupEnv (L loc rdr_name)
340 case lookupGRE_RdrName rdr_name tyclGroupEnv of
341 (gre:_) -> return $ gre_name gre
342 -- if there is more than one, an error will be raised elsewhere
343 [] -> lookupOccRn rdr_name
346 --------------------------------------------------
348 --------------------------------------------------
350 getLookupOccRn :: RnM (Name -> Maybe Name)
352 = getLocalRdrEnv `thenM` \ local_env ->
353 return (lookupLocalRdrOcc local_env . nameOccName)
355 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
356 lookupLocatedOccRn = wrapLocM lookupOccRn
358 -- lookupOccRn looks up an occurrence of a RdrName
359 lookupOccRn :: RdrName -> RnM Name
361 = getLocalRdrEnv `thenM` \ local_env ->
362 case lookupLocalRdrEnv local_env rdr_name of
363 Just name -> returnM name
364 Nothing -> lookupGlobalOccRn rdr_name
366 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
367 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
369 lookupGlobalOccRn :: RdrName -> RnM Name
370 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
371 -- environment. Adds an error message if the RdrName is not in scope.
372 -- Also has a special case for GHCi.
374 lookupGlobalOccRn rdr_name
375 = do { -- First look up the name in the normal environment.
376 mb_name <- lookupGlobalOccRn_maybe rdr_name
381 { -- We allow qualified names on the command line to refer to
382 -- *any* name exported by any module in scope, just as if there
383 -- was an "import qualified M" declaration for every module.
384 allow_qual <- doptM Opt_ImplicitImportQualified
386 -- This test is not expensive,
387 -- and only happens for failed lookups
388 ; if isQual rdr_name && allow_qual && mod == iNTERACTIVE
389 then lookupQualifiedName rdr_name
390 else unboundName rdr_name } } }
392 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
393 -- No filter function; does not report an error on failure
395 lookupGlobalOccRn_maybe rdr_name
396 | Just n <- isExact_maybe rdr_name -- This happens in derived code
399 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
400 = do { n <- lookupOrig rdr_mod rdr_occ; return (Just n) }
403 = do { mb_gre <- lookupGreRn_maybe rdr_name
405 Nothing -> return Nothing
406 Just gre -> return (Just (gre_name gre)) }
409 unboundName :: RdrName -> RnM Name
411 = do { addErr (unknownNameErr rdr_name)
412 ; env <- getGlobalRdrEnv;
413 ; traceRn (vcat [unknownNameErr rdr_name,
414 ptext (sLit "Global envt is:"),
415 nest 3 (pprGlobalRdrEnv env)])
416 ; returnM (mkUnboundName rdr_name) }
418 --------------------------------------------------
419 -- Lookup in the Global RdrEnv of the module
420 --------------------------------------------------
422 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
423 -- Just look up the RdrName in the GlobalRdrEnv
424 lookupGreRn_maybe rdr_name
425 = do { mGre <- lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
429 LocalDef -> return ()
430 Imported _ -> addUsedRdrName rdr_name
435 addUsedRdrName :: RdrName -> RnM ()
437 = do { env <- getGblEnv
438 ; updMutVar (tcg_used_rdrnames env)
439 (\s -> Set.insert rdr s) }
441 addUsedRdrNames :: [RdrName] -> RnM ()
443 = do { env <- getGblEnv
444 ; updMutVar (tcg_used_rdrnames env)
445 (\s -> foldr Set.insert s rdrs) }
447 lookupGreRn :: RdrName -> RnM GlobalRdrElt
448 -- If not found, add error message, and return a fake GRE
450 = do { mb_gre <- lookupGreRn_maybe rdr_name
452 Just gre -> return gre ;
454 { traceRn $ text "lookupGreRn"
455 ; name <- unboundName rdr_name
456 ; return (GRE { gre_name = name, gre_par = NoParent,
457 gre_prov = LocalDef }) }}}
459 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
460 -- Similar, but restricted to locally-defined things
461 lookupGreLocalRn rdr_name
462 = lookupGreRn_help rdr_name lookup_fn
464 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
466 lookupGreRn_help :: RdrName -- Only used in error message
467 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
468 -> RnM (Maybe GlobalRdrElt)
469 -- Checks for exactly one match; reports deprecations
470 -- Returns Nothing, without error, if too few
471 lookupGreRn_help rdr_name lookup
472 = do { env <- getGlobalRdrEnv
474 [] -> returnM Nothing
475 [gre] -> returnM (Just gre)
476 gres -> do { addNameClashErrRn rdr_name gres
477 ; returnM (Just (head gres)) } }
479 ------------------------------
481 ------------------------------
483 -- A qualified name on the command line can refer to any module at all: we
484 -- try to load the interface if we don't already have it.
485 lookupQualifiedName :: RdrName -> RnM Name
486 lookupQualifiedName rdr_name
487 | Just (mod,occ) <- isQual_maybe rdr_name
488 -- Note: we want to behave as we would for a source file import here,
489 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
490 = loadSrcInterface doc mod False Nothing `thenM` \ iface ->
493 (mod,avails) <- mi_exports iface,
495 name <- availNames avail,
497 ((mod,occ):ns) -> ASSERT (null ns)
499 _ -> unboundName rdr_name
502 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
504 doc = ptext (sLit "Need to find") <+> ppr rdr_name
507 lookupSigOccRn is used for type signatures and pragmas
513 It's clear that the 'f' in the signature must refer to A.f
514 The Haskell98 report does not stipulate this, but it will!
515 So we must treat the 'f' in the signature in the same way
516 as the binding occurrence of 'f', using lookupBndrRn
518 However, consider this case:
522 We don't want to say 'f' is out of scope; instead, we want to
523 return the imported 'f', so that later on the reanamer will
524 correctly report "misplaced type sig".
527 lookupSigOccRn :: Maybe NameSet -- Just ns => source file; these are the binders
529 -- Nothing => hs-boot file; signatures without
530 -- binders are expected
532 -> Located RdrName -> RnM (Located Name)
533 lookupSigOccRn mb_bound_names sig
534 = wrapLocM $ \ rdr_name ->
535 do { mb_name <- lookupBindGroupOcc mb_bound_names (hsSigDoc sig) rdr_name
537 Left err -> do { addErr err; return (mkUnboundName rdr_name) }
538 Right name -> return name }
540 lookupBindGroupOcc :: Maybe NameSet -- Just ns => source file; these are the binders
542 -- Nothing => hs-boot file; signatures without
543 -- binders are expected
545 -> RdrName -> RnM (Either Message Name)
546 -- Looks up the RdrName, expecting it to resolve to one of the
547 -- bound names passed in. If not, return an appropriate error message
548 lookupBindGroupOcc mb_bound_names what rdr_name
549 = do { local_env <- getLocalRdrEnv
550 ; case lookupLocalRdrEnv local_env rdr_name of
551 Just n -> check_local_name n
552 Nothing -> do -- Not defined in a nested scope
554 { env <- getGlobalRdrEnv
555 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
556 ; case (filter isLocalGRE gres) of
557 (gre:_) -> check_local_name (gre_name gre)
558 -- If there is more than one local GRE for the
559 -- same OccName, that will be reported separately
560 [] | null gres -> bale_out_with empty
561 | otherwise -> bale_out_with import_msg
564 check_local_name name -- The name is in scope, and not imported
565 = case mb_bound_names of
566 Just bound_names | not (name `elemNameSet` bound_names)
567 -> bale_out_with local_msg
568 _other -> return (Right name)
571 = return (Left (sep [ ptext (sLit "The") <+> what
572 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
573 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
576 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
577 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
579 import_msg = parens $ ptext (sLit "You cannot give a") <+> what
580 <+> ptext (sLit "for an imported value")
583 lookupLocalDataTcNames :: NameSet -> SDoc -> RdrName -> RnM [Name]
584 -- GHC extension: look up both the tycon and data con
585 -- for con-like things
586 -- Complain if neither is in scope
587 lookupLocalDataTcNames bound_names what rdr_name
588 | Just n <- isExact_maybe rdr_name
589 -- Special case for (:), which doesn't get into the GlobalRdrEnv
590 = return [n] -- For this we don't need to try the tycon too
592 = do { mb_gres <- mapM (lookupBindGroupOcc (Just bound_names) what)
593 (dataTcOccs rdr_name)
594 ; let (errs, names) = splitEithers mb_gres
595 ; when (null names) (addErr (head errs)) -- Bleat about one only
598 dataTcOccs :: RdrName -> [RdrName]
599 -- If the input is a data constructor, return both it and a type
600 -- constructor. This is useful when we aren't sure which we are
603 | Just n <- isExact_maybe rdr_name -- Ghastly special case
604 , n `hasKey` consDataConKey = [rdr_name] -- see note below
605 | isDataOcc occ = [rdr_name, rdr_name_tc]
606 | otherwise = [rdr_name]
608 occ = rdrNameOcc rdr_name
609 rdr_name_tc = setRdrNameSpace rdr_name tcName
611 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
612 -- and setRdrNameSpace generates an Orig, which is fine
613 -- But it's not fine for (:), because there *is* no corresponding type
614 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
615 -- appear to be in scope (because Orig's simply allocate a new name-cache
616 -- entry) and then we get an error when we use dataTcOccs in
617 -- TcRnDriver.tcRnGetInfo. Large sigh.
621 %*********************************************************
625 %*********************************************************
628 --------------------------------
629 type FastStringEnv a = UniqFM a -- Keyed by FastString
632 emptyFsEnv :: FastStringEnv a
633 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
634 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
636 emptyFsEnv = emptyUFM
637 lookupFsEnv = lookupUFM
638 extendFsEnv = addToUFM
640 --------------------------------
641 type MiniFixityEnv = FastStringEnv (Located Fixity)
642 -- Mini fixity env for the names we're about
643 -- to bind, in a single binding group
645 -- It is keyed by the *FastString*, not the *OccName*, because
646 -- the single fixity decl infix 3 T
647 -- affects both the data constructor T and the type constrctor T
649 -- We keep the location so that if we find
650 -- a duplicate, we can report it sensibly
652 --------------------------------
653 -- Used for nested fixity decls to bind names along with their fixities.
654 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
655 -- Also check for unused binders
656 bindLocalNamesFV_WithFixities :: [Name]
658 -> RnM (a, FreeVars) -> RnM (a, FreeVars)
659 bindLocalNamesFV_WithFixities names fixities thing_inside
660 = bindLocalNamesFV names $
661 extendFixityEnv boundFixities $
664 -- find the names that have fixity decls
665 boundFixities = foldr
667 -- check whether this name has a fixity decl
668 case lookupFsEnv fixities (occNameFS (nameOccName name)) of
669 Just (L _ fix) -> (name, FixItem (nameOccName name) fix) : acc
670 Nothing -> acc) [] names
671 -- bind the names; extend the fixity env; do the thing inside
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 returnM (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_NoImplicitPrelude 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 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
773 if implicit_prelude then normal_case
775 -- Get the similarly named thing from the local environment
776 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
777 returnM (HsVar usr_name, unitFV usr_name)
779 normal_case = returnM (HsVar std_name, emptyFVs)
781 lookupSyntaxTable :: [Name] -- Standard names
782 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
783 lookupSyntaxTable std_names
784 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
785 if implicit_prelude then normal_case
787 -- Get the similarly named thing from the local environment
788 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
790 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
792 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
796 %*********************************************************
800 %*********************************************************
803 newLocalsRn :: [Located RdrName] -> RnM [Name]
804 newLocalsRn rdr_names_w_loc
805 = newUniqueSupply `thenM` \ us ->
806 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
808 mk (L loc rdr_name) uniq
809 | Just name <- isExact_maybe rdr_name = name
810 -- This happens in code generated by Template Haskell
811 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
812 -- We only bind unqualified names here
813 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
814 mkInternalName uniq (rdrNameOcc rdr_name) loc
816 ---------------------
817 checkDupAndShadowedRdrNames :: SDoc -> [Located RdrName] -> RnM ()
818 checkDupAndShadowedRdrNames doc loc_rdr_names
819 = do { checkDupRdrNames doc loc_rdr_names
821 ; checkShadowedNames doc envs
822 [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names] }
824 ---------------------
825 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
829 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
830 = checkDupAndShadowedRdrNames doc_str rdr_names_w_loc `thenM_`
832 -- Make fresh Names and extend the environment
833 newLocalsRn rdr_names_w_loc `thenM` \names ->
834 bindLocalNames names (enclosed_scope names)
836 bindLocalNames :: [Name] -> RnM a -> RnM a
837 bindLocalNames names enclosed_scope
838 = getLocalRdrEnv `thenM` \ name_env ->
839 setLocalRdrEnv (extendLocalRdrEnv name_env names)
842 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
843 bindLocalNamesFV names enclosed_scope
844 = do { (result, fvs) <- bindLocalNames names enclosed_scope
845 ; returnM (result, delListFromNameSet fvs names) }
848 -------------------------------------
849 -- binLocalsFVRn is the same as bindLocalsRn
850 -- except that it deals with free vars
851 bindLocatedLocalsFV :: SDoc -> [Located RdrName]
852 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
853 bindLocatedLocalsFV doc rdr_names enclosed_scope
854 = bindLocatedLocalsRn doc rdr_names $ \ names ->
855 enclosed_scope names `thenM` \ (thing, fvs) ->
856 returnM (thing, delListFromNameSet fvs names)
858 -------------------------------------
859 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
860 -> ([LHsTyVarBndr Name] -> RnM a)
862 -- Haskell-98 binding of type variables; e.g. within a data type decl
863 bindTyVarsRn doc_str tyvar_names enclosed_scope
864 = bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
865 do { kind_sigs_ok <- doptM Opt_KindSignatures
866 ; checkM (null kinded_tyvars || kind_sigs_ok)
867 (mapM_ (addErr . kindSigErr) kinded_tyvars)
868 ; enclosed_scope (zipWith replace tyvar_names names) }
870 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
871 located_tyvars = hsLTyVarLocNames tyvar_names
872 kinded_tyvars = [n | L _ (KindedTyVar n _) <- tyvar_names]
874 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
875 -- Find the type variables in the pattern type
876 -- signatures that must be brought into scope
877 bindPatSigTyVars tys thing_inside
878 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
879 ; if not scoped_tyvars then
882 do { name_env <- getLocalRdrEnv
883 ; let locd_tvs = [ tv | ty <- tys
884 , tv <- extractHsTyRdrTyVars ty
885 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
886 nubbed_tvs = nubBy eqLocated locd_tvs
887 -- The 'nub' is important. For example:
888 -- f (x :: t) (y :: t) = ....
889 -- We don't want to complain about binding t twice!
891 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
893 doc_sig = text "In a pattern type-signature"
895 bindPatSigTyVarsFV :: [LHsType RdrName]
898 bindPatSigTyVarsFV tys thing_inside
899 = bindPatSigTyVars tys $ \ tvs ->
900 thing_inside `thenM` \ (result,fvs) ->
901 returnM (result, fvs `delListFromNameSet` tvs)
903 bindSigTyVarsFV :: [Name]
906 bindSigTyVarsFV tvs thing_inside
907 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
908 ; if not scoped_tyvars then
911 bindLocalNamesFV tvs thing_inside }
913 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
914 -- This function is used only in rnSourceDecl on InstDecl
915 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
917 -------------------------------------
918 checkDupRdrNames :: SDoc
921 checkDupRdrNames doc_str rdr_names_w_loc
922 = -- Check for duplicated names in a binding group
923 mappM_ (dupNamesErr getLoc doc_str) dups
925 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
927 checkDupNames :: SDoc
930 checkDupNames doc_str names
931 = -- Check for duplicated names in a binding group
932 mappM_ (dupNamesErr nameSrcSpan doc_str) dups
934 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
936 -------------------------------------
937 checkShadowedNames :: SDoc -> (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
938 checkShadowedNames doc_str (global_env,local_env) loc_rdr_names
939 = ifOptM Opt_WarnNameShadowing $
940 do { traceRn (text "shadow" <+> ppr loc_rdr_names)
941 ; mappM_ check_shadow loc_rdr_names }
943 check_shadow (loc, occ)
944 | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
946 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
947 | otherwise = do { gres' <- filterM is_shadowed_gre gres
948 ; complain (map pprNameProvenance gres') }
950 complain [] = return ()
951 complain pp_locs = addWarnAt loc (shadowedNameWarn doc_str occ pp_locs)
952 mb_local = lookupLocalRdrOcc local_env occ
953 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
954 -- Make an Unqualified RdrName and look that up, so that
955 -- we don't find any GREs that are in scope qualified-only
957 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
958 -- Returns False for record selectors that are shadowed, when
959 -- punning or wild-cards are on (cf Trac #2723)
960 is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
961 = do { dflags <- getDOpts
962 ; if (dopt Opt_RecordPuns dflags || dopt Opt_RecordWildCards dflags)
963 then do { is_fld <- is_rec_fld gre; return (not is_fld) }
965 is_shadowed_gre _other = return True
967 is_rec_fld gre -- Return True for record selector ids
968 | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
969 ; return (gre_name gre `elemNameSet` fld_set) }
970 | otherwise = do { sel_id <- tcLookupField (gre_name gre)
971 ; return (isRecordSelector sel_id) }
975 %************************************************************************
977 \subsection{Free variable manipulation}
979 %************************************************************************
983 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
984 mapFvRn f xs = do stuff <- mappM f xs
986 (ys, fvs_s) -> returnM (ys, plusFVs fvs_s)
988 -- because some of the rename functions are CPSed:
989 -- maps the function across the list from left to right;
990 -- collects all the free vars into one set
991 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
992 -> [a] -> ([b] -> RnM c) -> RnM c
994 mapFvRnCPS _ [] cont = cont []
995 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
996 mapFvRnCPS f xs $ \ xs' ->
1001 %************************************************************************
1003 \subsection{Envt utility functions}
1005 %************************************************************************
1008 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
1009 warnUnusedModules mods
1010 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
1012 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
1013 mk_warn m = vcat [ptext (sLit "Module") <+> quotes (ppr m)
1014 <+> text "is imported, but nothing from it is used,",
1015 nest 2 (ptext (sLit "except perhaps instances visible in")
1016 <+> quotes (ppr m)),
1017 ptext (sLit "To suppress this warning, use:")
1018 <+> ptext (sLit "import") <+> ppr m <> parens empty ]
1021 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1022 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
1023 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
1025 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1026 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
1027 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
1029 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
1030 check_unused flag bound_names used_names
1031 = ifOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1033 -------------------------
1035 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1037 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1039 warnUnusedLocals :: [Name] -> RnM ()
1040 warnUnusedLocals names
1041 = warnUnusedBinds [(n,LocalDef) | n<-names]
1043 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
1044 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
1045 where reportable (name,_)
1046 | isWiredInName name = False -- Don't report unused wired-in names
1047 -- Otherwise we get a zillion warnings
1049 | otherwise = not (startsWithUnderscore (nameOccName name))
1051 -------------------------
1053 warnUnusedName :: (Name, Provenance) -> RnM ()
1054 warnUnusedName (name, LocalDef)
1055 = addUnusedWarning name (nameSrcSpan name)
1056 (ptext (sLit "Defined but not used"))
1058 warnUnusedName (name, Imported is)
1061 warn spec = addUnusedWarning name span msg
1063 span = importSpecLoc spec
1064 pp_mod = quotes (ppr (importSpecModule spec))
1065 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1067 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1068 addUnusedWarning name span msg
1071 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1072 <+> quotes (ppr name)]
1076 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1077 addNameClashErrRn rdr_name names
1078 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1079 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1082 msg1 = ptext (sLit "either") <+> mk_ref np1
1083 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
1084 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1086 shadowedNameWarn :: SDoc -> OccName -> [SDoc] -> SDoc
1087 shadowedNameWarn doc occ shadowed_locs
1088 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1089 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1090 nest 2 (vcat shadowed_locs)]
1093 unknownNameErr :: RdrName -> SDoc
1094 unknownNameErr rdr_name
1095 = vcat [ hang (ptext (sLit "Not in scope:"))
1096 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1097 <+> quotes (ppr rdr_name))
1100 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1103 perhapsForallMsg :: SDoc
1105 = vcat [ ptext (sLit "Perhaps you intended to use -XRankNTypes or similar flag")
1106 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1108 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1109 unknownSubordinateErr doc op -- Doc is "method of class" or
1110 -- "field of constructor"
1111 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1113 badOrigBinding :: RdrName -> SDoc
1115 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1116 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1118 dupNamesErr :: Outputable n => (n -> SrcSpan) -> SDoc -> [n] -> RnM ()
1119 dupNamesErr get_loc descriptor names
1120 = addErrAt big_loc $
1121 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1122 locations, descriptor]
1124 locs = map get_loc names
1125 big_loc = foldr1 combineSrcSpans locs
1126 one_line = isOneLineSpan big_loc
1127 locations | one_line = empty
1128 | otherwise = ptext (sLit "Bound at:") <+>
1129 vcat (map ppr (sortLe (<=) locs))
1131 kindSigErr :: Outputable a => a -> SDoc
1133 = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
1134 2 (ptext (sLit "Perhaps you intended to use -XKindSignatures"))
1137 badQualBndrErr :: RdrName -> SDoc
1138 badQualBndrErr rdr_name
1139 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
1141 opDeclErr :: RdrName -> SDoc
1143 = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
1144 2 (ptext (sLit "Use -XTypeOperators to declare operators in type and declarations"))