2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
4 \section[RnEnv]{Environment manipulation for the renamer monad}
8 newTopSrcBinder, lookupFamInstDeclBndr,
9 lookupLocatedBndrRn, lookupBndrRn, lookupBndrRn_maybe,
10 lookupLocatedTopBndrRn, lookupTopBndrRn,
11 lookupLocatedOccRn, lookupOccRn,
12 lookupLocatedGlobalOccRn, lookupGlobalOccRn,
13 lookupLocalDataTcNames, lookupSrcOcc_maybe,
14 lookupFixityRn, lookupTyFixityRn,
15 lookupInstDeclBndr, lookupRecordBndr, lookupConstructorFields,
16 lookupSyntaxName, lookupSyntaxTable, lookupImportedName,
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
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 )
46 import Name ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
47 nameSrcLoc, nameSrcSpan, nameOccName, nameModule, isExternalName )
51 import DataCon ( dataConFieldLabels )
53 import Module ( Module, ModuleName )
54 import PrelNames ( mkUnboundName, rOOT_MAIN, iNTERACTIVE,
55 consDataConKey, hasKey, forall_tv_RDR )
57 import BasicTypes ( IPName, mapIPName, Fixity )
62 import ListSetOps ( removeDups )
71 thenM :: Monad a => a b -> (b -> a c) -> a c
74 thenM_ :: Monad a => a b -> a c -> a c
77 returnM :: Monad m => a -> m a
80 mappM :: (Monad m) => (a -> m b) -> [a] -> m [b]
83 mappM_ :: (Monad m) => (a -> m b) -> [a] -> m ()
86 checkM :: Monad m => Bool -> m () -> m ()
90 %*********************************************************
94 %*********************************************************
97 newTopSrcBinder :: Module -> Located RdrName -> RnM Name
98 newTopSrcBinder this_mod (L loc rdr_name)
99 | Just name <- isExact_maybe rdr_name
100 = -- This is here to catch
101 -- (a) Exact-name binders created by Template Haskell
102 -- (b) The PrelBase defn of (say) [] and similar, for which
103 -- the parser reads the special syntax and returns an Exact RdrName
104 -- We are at a binding site for the name, so check first that it
105 -- the current module is the correct one; otherwise GHC can get
106 -- very confused indeed. This test rejects code like
107 -- data T = (,) Int Int
108 -- unless we are in GHC.Tup
109 ASSERT2( isExternalName name, ppr name )
110 do { checkM (this_mod == nameModule name)
111 (addErrAt loc (badOrigBinding rdr_name))
115 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
116 = do { checkM (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
117 (addErrAt loc (badOrigBinding rdr_name))
118 -- When reading External Core we get Orig names as binders,
119 -- but they should agree with the module gotten from the monad
121 -- We can get built-in syntax showing up here too, sadly. If you type
123 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
124 -- uses setRdrNameSpace to make it into a data constructors. At that point
125 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
126 -- Hence the badOrigBinding error message.
128 -- Except for the ":Main.main = ..." definition inserted into
129 -- the Main module; ugh!
131 -- Because of this latter case, we call newGlobalBinder with a module from
132 -- the RdrName, not from the environment. In principle, it'd be fine to
133 -- have an arbitrary mixture of external core definitions in a single module,
134 -- (apart from module-initialisation issues, perhaps).
135 ; newGlobalBinder rdr_mod rdr_occ loc }
136 --TODO, should pass the whole span
139 = do { checkM (not (isQual rdr_name))
140 (addErrAt loc (badQualBndrErr rdr_name))
141 -- Binders should not be qualified; if they are, and with a different
142 -- module name, we we get a confusing "M.T is not in scope" error later
143 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
146 %*********************************************************
148 Source code occurrences
150 %*********************************************************
152 Looking up a name in the RnEnv.
155 lookupLocatedBndrRn :: Located RdrName -> RnM (Located Name)
156 lookupLocatedBndrRn = wrapLocM lookupBndrRn
158 lookupBndrRn :: RdrName -> RnM Name
159 lookupBndrRn n = do nopt <- lookupBndrRn_maybe n
162 Nothing -> do traceRn $ text "lookupTopBndrRn"
165 lookupTopBndrRn :: RdrName -> RnM Name
166 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
169 Nothing -> do traceRn $ text "lookupTopBndrRn"
172 lookupBndrRn_maybe :: RdrName -> RnM (Maybe Name)
173 -- NOTE: assumes that the SrcSpan of the binder has already been setSrcSpan'd
174 lookupBndrRn_maybe rdr_name
175 = getLocalRdrEnv `thenM` \ local_env ->
176 case lookupLocalRdrEnv local_env rdr_name of
177 Just name -> returnM (Just name)
178 Nothing -> lookupTopBndrRn_maybe rdr_name
180 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
181 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
183 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
184 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
185 -- and there may be several imported 'f's too, which must not confuse us.
186 -- For example, this is OK:
188 -- infix 9 f -- The 'f' here does not need to be qualified
189 -- f x = x -- Nor here, of course
190 -- So we have to filter out the non-local ones.
192 -- A separate function (importsFromLocalDecls) reports duplicate top level
193 -- decls, so here it's safe just to choose an arbitrary one.
195 -- There should never be a qualified name in a binding position in Haskell,
196 -- but there can be if we have read in an external-Core file.
197 -- The Haskell parser checks for the illegal qualified name in Haskell
198 -- source files, so we don't need to do so here.
200 lookupTopBndrRn_maybe rdr_name
201 | Just name <- isExact_maybe rdr_name
202 = returnM (Just name)
204 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
205 -- This deals with the case of derived bindings, where
206 -- we don't bother to call newTopSrcBinder first
207 -- We assume there is no "parent" name
208 = do { loc <- getSrcSpanM
209 ; n <- newGlobalBinder rdr_mod rdr_occ loc
213 = do { mb_gre <- lookupGreLocalRn rdr_name
215 Nothing -> returnM Nothing
216 Just gre -> returnM (Just $ gre_name gre) }
219 -----------------------------------------------
220 lookupInstDeclBndr :: Name -> Located RdrName -> RnM (Located 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 = lookup_located_sub_bndr is_op doc rdr
234 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
235 is_op (GRE {gre_par = ParentIs n}) = n == cls
238 -----------------------------------------------
239 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
240 -- Used for record construction and pattern matching
241 -- When the -fdisambiguate-record-fields flag is on, take account of the
242 -- constructor name to disambiguate which field to use; it's just the
243 -- same as for instance decls
244 lookupRecordBndr Nothing rdr_name
245 = lookupLocatedGlobalOccRn rdr_name
246 lookupRecordBndr (Just (L _ data_con)) rdr_name
247 = do { flag_on <- doptM Opt_DisambiguateRecordFields
249 then lookupLocatedGlobalOccRn rdr_name
251 fields <- lookupConstructorFields data_con
252 ; let is_field gre = gre_name gre `elem` fields
253 ; lookup_located_sub_bndr is_field doc rdr_name
256 doc = ptext (sLit "field of constructor") <+> quotes (ppr data_con)
259 lookupConstructorFields :: Name -> RnM [Name]
260 -- Look up the fields of a given constructor
261 -- * For constructors from this module, use the record field env,
262 -- which is itself gathered from the (as yet un-typechecked)
265 -- * For constructors from imported modules, use the *type* environment
266 -- since imported modles are already compiled, the info is conveniently
269 lookupConstructorFields con_name
270 = do { this_mod <- getModule
271 ; if nameIsLocalOrFrom this_mod con_name then
272 do { field_env <- getRecFieldEnv
273 ; return (lookupNameEnv field_env con_name `orElse` []) }
275 do { con <- tcLookupDataCon con_name
276 ; return (dataConFieldLabels con) } }
278 -----------------------------------------------
279 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
280 -> SDoc -> Located RdrName
281 -> RnM (Located Name)
282 lookup_located_sub_bndr is_good doc rdr_name
283 = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
285 lookup_sub_bndr :: (GlobalRdrElt -> Bool) -> SDoc -> RdrName -> RnM Name
286 lookup_sub_bndr is_good doc rdr_name
287 | isUnqual rdr_name -- Find all the things the rdr-name maps to
288 = do { -- and pick the one with the right parent name
289 ; env <- getGlobalRdrEnv
290 ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) 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] -> return (gre_name gre)
295 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
296 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
297 ; return (mkUnboundName rdr_name) }
298 gres -> do { addNameClashErrRn rdr_name gres
299 ; return (gre_name (head gres)) }
302 | otherwise -- Occurs in derived instances, where we just
303 -- refer directly to the right method
304 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
305 -- NB: qualified names are rejected by the parser
306 lookupImportedName rdr_name
308 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
309 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
311 -- Looking up family names in type instances is a subtle affair. The family
312 -- may be imported, in which case we need to lookup the occurence of a global
313 -- name. Alternatively, the family may be in the same binding group (and in
314 -- fact in a declaration processed later), and we need to create a new top
317 -- So, also this is strictly speaking an occurence, we cannot raise an error
318 -- message yet for instances without a family declaration. This will happen
319 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
321 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
322 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
323 = do { mb_gre <- lookupGreRn_maybe rdr_name
325 Just gre -> returnM (gre_name gre) ;
326 Nothing -> newTopSrcBinder mod lrdr_name }
328 --------------------------------------------------
330 --------------------------------------------------
332 getLookupOccRn :: RnM (Name -> Maybe Name)
334 = getLocalRdrEnv `thenM` \ local_env ->
335 return (lookupLocalRdrOcc local_env . nameOccName)
337 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
338 lookupLocatedOccRn = wrapLocM lookupOccRn
340 -- lookupOccRn looks up an occurrence of a RdrName
341 lookupOccRn :: RdrName -> RnM Name
343 = getLocalRdrEnv `thenM` \ local_env ->
344 case lookupLocalRdrEnv local_env rdr_name of
345 Just name -> returnM name
346 Nothing -> lookupGlobalOccRn rdr_name
348 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
349 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
351 lookupGlobalOccRn :: RdrName -> RnM Name
352 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
353 -- environment. It's used only for
354 -- record field names
355 -- class op names in class and instance decls
357 lookupGlobalOccRn rdr_name
358 | not (isSrcRdrName rdr_name)
359 = lookupImportedName rdr_name
362 = -- First look up the name in the normal environment.
363 lookupGreRn_maybe rdr_name `thenM` \ mb_gre ->
365 Just gre -> returnM (gre_name gre) ;
368 -- We allow qualified names on the command line to refer to
369 -- *any* name exported by any module in scope, just as if
370 -- there was an "import qualified M" declaration for every
372 getModule `thenM` \ mod ->
373 if isQual rdr_name && mod == iNTERACTIVE then
374 -- This test is not expensive,
375 lookupQualifiedName rdr_name -- and only happens for failed lookups
377 traceRn $ text "lookupGlobalOccRn"
378 unboundName rdr_name }
380 lookupImportedName :: RdrName -> TcRnIf m n Name
381 -- Lookup the occurrence of an imported name
382 -- The RdrName is *always* qualified or Exact
383 -- Treat it as an original name, and conjure up the Name
384 -- Usually it's Exact or Orig, but it can be Qual if it
385 -- comes from an hi-boot file. (This minor infelicity is
386 -- just to reduce duplication in the parser.)
387 lookupImportedName rdr_name
388 | Just n <- isExact_maybe rdr_name
389 -- This happens in derived code
392 -- Always Orig, even when reading a .hi-boot file
393 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
394 = lookupOrig rdr_mod rdr_occ
397 = pprPanic "RnEnv.lookupImportedName" (ppr rdr_name)
399 unboundName :: RdrName -> RnM Name
401 = do { addErr (unknownNameErr rdr_name)
402 ; env <- getGlobalRdrEnv;
403 ; traceRn (vcat [unknownNameErr rdr_name,
404 ptext (sLit "Global envt is:"),
405 nest 3 (pprGlobalRdrEnv env)])
406 ; returnM (mkUnboundName rdr_name) }
408 --------------------------------------------------
409 -- Lookup in the Global RdrEnv of the module
410 --------------------------------------------------
412 lookupSrcOcc_maybe :: RdrName -> RnM (Maybe Name)
413 -- No filter function; does not report an error on failure
414 lookupSrcOcc_maybe rdr_name
415 = do { mb_gre <- lookupGreRn_maybe rdr_name
417 Nothing -> returnM Nothing
418 Just gre -> returnM (Just (gre_name gre)) }
420 -------------------------
421 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
422 -- Just look up the RdrName in the GlobalRdrEnv
423 lookupGreRn_maybe rdr_name
424 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
426 lookupGreRn :: RdrName -> RnM GlobalRdrElt
427 -- If not found, add error message, and return a fake GRE
429 = do { mb_gre <- lookupGreRn_maybe rdr_name
431 Just gre -> return gre ;
433 { traceRn $ text "lookupGreRn"
434 ; name <- unboundName rdr_name
435 ; return (GRE { gre_name = name, gre_par = NoParent,
436 gre_prov = LocalDef }) }}}
438 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
439 -- Similar, but restricted to locally-defined things
440 lookupGreLocalRn rdr_name
441 = lookupGreRn_help rdr_name lookup_fn
443 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
445 lookupGreRn_help :: RdrName -- Only used in error message
446 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
447 -> RnM (Maybe GlobalRdrElt)
448 -- Checks for exactly one match; reports deprecations
449 -- Returns Nothing, without error, if too few
450 lookupGreRn_help rdr_name lookup
451 = do { env <- getGlobalRdrEnv
453 [] -> returnM Nothing
454 [gre] -> returnM (Just gre)
455 gres -> do { addNameClashErrRn rdr_name gres
456 ; returnM (Just (head gres)) } }
458 ------------------------------
460 ------------------------------
462 -- A qualified name on the command line can refer to any module at all: we
463 -- try to load the interface if we don't already have it.
464 lookupQualifiedName :: RdrName -> RnM Name
465 lookupQualifiedName rdr_name
466 | Just (mod,occ) <- isQual_maybe rdr_name
467 -- Note: we want to behave as we would for a source file import here,
468 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
469 = loadSrcInterface doc mod False `thenM` \ iface ->
472 (mod,avails) <- mi_exports iface,
474 name <- availNames avail,
476 ((mod,occ):ns) -> ASSERT (null ns)
478 _ -> unboundName rdr_name
481 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
483 doc = ptext (sLit "Need to find") <+> ppr rdr_name
486 %*********************************************************
490 %*********************************************************
493 --------------------------------
494 type FastStringEnv a = UniqFM a -- Keyed by FastString
497 emptyFsEnv :: FastStringEnv a
498 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
499 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
501 emptyFsEnv = emptyUFM
502 lookupFsEnv = lookupUFM
503 extendFsEnv = addToUFM
505 --------------------------------
506 type MiniFixityEnv = FastStringEnv (Located Fixity)
507 -- Mini fixity env for the names we're about
508 -- to bind, in a single binding group
510 -- It is keyed by the *FastString*, not the *OccName*, because
511 -- the single fixity decl infix 3 T
512 -- affects both the data constructor T and the type constrctor T
514 -- We keep the location so that if we find
515 -- a duplicate, we can report it sensibly
517 --------------------------------
518 -- Used for nested fixity decls to bind names along with their fixities.
519 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
520 -- Also check for unused binders
521 bindLocalNamesFV_WithFixities :: [Name]
523 -> RnM (a, FreeVars) -> RnM (a, FreeVars)
524 bindLocalNamesFV_WithFixities names fixities thing_inside
525 = bindLocalNamesFV names $
526 extendFixityEnv boundFixities $
529 -- find the names that have fixity decls
530 boundFixities = foldr
532 -- check whether this name has a fixity decl
533 case lookupFsEnv fixities (occNameFS (nameOccName name)) of
534 Just (L _ fix) -> (name, FixItem (nameOccName name) fix) : acc
535 Nothing -> acc) [] names
536 -- bind the names; extend the fixity env; do the thing inside
539 --------------------------------
540 lookupFixity is a bit strange.
542 * Nested local fixity decls are put in the local fixity env, which we
543 find with getFixtyEnv
545 * Imported fixities are found in the HIT or PIT
547 * Top-level fixity decls in this module may be for Names that are
548 either Global (constructors, class operations)
549 or Local/Exported (everything else)
550 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
551 We put them all in the local fixity environment
554 lookupFixityRn :: Name -> RnM Fixity
556 = getModule `thenM` \ this_mod ->
557 if nameIsLocalOrFrom this_mod name
558 then do -- It's defined in this module
559 local_fix_env <- getFixityEnv
560 traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
561 vcat [ppr name, ppr local_fix_env])
562 return $ lookupFixity local_fix_env name
563 else -- It's imported
564 -- For imported names, we have to get their fixities by doing a
565 -- loadInterfaceForName, and consulting the Ifaces that comes back
566 -- from that, because the interface file for the Name might not
567 -- have been loaded yet. Why not? Suppose you import module A,
568 -- which exports a function 'f', thus;
569 -- module CurrentModule where
571 -- module A( f ) where
573 -- Then B isn't loaded right away (after all, it's possible that
574 -- nothing from B will be used). When we come across a use of
575 -- 'f', we need to know its fixity, and it's then, and only
576 -- then, that we load B.hi. That is what's happening here.
578 -- loadInterfaceForName will find B.hi even if B is a hidden module,
579 -- and that's what we want.
580 loadInterfaceForName doc name `thenM` \ iface -> do {
581 traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
582 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
583 returnM (mi_fix_fn iface (nameOccName name))
586 doc = ptext (sLit "Checking fixity for") <+> ppr name
589 lookupTyFixityRn :: Located Name -> RnM Fixity
590 lookupTyFixityRn (L _ n) = lookupFixityRn n
593 lookupLocalDataTcNames :: RdrName -> RnM [Name]
594 -- GHC extension: look up both the tycon and data con
595 -- for con-like things
596 -- Complain if neither is in scope
597 lookupLocalDataTcNames rdr_name
598 | Just n <- isExact_maybe rdr_name
599 -- Special case for (:), which doesn't get into the GlobalRdrEnv
600 = return [n] -- For this we don't need to try the tycon too
602 = do { mb_gres <- mapM lookupGreLocalRn (dataTcOccs rdr_name)
603 ; case [gre_name gre | Just gre <- mb_gres] of
605 -- run for error reporting
606 ; unboundName rdr_name
608 names -> return names
611 dataTcOccs :: RdrName -> [RdrName]
612 -- If the input is a data constructor, return both it and a type
613 -- constructor. This is useful when we aren't sure which we are
616 | Just n <- isExact_maybe rdr_name -- Ghastly special case
617 , n `hasKey` consDataConKey = [rdr_name] -- see note below
618 | isDataOcc occ = [rdr_name_tc, rdr_name]
619 | otherwise = [rdr_name]
621 occ = rdrNameOcc rdr_name
622 rdr_name_tc = setRdrNameSpace rdr_name tcName
624 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
625 -- and setRdrNameSpace generates an Orig, which is fine
626 -- But it's not fine for (:), because there *is* no corresponding type
627 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
628 -- appear to be in scope (because Orig's simply allocate a new name-cache
629 -- entry) and then we get an error when we use dataTcOccs in
630 -- TcRnDriver.tcRnGetInfo. Large sigh.
633 %************************************************************************
636 Dealing with rebindable syntax is driven by the
637 Opt_NoImplicitPrelude dynamic flag.
639 In "deriving" code we don't want to use rebindable syntax
640 so we switch off the flag locally
643 %************************************************************************
645 Haskell 98 says that when you say "3" you get the "fromInteger" from the
646 Standard Prelude, regardless of what is in scope. However, to experiment
647 with having a language that is less coupled to the standard prelude, we're
648 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
649 happens to be in scope. Then you can
651 import MyPrelude as Prelude
652 to get the desired effect.
654 At the moment this just happens for
655 * fromInteger, fromRational on literals (in expressions and patterns)
656 * negate (in expressions)
657 * minus (arising from n+k patterns)
660 We store the relevant Name in the HsSyn tree, in
661 * HsIntegral/HsFractional/HsIsString
665 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
666 fromRationalName etc), but the renamer changes this to the appropriate user
667 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
669 We treat the orignal (standard) names as free-vars too, because the type checker
670 checks the type of the user thing against the type of the standard thing.
673 lookupSyntaxName :: Name -- The standard name
674 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
675 lookupSyntaxName std_name
676 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
677 if implicit_prelude then normal_case
679 -- Get the similarly named thing from the local environment
680 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
681 returnM (HsVar usr_name, unitFV usr_name)
683 normal_case = returnM (HsVar std_name, emptyFVs)
685 lookupSyntaxTable :: [Name] -- Standard names
686 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
687 lookupSyntaxTable std_names
688 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
689 if implicit_prelude then normal_case
691 -- Get the similarly named thing from the local environment
692 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
694 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
696 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
700 %*********************************************************
704 %*********************************************************
707 newLocalsRn :: [Located RdrName] -> RnM [Name]
708 newLocalsRn rdr_names_w_loc
709 = newUniqueSupply `thenM` \ us ->
710 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
712 mk (L loc rdr_name) uniq
713 | Just name <- isExact_maybe rdr_name = name
714 -- This happens in code generated by Template Haskell
715 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
716 -- We only bind unqualified names here
717 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
718 mkInternalName uniq (rdrNameOcc rdr_name) loc
720 ---------------------
721 checkDupAndShadowedRdrNames :: SDoc -> [Located RdrName] -> RnM ()
722 checkDupAndShadowedRdrNames doc loc_rdr_names
723 = do { checkDupRdrNames doc loc_rdr_names
725 ; checkShadowedNames doc envs
726 [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names] }
728 ---------------------
729 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
733 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
734 = checkDupAndShadowedRdrNames doc_str rdr_names_w_loc `thenM_`
736 -- Make fresh Names and extend the environment
737 newLocalsRn rdr_names_w_loc `thenM` \names ->
738 bindLocalNames names (enclosed_scope names)
740 bindLocalNames :: [Name] -> RnM a -> RnM a
741 bindLocalNames names enclosed_scope
742 = getLocalRdrEnv `thenM` \ name_env ->
743 setLocalRdrEnv (extendLocalRdrEnv name_env names)
746 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
747 bindLocalNamesFV names enclosed_scope
748 = do { (result, fvs) <- bindLocalNames names enclosed_scope
749 ; returnM (result, delListFromNameSet fvs names) }
752 -------------------------------------
753 -- binLocalsFVRn is the same as bindLocalsRn
754 -- except that it deals with free vars
755 bindLocatedLocalsFV :: SDoc -> [Located RdrName]
756 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
757 bindLocatedLocalsFV doc rdr_names enclosed_scope
758 = bindLocatedLocalsRn doc rdr_names $ \ names ->
759 enclosed_scope names `thenM` \ (thing, fvs) ->
760 returnM (thing, delListFromNameSet fvs names)
762 -------------------------------------
763 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
764 -> ([LHsTyVarBndr Name] -> RnM a)
766 -- Haskell-98 binding of type variables; e.g. within a data type decl
767 bindTyVarsRn doc_str tyvar_names enclosed_scope
769 located_tyvars = hsLTyVarLocNames tyvar_names
771 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
772 enclosed_scope (zipWith replace tyvar_names names)
774 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
776 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
777 -- Find the type variables in the pattern type
778 -- signatures that must be brought into scope
779 bindPatSigTyVars tys thing_inside
780 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
781 ; if not scoped_tyvars then
784 do { name_env <- getLocalRdrEnv
785 ; let locd_tvs = [ tv | ty <- tys
786 , tv <- extractHsTyRdrTyVars ty
787 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
788 nubbed_tvs = nubBy eqLocated locd_tvs
789 -- The 'nub' is important. For example:
790 -- f (x :: t) (y :: t) = ....
791 -- We don't want to complain about binding t twice!
793 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
795 doc_sig = text "In a pattern type-signature"
797 bindPatSigTyVarsFV :: [LHsType RdrName]
800 bindPatSigTyVarsFV tys thing_inside
801 = bindPatSigTyVars tys $ \ tvs ->
802 thing_inside `thenM` \ (result,fvs) ->
803 returnM (result, fvs `delListFromNameSet` tvs)
805 bindSigTyVarsFV :: [Name]
808 bindSigTyVarsFV tvs thing_inside
809 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
810 ; if not scoped_tyvars then
813 bindLocalNamesFV tvs thing_inside }
815 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
816 -- This function is used only in rnSourceDecl on InstDecl
817 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
819 -------------------------------------
820 checkDupRdrNames :: SDoc
823 checkDupRdrNames doc_str rdr_names_w_loc
824 = -- Check for duplicated names in a binding group
825 mappM_ (dupNamesErr getLoc doc_str) dups
827 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
829 checkDupNames :: SDoc
832 checkDupNames doc_str names
833 = -- Check for duplicated names in a binding group
834 mappM_ (dupNamesErr nameSrcSpan doc_str) dups
836 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
838 -------------------------------------
839 checkShadowedNames :: SDoc -> (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
840 checkShadowedNames doc_str (global_env,local_env) loc_rdr_names
841 = ifOptM Opt_WarnNameShadowing $
842 do { traceRn (text "shadow" <+> ppr loc_rdr_names)
843 ; mappM_ check_shadow loc_rdr_names }
845 check_shadow (loc, occ)
846 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
847 | not (null gres) = complain (map pprNameProvenance gres)
848 | otherwise = return ()
850 complain pp_locs = addWarnAt loc (shadowedNameWarn doc_str occ pp_locs)
851 mb_local = lookupLocalRdrOcc local_env occ
852 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
853 -- Make an Unqualified RdrName and look that up, so that
854 -- we don't find any GREs that are in scope qualified-only
858 %************************************************************************
860 \subsection{Free variable manipulation}
862 %************************************************************************
866 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
867 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
869 (ys, fvs_s) = unzip stuff
871 returnM (ys, plusFVs fvs_s)
873 -- because some of the rename functions are CPSed:
874 -- maps the function across the list from left to right;
875 -- collects all the free vars into one set
876 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
877 -> [a] -> ([b] -> RnM c) -> RnM c
879 mapFvRnCPS _ [] cont = cont []
880 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
881 mapFvRnCPS f xs $ \ xs' ->
886 %************************************************************************
888 \subsection{Envt utility functions}
890 %************************************************************************
893 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
894 warnUnusedModules mods
895 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
897 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
898 mk_warn m = vcat [ptext (sLit "Module") <+> quotes (ppr m)
899 <+> text "is imported, but nothing from it is used,",
900 nest 2 (ptext (sLit "except perhaps instances visible in")
902 ptext (sLit "To suppress this warning, use:")
903 <+> ptext (sLit "import") <+> ppr m <> parens empty ]
906 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
907 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
908 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
910 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
911 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
912 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
914 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
915 check_unused flag bound_names used_names
916 = ifOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
918 -------------------------
920 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
922 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
924 warnUnusedLocals :: [Name] -> RnM ()
925 warnUnusedLocals names
926 = warnUnusedBinds [(n,LocalDef) | n<-names]
928 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
929 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
930 where reportable (name,_)
931 | isWiredInName name = False -- Don't report unused wired-in names
932 -- Otherwise we get a zillion warnings
934 | otherwise = reportIfUnused (nameOccName name)
936 -------------------------
938 warnUnusedName :: (Name, Provenance) -> RnM ()
939 warnUnusedName (name, LocalDef)
940 = addUnusedWarning name (srcLocSpan (nameSrcLoc name))
941 (ptext (sLit "Defined but not used"))
943 warnUnusedName (name, Imported is)
946 warn spec = addUnusedWarning name span msg
948 span = importSpecLoc spec
949 pp_mod = quotes (ppr (importSpecModule spec))
950 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
952 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
953 addUnusedWarning name span msg
956 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
957 <+> quotes (ppr name)]
961 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
962 addNameClashErrRn rdr_name names
963 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
964 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
967 msg1 = ptext (sLit "either") <+> mk_ref np1
968 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
969 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
971 shadowedNameWarn :: SDoc -> OccName -> [SDoc] -> SDoc
972 shadowedNameWarn doc occ shadowed_locs
973 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
974 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
975 nest 2 (vcat shadowed_locs)]
978 unknownNameErr :: RdrName -> SDoc
979 unknownNameErr rdr_name
980 = vcat [ hang (ptext (sLit "Not in scope:"))
981 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
982 <+> quotes (ppr rdr_name))
985 extra | rdr_name == forall_tv_RDR
986 = ptext (sLit "Perhaps you intended to use -XRankNTypes or similar flag")
989 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
990 unknownSubordinateErr doc op -- Doc is "method of class" or
991 -- "field of constructor"
992 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
994 badOrigBinding :: RdrName -> SDoc
996 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
997 -- The rdrNameOcc is because we don't want to print Prelude.(,)
999 dupNamesErr :: Outputable n => (n -> SrcSpan) -> SDoc -> [n] -> RnM ()
1000 dupNamesErr get_loc descriptor names
1001 = addErrAt big_loc $
1002 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1003 locations, descriptor]
1005 locs = map get_loc names
1006 big_loc = foldr1 combineSrcSpans locs
1007 one_line = isOneLineSpan big_loc
1008 locations | one_line = empty
1009 | otherwise = ptext (sLit "Bound at:") <+>
1010 vcat (map ppr (sortLe (<=) locs))
1012 badQualBndrErr :: RdrName -> SDoc
1013 badQualBndrErr rdr_name
1014 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name