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, perhapsForallMsg
36 #include "HsVersions.h"
38 import LoadIface ( loadInterfaceForName, loadSrcInterface )
39 import IfaceEnv ( lookupOrig, newGlobalBinder, newIPName )
41 import RdrHsSyn ( extractHsTyRdrTyVars )
43 import HscTypes ( availNames, ModIface(..), FixItem(..), lookupFixity)
44 import TcEnv ( tcLookupDataCon, isBrackStage )
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
145 ; if isBrackStage stage then
146 -- We are inside a TH bracket, so make an *Internal* name
147 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
148 do { uniq <- newUnique
149 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
152 newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
155 %*********************************************************
157 Source code occurrences
159 %*********************************************************
161 Looking up a name in the RnEnv.
164 lookupLocatedBndrRn :: Located RdrName -> RnM (Located Name)
165 lookupLocatedBndrRn = wrapLocM lookupBndrRn
167 lookupBndrRn :: RdrName -> RnM Name
168 lookupBndrRn n = do nopt <- lookupBndrRn_maybe n
171 Nothing -> do traceRn $ text "lookupTopBndrRn"
174 lookupTopBndrRn :: RdrName -> RnM Name
175 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
178 Nothing -> do traceRn $ text "lookupTopBndrRn"
181 lookupBndrRn_maybe :: RdrName -> RnM (Maybe Name)
182 -- NOTE: assumes that the SrcSpan of the binder has already been setSrcSpan'd
183 lookupBndrRn_maybe rdr_name
184 = getLocalRdrEnv `thenM` \ local_env ->
185 case lookupLocalRdrEnv local_env rdr_name of
186 Just name -> returnM (Just name)
187 Nothing -> lookupTopBndrRn_maybe rdr_name
189 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
190 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
192 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
193 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
194 -- and there may be several imported 'f's too, which must not confuse us.
195 -- For example, this is OK:
197 -- infix 9 f -- The 'f' here does not need to be qualified
198 -- f x = x -- Nor here, of course
199 -- So we have to filter out the non-local ones.
201 -- A separate function (importsFromLocalDecls) reports duplicate top level
202 -- decls, so here it's safe just to choose an arbitrary one.
204 -- There should never be a qualified name in a binding position in Haskell,
205 -- but there can be if we have read in an external-Core file.
206 -- The Haskell parser checks for the illegal qualified name in Haskell
207 -- source files, so we don't need to do so here.
209 lookupTopBndrRn_maybe rdr_name
210 | Just name <- isExact_maybe rdr_name
211 = returnM (Just name)
213 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
214 -- This deals with the case of derived bindings, where
215 -- we don't bother to call newTopSrcBinder first
216 -- We assume there is no "parent" name
217 = do { loc <- getSrcSpanM
218 ; n <- newGlobalBinder rdr_mod rdr_occ loc
222 = do { mb_gre <- lookupGreLocalRn rdr_name
224 Nothing -> returnM Nothing
225 Just gre -> returnM (Just $ gre_name gre) }
228 -----------------------------------------------
229 lookupInstDeclBndr :: Name -> Located RdrName -> RnM (Located Name)
230 -- This is called on the method name on the left-hand side of an
231 -- instance declaration binding. eg. instance Functor T where
233 -- ^^^^ called on this
234 -- Regardless of how many unqualified fmaps are in scope, we want
235 -- the one that comes from the Functor class.
237 -- Furthermore, note that we take no account of whether the
238 -- name is only in scope qualified. I.e. even if method op is
239 -- in scope as M.op, we still allow plain 'op' on the LHS of
241 lookupInstDeclBndr cls rdr = lookup_located_sub_bndr is_op doc rdr
243 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
244 is_op (GRE {gre_par = ParentIs n}) = n == cls
247 -----------------------------------------------
248 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
249 -- Used for record construction and pattern matching
250 -- When the -fdisambiguate-record-fields flag is on, take account of the
251 -- constructor name to disambiguate which field to use; it's just the
252 -- same as for instance decls
253 lookupRecordBndr Nothing rdr_name
254 = lookupLocatedGlobalOccRn rdr_name
255 lookupRecordBndr (Just (L _ data_con)) rdr_name
256 = do { flag_on <- doptM Opt_DisambiguateRecordFields
258 then lookupLocatedGlobalOccRn rdr_name
260 fields <- lookupConstructorFields data_con
261 ; let is_field gre = gre_name gre `elem` fields
262 ; lookup_located_sub_bndr is_field doc rdr_name
265 doc = ptext (sLit "field of constructor") <+> quotes (ppr data_con)
268 lookupConstructorFields :: Name -> RnM [Name]
269 -- Look up the fields of a given constructor
270 -- * For constructors from this module, use the record field env,
271 -- which is itself gathered from the (as yet un-typechecked)
274 -- * For constructors from imported modules, use the *type* environment
275 -- since imported modles are already compiled, the info is conveniently
278 lookupConstructorFields con_name
279 = do { this_mod <- getModule
280 ; if nameIsLocalOrFrom this_mod con_name then
281 do { field_env <- getRecFieldEnv
282 ; return (lookupNameEnv field_env con_name `orElse` []) }
284 do { con <- tcLookupDataCon con_name
285 ; return (dataConFieldLabels con) } }
287 -----------------------------------------------
288 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
289 -> SDoc -> Located RdrName
290 -> RnM (Located Name)
291 lookup_located_sub_bndr is_good doc rdr_name
292 = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
294 lookup_sub_bndr :: (GlobalRdrElt -> Bool) -> SDoc -> RdrName -> RnM Name
295 lookup_sub_bndr is_good doc rdr_name
296 | isUnqual rdr_name -- Find all the things the rdr-name maps to
297 = do { -- and pick the one with the right parent name
298 ; env <- getGlobalRdrEnv
299 ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) of
300 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
301 -- The latter does pickGREs, but we want to allow 'x'
302 -- even if only 'M.x' is in scope
303 [gre] -> return (gre_name gre)
304 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
305 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
306 ; return (mkUnboundName rdr_name) }
307 gres -> do { addNameClashErrRn rdr_name gres
308 ; return (gre_name (head gres)) }
311 | otherwise -- Occurs in derived instances, where we just
312 -- refer directly to the right method
313 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
314 -- NB: qualified names are rejected by the parser
315 lookupImportedName rdr_name
317 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
318 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
320 -- Looking up family names in type instances is a subtle affair. The family
321 -- may be imported, in which case we need to lookup the occurence of a global
322 -- name. Alternatively, the family may be in the same binding group (and in
323 -- fact in a declaration processed later), and we need to create a new top
326 -- So, also this is strictly speaking an occurence, we cannot raise an error
327 -- message yet for instances without a family declaration. This will happen
328 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
330 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
331 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
332 = do { mb_gre <- lookupGreRn_maybe rdr_name
334 Just gre -> returnM (gre_name gre)
335 Nothing -> newTopSrcBinder mod lrdr_name }
337 --------------------------------------------------
339 --------------------------------------------------
341 getLookupOccRn :: RnM (Name -> Maybe Name)
343 = getLocalRdrEnv `thenM` \ local_env ->
344 return (lookupLocalRdrOcc local_env . nameOccName)
346 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
347 lookupLocatedOccRn = wrapLocM lookupOccRn
349 -- lookupOccRn looks up an occurrence of a RdrName
350 lookupOccRn :: RdrName -> RnM Name
352 = getLocalRdrEnv `thenM` \ local_env ->
353 case lookupLocalRdrEnv local_env rdr_name of
354 Just name -> returnM name
355 Nothing -> lookupGlobalOccRn rdr_name
357 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
358 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
360 lookupGlobalOccRn :: RdrName -> RnM Name
361 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
362 -- environment. It's used only for
363 -- record field names
364 -- class op names in class and instance decls
366 lookupGlobalOccRn rdr_name
367 | not (isSrcRdrName rdr_name)
368 = lookupImportedName rdr_name
372 -- First look up the name in the normal environment.
373 mb_gre <- lookupGreRn_maybe rdr_name
375 Just gre -> returnM (gre_name gre) ;
378 -- We allow qualified names on the command line to refer to
379 -- *any* name exported by any module in scope, just as if
380 -- there was an "import qualified M" declaration for every
382 allow_qual <- doptM Opt_ImplicitImportQualified
384 -- This test is not expensive,
385 -- and only happens for failed lookups
386 if isQual rdr_name && allow_qual && mod == iNTERACTIVE
387 then lookupQualifiedName rdr_name
389 traceRn $ text "lookupGlobalOccRn"
393 lookupImportedName :: RdrName -> TcRnIf m n Name
394 -- Lookup the occurrence of an imported name
395 -- The RdrName is *always* qualified or Exact
396 -- Treat it as an original name, and conjure up the Name
397 -- Usually it's Exact or Orig, but it can be Qual if it
398 -- comes from an hi-boot file. (This minor infelicity is
399 -- just to reduce duplication in the parser.)
400 lookupImportedName rdr_name
401 | Just n <- isExact_maybe rdr_name
402 -- This happens in derived code
405 -- Always Orig, even when reading a .hi-boot file
406 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
407 = lookupOrig rdr_mod rdr_occ
410 = pprPanic "RnEnv.lookupImportedName" (ppr rdr_name)
412 unboundName :: RdrName -> RnM Name
414 = do { addErr (unknownNameErr rdr_name)
415 ; env <- getGlobalRdrEnv;
416 ; traceRn (vcat [unknownNameErr rdr_name,
417 ptext (sLit "Global envt is:"),
418 nest 3 (pprGlobalRdrEnv env)])
419 ; returnM (mkUnboundName rdr_name) }
421 --------------------------------------------------
422 -- Lookup in the Global RdrEnv of the module
423 --------------------------------------------------
425 lookupSrcOcc_maybe :: RdrName -> RnM (Maybe Name)
426 -- No filter function; does not report an error on failure
427 lookupSrcOcc_maybe rdr_name
428 = do { mb_gre <- lookupGreRn_maybe rdr_name
430 Nothing -> returnM Nothing
431 Just gre -> returnM (Just (gre_name gre)) }
433 -------------------------
434 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
435 -- Just look up the RdrName in the GlobalRdrEnv
436 lookupGreRn_maybe rdr_name
437 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
439 lookupGreRn :: RdrName -> RnM GlobalRdrElt
440 -- If not found, add error message, and return a fake GRE
442 = do { mb_gre <- lookupGreRn_maybe rdr_name
444 Just gre -> return gre ;
446 { traceRn $ text "lookupGreRn"
447 ; name <- unboundName rdr_name
448 ; return (GRE { gre_name = name, gre_par = NoParent,
449 gre_prov = LocalDef }) }}}
451 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
452 -- Similar, but restricted to locally-defined things
453 lookupGreLocalRn rdr_name
454 = lookupGreRn_help rdr_name lookup_fn
456 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
458 lookupGreRn_help :: RdrName -- Only used in error message
459 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
460 -> RnM (Maybe GlobalRdrElt)
461 -- Checks for exactly one match; reports deprecations
462 -- Returns Nothing, without error, if too few
463 lookupGreRn_help rdr_name lookup
464 = do { env <- getGlobalRdrEnv
466 [] -> returnM Nothing
467 [gre] -> returnM (Just gre)
468 gres -> do { addNameClashErrRn rdr_name gres
469 ; returnM (Just (head gres)) } }
471 ------------------------------
473 ------------------------------
475 -- A qualified name on the command line can refer to any module at all: we
476 -- try to load the interface if we don't already have it.
477 lookupQualifiedName :: RdrName -> RnM Name
478 lookupQualifiedName rdr_name
479 | Just (mod,occ) <- isQual_maybe rdr_name
480 -- Note: we want to behave as we would for a source file import here,
481 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
482 = loadSrcInterface doc mod False Nothing `thenM` \ iface ->
485 (mod,avails) <- mi_exports iface,
487 name <- availNames avail,
489 ((mod,occ):ns) -> ASSERT (null ns)
491 _ -> unboundName rdr_name
494 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
496 doc = ptext (sLit "Need to find") <+> ppr rdr_name
499 %*********************************************************
503 %*********************************************************
506 --------------------------------
507 type FastStringEnv a = UniqFM a -- Keyed by FastString
510 emptyFsEnv :: FastStringEnv a
511 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
512 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
514 emptyFsEnv = emptyUFM
515 lookupFsEnv = lookupUFM
516 extendFsEnv = addToUFM
518 --------------------------------
519 type MiniFixityEnv = FastStringEnv (Located Fixity)
520 -- Mini fixity env for the names we're about
521 -- to bind, in a single binding group
523 -- It is keyed by the *FastString*, not the *OccName*, because
524 -- the single fixity decl infix 3 T
525 -- affects both the data constructor T and the type constrctor T
527 -- We keep the location so that if we find
528 -- a duplicate, we can report it sensibly
530 --------------------------------
531 -- Used for nested fixity decls to bind names along with their fixities.
532 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
533 -- Also check for unused binders
534 bindLocalNamesFV_WithFixities :: [Name]
536 -> RnM (a, FreeVars) -> RnM (a, FreeVars)
537 bindLocalNamesFV_WithFixities names fixities thing_inside
538 = bindLocalNamesFV names $
539 extendFixityEnv boundFixities $
542 -- find the names that have fixity decls
543 boundFixities = foldr
545 -- check whether this name has a fixity decl
546 case lookupFsEnv fixities (occNameFS (nameOccName name)) of
547 Just (L _ fix) -> (name, FixItem (nameOccName name) fix) : acc
548 Nothing -> acc) [] names
549 -- bind the names; extend the fixity env; do the thing inside
552 --------------------------------
553 lookupFixity is a bit strange.
555 * Nested local fixity decls are put in the local fixity env, which we
556 find with getFixtyEnv
558 * Imported fixities are found in the HIT or PIT
560 * Top-level fixity decls in this module may be for Names that are
561 either Global (constructors, class operations)
562 or Local/Exported (everything else)
563 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
564 We put them all in the local fixity environment
567 lookupFixityRn :: Name -> RnM Fixity
569 = getModule `thenM` \ this_mod ->
570 if nameIsLocalOrFrom this_mod name
571 then do -- It's defined in this module
572 local_fix_env <- getFixityEnv
573 traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
574 vcat [ppr name, ppr local_fix_env])
575 return $ lookupFixity local_fix_env name
576 else -- It's imported
577 -- For imported names, we have to get their fixities by doing a
578 -- loadInterfaceForName, and consulting the Ifaces that comes back
579 -- from that, because the interface file for the Name might not
580 -- have been loaded yet. Why not? Suppose you import module A,
581 -- which exports a function 'f', thus;
582 -- module CurrentModule where
584 -- module A( f ) where
586 -- Then B isn't loaded right away (after all, it's possible that
587 -- nothing from B will be used). When we come across a use of
588 -- 'f', we need to know its fixity, and it's then, and only
589 -- then, that we load B.hi. That is what's happening here.
591 -- loadInterfaceForName will find B.hi even if B is a hidden module,
592 -- and that's what we want.
593 loadInterfaceForName doc name `thenM` \ iface -> do {
594 traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
595 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
596 returnM (mi_fix_fn iface (nameOccName name))
599 doc = ptext (sLit "Checking fixity for") <+> ppr name
602 lookupTyFixityRn :: Located Name -> RnM Fixity
603 lookupTyFixityRn (L _ n) = lookupFixityRn n
606 lookupLocalDataTcNames :: RdrName -> RnM [Name]
607 -- GHC extension: look up both the tycon and data con
608 -- for con-like things
609 -- Complain if neither is in scope
610 lookupLocalDataTcNames rdr_name
611 | Just n <- isExact_maybe rdr_name
612 -- Special case for (:), which doesn't get into the GlobalRdrEnv
613 = return [n] -- For this we don't need to try the tycon too
615 = do { mb_gres <- mapM lookupGreLocalRn (dataTcOccs rdr_name)
616 ; case [gre_name gre | Just gre <- mb_gres] of
618 -- run for error reporting
619 ; unboundName rdr_name
621 names -> return names
624 dataTcOccs :: RdrName -> [RdrName]
625 -- If the input is a data constructor, return both it and a type
626 -- constructor. This is useful when we aren't sure which we are
629 | Just n <- isExact_maybe rdr_name -- Ghastly special case
630 , n `hasKey` consDataConKey = [rdr_name] -- see note below
631 | isDataOcc occ = [rdr_name_tc, rdr_name]
632 | otherwise = [rdr_name]
634 occ = rdrNameOcc rdr_name
635 rdr_name_tc = setRdrNameSpace rdr_name tcName
637 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
638 -- and setRdrNameSpace generates an Orig, which is fine
639 -- But it's not fine for (:), because there *is* no corresponding type
640 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
641 -- appear to be in scope (because Orig's simply allocate a new name-cache
642 -- entry) and then we get an error when we use dataTcOccs in
643 -- TcRnDriver.tcRnGetInfo. Large sigh.
646 %************************************************************************
649 Dealing with rebindable syntax is driven by the
650 Opt_NoImplicitPrelude dynamic flag.
652 In "deriving" code we don't want to use rebindable syntax
653 so we switch off the flag locally
656 %************************************************************************
658 Haskell 98 says that when you say "3" you get the "fromInteger" from the
659 Standard Prelude, regardless of what is in scope. However, to experiment
660 with having a language that is less coupled to the standard prelude, we're
661 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
662 happens to be in scope. Then you can
664 import MyPrelude as Prelude
665 to get the desired effect.
667 At the moment this just happens for
668 * fromInteger, fromRational on literals (in expressions and patterns)
669 * negate (in expressions)
670 * minus (arising from n+k patterns)
673 We store the relevant Name in the HsSyn tree, in
674 * HsIntegral/HsFractional/HsIsString
678 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
679 fromRationalName etc), but the renamer changes this to the appropriate user
680 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
682 We treat the orignal (standard) names as free-vars too, because the type checker
683 checks the type of the user thing against the type of the standard thing.
686 lookupSyntaxName :: Name -- The standard name
687 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
688 lookupSyntaxName std_name
689 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
690 if implicit_prelude then normal_case
692 -- Get the similarly named thing from the local environment
693 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
694 returnM (HsVar usr_name, unitFV usr_name)
696 normal_case = returnM (HsVar std_name, emptyFVs)
698 lookupSyntaxTable :: [Name] -- Standard names
699 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
700 lookupSyntaxTable std_names
701 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
702 if implicit_prelude then normal_case
704 -- Get the similarly named thing from the local environment
705 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
707 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
709 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
713 %*********************************************************
717 %*********************************************************
720 newLocalsRn :: [Located RdrName] -> RnM [Name]
721 newLocalsRn rdr_names_w_loc
722 = newUniqueSupply `thenM` \ us ->
723 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
725 mk (L loc rdr_name) uniq
726 | Just name <- isExact_maybe rdr_name = name
727 -- This happens in code generated by Template Haskell
728 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
729 -- We only bind unqualified names here
730 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
731 mkInternalName uniq (rdrNameOcc rdr_name) loc
733 ---------------------
734 checkDupAndShadowedRdrNames :: SDoc -> [Located RdrName] -> RnM ()
735 checkDupAndShadowedRdrNames doc loc_rdr_names
736 = do { checkDupRdrNames doc loc_rdr_names
738 ; checkShadowedNames doc envs
739 [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names] }
741 ---------------------
742 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
746 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
747 = checkDupAndShadowedRdrNames doc_str rdr_names_w_loc `thenM_`
749 -- Make fresh Names and extend the environment
750 newLocalsRn rdr_names_w_loc `thenM` \names ->
751 bindLocalNames names (enclosed_scope names)
753 bindLocalNames :: [Name] -> RnM a -> RnM a
754 bindLocalNames names enclosed_scope
755 = getLocalRdrEnv `thenM` \ name_env ->
756 setLocalRdrEnv (extendLocalRdrEnv name_env names)
759 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
760 bindLocalNamesFV names enclosed_scope
761 = do { (result, fvs) <- bindLocalNames names enclosed_scope
762 ; returnM (result, delListFromNameSet fvs names) }
765 -------------------------------------
766 -- binLocalsFVRn is the same as bindLocalsRn
767 -- except that it deals with free vars
768 bindLocatedLocalsFV :: SDoc -> [Located RdrName]
769 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
770 bindLocatedLocalsFV doc rdr_names enclosed_scope
771 = bindLocatedLocalsRn doc rdr_names $ \ names ->
772 enclosed_scope names `thenM` \ (thing, fvs) ->
773 returnM (thing, delListFromNameSet fvs names)
775 -------------------------------------
776 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
777 -> ([LHsTyVarBndr Name] -> RnM a)
779 -- Haskell-98 binding of type variables; e.g. within a data type decl
780 bindTyVarsRn doc_str tyvar_names enclosed_scope
782 located_tyvars = hsLTyVarLocNames tyvar_names
784 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
785 enclosed_scope (zipWith replace tyvar_names names)
787 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
789 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
790 -- Find the type variables in the pattern type
791 -- signatures that must be brought into scope
792 bindPatSigTyVars tys thing_inside
793 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
794 ; if not scoped_tyvars then
797 do { name_env <- getLocalRdrEnv
798 ; let locd_tvs = [ tv | ty <- tys
799 , tv <- extractHsTyRdrTyVars ty
800 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
801 nubbed_tvs = nubBy eqLocated locd_tvs
802 -- The 'nub' is important. For example:
803 -- f (x :: t) (y :: t) = ....
804 -- We don't want to complain about binding t twice!
806 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
808 doc_sig = text "In a pattern type-signature"
810 bindPatSigTyVarsFV :: [LHsType RdrName]
813 bindPatSigTyVarsFV tys thing_inside
814 = bindPatSigTyVars tys $ \ tvs ->
815 thing_inside `thenM` \ (result,fvs) ->
816 returnM (result, fvs `delListFromNameSet` tvs)
818 bindSigTyVarsFV :: [Name]
821 bindSigTyVarsFV tvs thing_inside
822 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
823 ; if not scoped_tyvars then
826 bindLocalNamesFV tvs thing_inside }
828 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
829 -- This function is used only in rnSourceDecl on InstDecl
830 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
832 -------------------------------------
833 checkDupRdrNames :: SDoc
836 checkDupRdrNames doc_str rdr_names_w_loc
837 = -- Check for duplicated names in a binding group
838 mappM_ (dupNamesErr getLoc doc_str) dups
840 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
842 checkDupNames :: SDoc
845 checkDupNames doc_str names
846 = -- Check for duplicated names in a binding group
847 mappM_ (dupNamesErr nameSrcSpan doc_str) dups
849 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
851 -------------------------------------
852 checkShadowedNames :: SDoc -> (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
853 checkShadowedNames doc_str (global_env,local_env) loc_rdr_names
854 = ifOptM Opt_WarnNameShadowing $
855 do { traceRn (text "shadow" <+> ppr loc_rdr_names)
856 ; mappM_ check_shadow loc_rdr_names }
858 check_shadow (loc, occ)
859 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
860 | not (null gres) = complain (map pprNameProvenance gres)
861 | otherwise = return ()
863 complain pp_locs = addWarnAt loc (shadowedNameWarn doc_str occ pp_locs)
864 mb_local = lookupLocalRdrOcc local_env occ
865 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
866 -- Make an Unqualified RdrName and look that up, so that
867 -- we don't find any GREs that are in scope qualified-only
871 %************************************************************************
873 \subsection{Free variable manipulation}
875 %************************************************************************
879 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
880 mapFvRn f xs = do stuff <- mappM f xs
882 (ys, fvs_s) -> returnM (ys, plusFVs fvs_s)
884 -- because some of the rename functions are CPSed:
885 -- maps the function across the list from left to right;
886 -- collects all the free vars into one set
887 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
888 -> [a] -> ([b] -> RnM c) -> RnM c
890 mapFvRnCPS _ [] cont = cont []
891 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
892 mapFvRnCPS f xs $ \ xs' ->
897 %************************************************************************
899 \subsection{Envt utility functions}
901 %************************************************************************
904 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
905 warnUnusedModules mods
906 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
908 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
909 mk_warn m = vcat [ptext (sLit "Module") <+> quotes (ppr m)
910 <+> text "is imported, but nothing from it is used,",
911 nest 2 (ptext (sLit "except perhaps instances visible in")
913 ptext (sLit "To suppress this warning, use:")
914 <+> ptext (sLit "import") <+> ppr m <> parens empty ]
917 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
918 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
919 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
921 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
922 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
923 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
925 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
926 check_unused flag bound_names used_names
927 = ifOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
929 -------------------------
931 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
933 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
935 warnUnusedLocals :: [Name] -> RnM ()
936 warnUnusedLocals names
937 = warnUnusedBinds [(n,LocalDef) | n<-names]
939 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
940 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
941 where reportable (name,_)
942 | isWiredInName name = False -- Don't report unused wired-in names
943 -- Otherwise we get a zillion warnings
945 | otherwise = reportIfUnused (nameOccName name)
947 -------------------------
949 warnUnusedName :: (Name, Provenance) -> RnM ()
950 warnUnusedName (name, LocalDef)
951 = addUnusedWarning name (srcLocSpan (nameSrcLoc name))
952 (ptext (sLit "Defined but not used"))
954 warnUnusedName (name, Imported is)
957 warn spec = addUnusedWarning name span msg
959 span = importSpecLoc spec
960 pp_mod = quotes (ppr (importSpecModule spec))
961 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
963 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
964 addUnusedWarning name span msg
967 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
968 <+> quotes (ppr name)]
972 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
973 addNameClashErrRn rdr_name names
974 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
975 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
978 msg1 = ptext (sLit "either") <+> mk_ref np1
979 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
980 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
982 shadowedNameWarn :: SDoc -> OccName -> [SDoc] -> SDoc
983 shadowedNameWarn doc occ shadowed_locs
984 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
985 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
986 nest 2 (vcat shadowed_locs)]
989 unknownNameErr :: RdrName -> SDoc
990 unknownNameErr rdr_name
991 = vcat [ hang (ptext (sLit "Not in scope:"))
992 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
993 <+> quotes (ppr rdr_name))
996 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
999 perhapsForallMsg :: SDoc
1001 = vcat [ ptext (sLit "Perhaps you intended to use -XRankNTypes or similar flag")
1002 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1004 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1005 unknownSubordinateErr doc op -- Doc is "method of class" or
1006 -- "field of constructor"
1007 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1009 badOrigBinding :: RdrName -> SDoc
1011 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1012 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1014 dupNamesErr :: Outputable n => (n -> SrcSpan) -> SDoc -> [n] -> RnM ()
1015 dupNamesErr get_loc descriptor names
1016 = addErrAt big_loc $
1017 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1018 locations, descriptor]
1020 locs = map get_loc names
1021 big_loc = foldr1 combineSrcSpans locs
1022 one_line = isOneLineSpan big_loc
1023 locations | one_line = empty
1024 | otherwise = ptext (sLit "Bound at:") <+>
1025 vcat (map ppr (sortLe (<=) locs))
1027 badQualBndrErr :: RdrName -> SDoc
1028 badQualBndrErr rdr_name
1029 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name