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,
10 lookupLocatedTopBndrRn, lookupTopBndrRn,
11 lookupLocatedOccRn, lookupOccRn,
12 lookupLocatedGlobalOccRn, lookupGlobalOccRn,
13 lookupLocalDataTcNames, lookupSrcOcc_maybe,
14 lookupFixityRn, lookupTyFixityRn, lookupLocatedSigOccRn,
15 lookupInstDeclBndr, lookupRecordBndr, lookupConstructorFields,
16 lookupSyntaxName, lookupSyntaxTable, lookupImportedName,
17 lookupGreRn, lookupGreRn_maybe,
20 newLocalsRn, newIPNameRn,
21 bindLocalNames, bindLocalNamesFV,
22 bindLocatedLocalsFV, bindLocatedLocalsRn,
23 bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
24 bindTyVarsRn, extendTyVarEnvFVRn,
27 checkDupNames, mapFvRn,
28 warnUnusedMatches, warnUnusedModules, warnUnusedImports,
29 warnUnusedTopBinds, warnUnusedLocalBinds,
30 dataTcOccs, unknownNameErr,
33 #include "HsVersions.h"
35 import LoadIface ( loadInterfaceForName, loadSrcInterface )
36 import IfaceEnv ( lookupOrig, newGlobalBinder, newIPName )
37 import HsSyn ( FixitySig(..), HsExpr(..), SyntaxExpr, SyntaxTable,
38 LHsTyVarBndr, LHsType,
39 Fixity, hsLTyVarLocNames, replaceTyVarName )
40 import RdrHsSyn ( extractHsTyRdrTyVars )
41 import RdrName ( RdrName, isQual, isUnqual, isOrig_maybe,
43 mkRdrUnqual, setRdrNameSpace, rdrNameOcc,
44 pprGlobalRdrEnv, lookupGRE_RdrName,
45 isExact_maybe, isSrcRdrName,
47 GlobalRdrElt(..), GlobalRdrEnv, lookupGlobalRdrEnv,
48 isLocalGRE, extendLocalRdrEnv, elemLocalRdrEnv, lookupLocalRdrEnv,
49 Provenance(..), pprNameProvenance,
50 importSpecLoc, importSpecModule
52 import HscTypes ( availNames, ModIface(..), FixItem(..), lookupFixity )
53 import TcEnv ( tcLookupDataCon )
55 import Name ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
56 nameSrcLoc, nameOccName, nameModule, isExternalName )
59 import DataCon ( dataConFieldLabels )
60 import OccName ( tcName, isDataOcc, pprNonVarNameSpace, occNameSpace,
62 import Module ( Module, ModuleName )
63 import PrelNames ( mkUnboundName, rOOT_MAIN, iNTERACTIVE, consDataConKey, hasKey )
65 import BasicTypes ( IPName, mapIPName )
66 import SrcLoc ( SrcSpan, srcSpanStart, Located(..), eqLocated, unLoc,
67 srcLocSpan, getLoc, combineSrcSpans, isOneLineSpan )
69 import Util ( sortLe )
71 import ListSetOps ( removeDups )
77 %*********************************************************
81 %*********************************************************
84 newTopSrcBinder :: Module -> Located RdrName -> RnM Name
85 newTopSrcBinder this_mod (L loc rdr_name)
86 | Just name <- isExact_maybe rdr_name
87 = -- This is here to catch
88 -- (a) Exact-name binders created by Template Haskell
89 -- (b) The PrelBase defn of (say) [] and similar, for which
90 -- the parser reads the special syntax and returns an Exact RdrName
91 -- We are at a binding site for the name, so check first that it
92 -- the current module is the correct one; otherwise GHC can get
93 -- very confused indeed. This test rejects code like
94 -- data T = (,) Int Int
95 -- unless we are in GHC.Tup
96 ASSERT2( isExternalName name, ppr name )
97 do { checkM (this_mod == nameModule name)
98 (addErrAt loc (badOrigBinding rdr_name))
102 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
103 = do { checkM (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
104 (addErrAt loc (badOrigBinding rdr_name))
105 -- When reading External Core we get Orig names as binders,
106 -- but they should agree with the module gotten from the monad
108 -- We can get built-in syntax showing up here too, sadly. If you type
110 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
111 -- uses setRdrNameSpace to make it into a data constructors. At that point
112 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
113 -- Hence the badOrigBinding error message.
115 -- Except for the ":Main.main = ..." definition inserted into
116 -- the Main module; ugh!
118 -- Because of this latter case, we call newGlobalBinder with a module from
119 -- the RdrName, not from the environment. In principle, it'd be fine to
120 -- have an arbitrary mixture of external core definitions in a single module,
121 -- (apart from module-initialisation issues, perhaps).
122 ; newGlobalBinder rdr_mod rdr_occ loc }
123 --TODO, should pass the whole span
126 = do { checkM (not (isQual rdr_name))
127 (addErrAt loc (badQualBndrErr rdr_name))
128 -- Binders should not be qualified; if they are, and with a different
129 -- module name, we we get a confusing "M.T is not in scope" error later
130 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
133 %*********************************************************
135 Source code occurrences
137 %*********************************************************
139 Looking up a name in the RnEnv.
142 lookupLocatedBndrRn :: Located RdrName -> RnM (Located Name)
143 lookupLocatedBndrRn = wrapLocM lookupBndrRn
145 lookupBndrRn :: RdrName -> RnM Name
146 -- NOTE: assumes that the SrcSpan of the binder has already been setSrcSpan'd
147 lookupBndrRn rdr_name
148 = getLocalRdrEnv `thenM` \ local_env ->
149 case lookupLocalRdrEnv local_env rdr_name of
150 Just name -> returnM name
151 Nothing -> lookupTopBndrRn rdr_name
153 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
154 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
156 lookupTopBndrRn :: RdrName -> RnM Name
157 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
158 -- and there may be several imported 'f's too, which must not confuse us.
159 -- For example, this is OK:
161 -- infix 9 f -- The 'f' here does not need to be qualified
162 -- f x = x -- Nor here, of course
163 -- So we have to filter out the non-local ones.
165 -- A separate function (importsFromLocalDecls) reports duplicate top level
166 -- decls, so here it's safe just to choose an arbitrary one.
168 -- There should never be a qualified name in a binding position in Haskell,
169 -- but there can be if we have read in an external-Core file.
170 -- The Haskell parser checks for the illegal qualified name in Haskell
171 -- source files, so we don't need to do so here.
173 lookupTopBndrRn rdr_name
174 | Just name <- isExact_maybe rdr_name
177 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
178 -- This deals with the case of derived bindings, where
179 -- we don't bother to call newTopSrcBinder first
180 -- We assume there is no "parent" name
181 = do { loc <- getSrcSpanM
182 ; newGlobalBinder rdr_mod rdr_occ loc }
185 = do { mb_gre <- lookupGreLocalRn rdr_name
188 traceRn $ text "lookupTopBndrRn"
190 Just gre -> returnM (gre_name gre) }
192 -- lookupLocatedSigOccRn is used for type signatures and pragmas
198 -- It's clear that the 'f' in the signature must refer to A.f
199 -- The Haskell98 report does not stipulate this, but it will!
200 -- So we must treat the 'f' in the signature in the same way
201 -- as the binding occurrence of 'f', using lookupBndrRn
203 -- However, consider this case:
207 -- We don't want to say 'f' is out of scope; instead, we want to
208 -- return the imported 'f', so that later on the reanamer will
209 -- correctly report "misplaced type sig".
210 lookupLocatedSigOccRn :: Located RdrName -> RnM (Located Name)
211 lookupLocatedSigOccRn = wrapLocM $ \ rdr_name -> do
212 { local_env <- getLocalRdrEnv
213 ; case lookupLocalRdrEnv local_env rdr_name of {
216 { mb_gre <- lookupGreLocalRn rdr_name
218 Just gre -> return (gre_name gre)
219 Nothing -> lookupGlobalOccRn rdr_name
222 -----------------------------------------------
223 lookupInstDeclBndr :: Name -> Located RdrName -> RnM (Located Name)
224 -- This is called on the method name on the left-hand side of an
225 -- instance declaration binding. eg. instance Functor T where
227 -- ^^^^ called on this
228 -- Regardless of how many unqualified fmaps are in scope, we want
229 -- the one that comes from the Functor class.
231 -- Furthermore, note that we take no account of whether the
232 -- name is only in scope qualified. I.e. even if method op is
233 -- in scope as M.op, we still allow plain 'op' on the LHS of
235 lookupInstDeclBndr cls rdr = lookup_located_sub_bndr is_op doc rdr
237 doc = ptext SLIT("method of class") <+> quotes (ppr cls)
238 is_op gre@(GRE {gre_par = ParentIs n}) = n == cls
241 -----------------------------------------------
242 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
243 -- Used for record construction and pattern matching
244 -- When the -fdisambiguate-record-fields flag is on, take account of the
245 -- constructor name to disambiguate which field to use; it's just the
246 -- same as for instance decls
247 lookupRecordBndr Nothing rdr_name
248 = lookupLocatedGlobalOccRn rdr_name
249 lookupRecordBndr (Just (L _ data_con)) rdr_name
250 = do { flag_on <- doptM Opt_DisambiguateRecordFields
252 then lookupLocatedGlobalOccRn rdr_name
254 fields <- lookupConstructorFields data_con
255 ; let is_field gre = gre_name gre `elem` fields
256 ; lookup_located_sub_bndr is_field doc rdr_name
259 doc = ptext SLIT("field of constructor") <+> quotes (ppr data_con)
262 lookupConstructorFields :: Name -> RnM [Name]
263 -- Look up the fields of a given constructor
264 -- * For constructors from this module, use the record field env,
265 -- which is itself gathered from the (as yet un-typechecked)
268 -- * For constructors from imported modules, use the *type* environment
269 -- since imported modles are already compiled, the info is conveniently
272 lookupConstructorFields con_name
273 = do { this_mod <- getModule
274 ; if nameIsLocalOrFrom this_mod con_name then
275 do { field_env <- getRecFieldEnv
276 ; return (lookupNameEnv field_env con_name `orElse` []) }
278 do { con <- tcLookupDataCon con_name
279 ; return (dataConFieldLabels con) } }
281 -----------------------------------------------
282 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
283 -> SDoc -> Located RdrName
284 -> RnM (Located Name)
285 lookup_located_sub_bndr is_good doc rdr_name
286 = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
288 lookup_sub_bndr is_good doc rdr_name
289 | isUnqual rdr_name -- Find all the things the rdr-name maps to
290 = do { -- and pick the one with the right parent name
291 ; env <- getGlobalRdrEnv
292 ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) of
293 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
294 -- The latter does pickGREs, but we want to allow 'x'
295 -- even if only 'M.x' is in scope
296 [gre] -> return (gre_name gre)
297 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
298 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
299 ; return (mkUnboundName rdr_name) }
300 gres -> do { addNameClashErrRn rdr_name gres
301 ; return (gre_name (head gres)) }
304 | otherwise -- Occurs in derived instances, where we just
305 -- refer directly to the right method
306 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
307 -- NB: qualified names are rejected by the parser
308 lookupImportedName rdr_name
310 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
311 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
313 -- Looking up family names in type instances is a subtle affair. The family
314 -- may be imported, in which case we need to lookup the occurence of a global
315 -- name. Alternatively, the family may be in the same binding group (and in
316 -- fact in a declaration processed later), and we need to create a new top
319 -- So, also this is strictly speaking an occurence, we cannot raise an error
320 -- message yet for instances without a family declaration. This will happen
321 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
323 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
324 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
325 = do { mb_gre <- lookupGreRn_maybe rdr_name
327 Just gre -> returnM (gre_name gre) ;
328 Nothing -> newTopSrcBinder mod lrdr_name }
330 --------------------------------------------------
332 --------------------------------------------------
334 getLookupOccRn :: RnM (Name -> Maybe Name)
336 = getLocalRdrEnv `thenM` \ local_env ->
337 return (lookupLocalRdrEnv local_env . mkRdrUnqual . nameOccName)
339 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
340 lookupLocatedOccRn = wrapLocM lookupOccRn
342 -- lookupOccRn looks up an occurrence of a RdrName
343 lookupOccRn :: RdrName -> RnM Name
345 = getLocalRdrEnv `thenM` \ local_env ->
346 case lookupLocalRdrEnv local_env rdr_name of
347 Just name -> returnM name
348 Nothing -> lookupGlobalOccRn rdr_name
350 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
351 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
353 lookupGlobalOccRn :: RdrName -> RnM Name
354 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
355 -- environment. It's used only for
356 -- record field names
357 -- class op names in class and instance decls
359 lookupGlobalOccRn rdr_name
360 | not (isSrcRdrName rdr_name)
361 = lookupImportedName rdr_name
364 = -- First look up the name in the normal environment.
365 lookupGreRn_maybe rdr_name `thenM` \ mb_gre ->
367 Just gre -> returnM (gre_name gre) ;
370 -- We allow qualified names on the command line to refer to
371 -- *any* name exported by any module in scope, just as if
372 -- there was an "import qualified M" declaration for every
374 getModule `thenM` \ mod ->
375 if isQual rdr_name && mod == iNTERACTIVE then
376 -- This test is not expensive,
377 lookupQualifiedName rdr_name -- and only happens for failed lookups
379 traceRn $ text "lookupGlobalOccRn"
380 unboundName rdr_name }
382 lookupImportedName :: RdrName -> TcRnIf m n Name
383 -- Lookup the occurrence of an imported name
384 -- The RdrName is *always* qualified or Exact
385 -- Treat it as an original name, and conjure up the Name
386 -- Usually it's Exact or Orig, but it can be Qual if it
387 -- comes from an hi-boot file. (This minor infelicity is
388 -- just to reduce duplication in the parser.)
389 lookupImportedName rdr_name
390 | Just n <- isExact_maybe rdr_name
391 -- This happens in derived code
394 -- Always Orig, even when reading a .hi-boot file
395 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
396 = lookupOrig rdr_mod rdr_occ
399 = pprPanic "RnEnv.lookupImportedName" (ppr rdr_name)
401 unboundName :: RdrName -> RnM Name
403 = do { addErr (unknownNameErr rdr_name)
404 ; env <- getGlobalRdrEnv;
405 ; traceRn (vcat [unknownNameErr rdr_name,
406 ptext SLIT("Global envt is:"),
407 nest 3 (pprGlobalRdrEnv env)])
408 ; returnM (mkUnboundName rdr_name) }
410 --------------------------------------------------
411 -- Lookup in the Global RdrEnv of the module
412 --------------------------------------------------
414 lookupSrcOcc_maybe :: RdrName -> RnM (Maybe Name)
415 -- No filter function; does not report an error on failure
416 lookupSrcOcc_maybe rdr_name
417 = do { mb_gre <- lookupGreRn_maybe rdr_name
419 Nothing -> returnM Nothing
420 Just gre -> returnM (Just (gre_name gre)) }
422 -------------------------
423 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
424 -- Just look up the RdrName in the GlobalRdrEnv
425 lookupGreRn_maybe rdr_name
426 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
428 lookupGreRn :: RdrName -> RnM GlobalRdrElt
429 -- If not found, add error message, and return a fake GRE
431 = do { mb_gre <- lookupGreRn_maybe rdr_name
433 Just gre -> return gre ;
435 { traceRn $ text "lookupGreRn"
436 ; name <- unboundName rdr_name
437 ; return (GRE { gre_name = name, gre_par = NoParent,
438 gre_prov = LocalDef }) }}}
440 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
441 -- Similar, but restricted to locally-defined things
442 lookupGreLocalRn rdr_name
443 = lookupGreRn_help rdr_name lookup_fn
445 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
447 lookupGreRn_help :: RdrName -- Only used in error message
448 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
449 -> RnM (Maybe GlobalRdrElt)
450 -- Checks for exactly one match; reports deprecations
451 -- Returns Nothing, without error, if too few
452 lookupGreRn_help rdr_name lookup
453 = do { env <- getGlobalRdrEnv
455 [] -> returnM Nothing
456 [gre] -> returnM (Just gre)
457 gres -> do { addNameClashErrRn rdr_name gres
458 ; returnM (Just (head gres)) } }
460 ------------------------------
462 ------------------------------
464 -- A qualified name on the command line can refer to any module at all: we
465 -- try to load the interface if we don't already have it.
466 lookupQualifiedName :: RdrName -> RnM Name
467 lookupQualifiedName rdr_name
468 | Just (mod,occ) <- isQual_maybe rdr_name
469 -- Note: we want to behave as we would for a source file import here,
470 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
471 = loadSrcInterface doc mod False `thenM` \ iface ->
474 (mod,avails) <- mi_exports iface,
476 name <- availNames avail,
478 ((mod,occ):ns) -> ASSERT (null ns)
480 _ -> unboundName rdr_name
483 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
485 doc = ptext SLIT("Need to find") <+> ppr rdr_name
488 %*********************************************************
492 %*********************************************************
495 lookupLocalDataTcNames :: RdrName -> RnM [Name]
496 -- GHC extension: look up both the tycon and data con
497 -- for con-like things
498 -- Complain if neither is in scope
499 lookupLocalDataTcNames rdr_name
500 | Just n <- isExact_maybe rdr_name
501 -- Special case for (:), which doesn't get into the GlobalRdrEnv
502 = return [n] -- For this we don't need to try the tycon too
504 = do { mb_gres <- mapM lookupGreLocalRn (dataTcOccs rdr_name)
505 ; case [gre_name gre | Just gre <- mb_gres] of
506 [] -> do { addErr (unknownNameErr rdr_name)
508 names -> return names
511 --------------------------------
512 bindLocalFixities :: [FixitySig RdrName] -> RnM a -> RnM a
513 -- Used for nested fixity decls
514 -- No need to worry about type constructors here,
515 -- Should check for duplicates but we don't
516 bindLocalFixities fixes thing_inside
517 | null fixes = thing_inside
518 | otherwise = mappM rn_sig fixes `thenM` \ new_bit ->
519 extendFixityEnv new_bit thing_inside
521 rn_sig (FixitySig lv@(L loc v) fix)
522 = addLocM lookupBndrRn lv `thenM` \ new_v ->
523 returnM (new_v, (FixItem (rdrNameOcc v) fix loc))
526 --------------------------------
527 lookupFixity is a bit strange.
529 * Nested local fixity decls are put in the local fixity env, which we
530 find with getFixtyEnv
532 * Imported fixities are found in the HIT or PIT
534 * Top-level fixity decls in this module may be for Names that are
535 either Global (constructors, class operations)
536 or Local/Exported (everything else)
537 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
538 We put them all in the local fixity environment
541 lookupFixityRn :: Name -> RnM Fixity
543 = getModule `thenM` \ this_mod ->
544 if nameIsLocalOrFrom this_mod name
545 then -- It's defined in this module
546 getFixityEnv `thenM` \ local_fix_env ->
547 traceRn (text "lookupFixityRn" <+> (ppr name $$ ppr local_fix_env)) `thenM_`
548 returnM (lookupFixity local_fix_env name)
550 else -- It's imported
551 -- For imported names, we have to get their fixities by doing a
552 -- loadInterfaceForName, and consulting the Ifaces that comes back
553 -- from that, because the interface file for the Name might not
554 -- have been loaded yet. Why not? Suppose you import module A,
555 -- which exports a function 'f', thus;
556 -- module CurrentModule where
558 -- module A( f ) where
560 -- Then B isn't loaded right away (after all, it's possible that
561 -- nothing from B will be used). When we come across a use of
562 -- 'f', we need to know its fixity, and it's then, and only
563 -- then, that we load B.hi. That is what's happening here.
565 -- loadInterfaceForName will find B.hi even if B is a hidden module,
566 -- and that's what we want.
567 loadInterfaceForName doc name `thenM` \ iface ->
568 returnM (mi_fix_fn iface (nameOccName name))
570 doc = ptext SLIT("Checking fixity for") <+> ppr name
573 lookupTyFixityRn :: Located Name -> RnM Fixity
574 lookupTyFixityRn (L loc n) = lookupFixityRn n
577 dataTcOccs :: RdrName -> [RdrName]
578 -- If the input is a data constructor, return both it and a type
579 -- constructor. This is useful when we aren't sure which we are
582 | Just n <- isExact_maybe rdr_name -- Ghastly special case
583 , n `hasKey` consDataConKey = [rdr_name] -- see note below
584 | isDataOcc occ = [rdr_name_tc, rdr_name]
585 | otherwise = [rdr_name]
587 occ = rdrNameOcc rdr_name
588 rdr_name_tc = setRdrNameSpace rdr_name tcName
590 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
591 -- and setRdrNameSpace generates an Orig, which is fine
592 -- But it's not fine for (:), because there *is* no corresponding type
593 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
594 -- appear to be in scope (because Orig's simply allocate a new name-cache
595 -- entry) and then we get an error when we use dataTcOccs in
596 -- TcRnDriver.tcRnGetInfo. Large sigh.
599 %************************************************************************
602 Dealing with rebindable syntax is driven by the
603 Opt_NoImplicitPrelude dynamic flag.
605 In "deriving" code we don't want to use rebindable syntax
606 so we switch off the flag locally
609 %************************************************************************
611 Haskell 98 says that when you say "3" you get the "fromInteger" from the
612 Standard Prelude, regardless of what is in scope. However, to experiment
613 with having a language that is less coupled to the standard prelude, we're
614 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
615 happens to be in scope. Then you can
617 import MyPrelude as Prelude
618 to get the desired effect.
620 At the moment this just happens for
621 * fromInteger, fromRational on literals (in expressions and patterns)
622 * negate (in expressions)
623 * minus (arising from n+k patterns)
626 We store the relevant Name in the HsSyn tree, in
627 * HsIntegral/HsFractional/HsIsString
631 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
632 fromRationalName etc), but the renamer changes this to the appropriate user
633 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
635 We treat the orignal (standard) names as free-vars too, because the type checker
636 checks the type of the user thing against the type of the standard thing.
639 lookupSyntaxName :: Name -- The standard name
640 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
641 lookupSyntaxName std_name
642 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
643 if implicit_prelude then normal_case
645 -- Get the similarly named thing from the local environment
646 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
647 returnM (HsVar usr_name, unitFV usr_name)
649 normal_case = returnM (HsVar std_name, emptyFVs)
651 lookupSyntaxTable :: [Name] -- Standard names
652 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
653 lookupSyntaxTable std_names
654 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
655 if implicit_prelude then normal_case
657 -- Get the similarly named thing from the local environment
658 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
660 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
662 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
666 %*********************************************************
670 %*********************************************************
673 newLocalsRn :: [Located RdrName] -> RnM [Name]
674 newLocalsRn rdr_names_w_loc
675 = newUniqueSupply `thenM` \ us ->
676 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
678 mk (L loc rdr_name) uniq
679 | Just name <- isExact_maybe rdr_name = name
680 -- This happens in code generated by Template Haskell
681 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
682 -- We only bind unqualified names here
683 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
684 mkInternalName uniq (rdrNameOcc rdr_name) loc
686 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
690 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
691 = -- Check for duplicate names
692 checkDupNames doc_str rdr_names_w_loc `thenM_`
694 -- Warn about shadowing, but only in source modules
695 ifOptM Opt_WarnNameShadowing
696 (checkShadowing doc_str rdr_names_w_loc) `thenM_`
698 -- Make fresh Names and extend the environment
699 newLocalsRn rdr_names_w_loc `thenM` \ names ->
700 getLocalRdrEnv `thenM` \ local_env ->
701 setLocalRdrEnv (extendLocalRdrEnv local_env names)
702 (enclosed_scope names)
705 bindLocalNames :: [Name] -> RnM a -> RnM a
706 bindLocalNames names enclosed_scope
707 = getLocalRdrEnv `thenM` \ name_env ->
708 setLocalRdrEnv (extendLocalRdrEnv name_env names)
711 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
712 bindLocalNamesFV names enclosed_scope
713 = do { (result, fvs) <- bindLocalNames names enclosed_scope
714 ; returnM (result, delListFromNameSet fvs names) }
717 -------------------------------------
718 -- binLocalsFVRn is the same as bindLocalsRn
719 -- except that it deals with free vars
720 bindLocatedLocalsFV :: SDoc -> [Located RdrName] -> ([Name] -> RnM (a,FreeVars))
722 bindLocatedLocalsFV doc rdr_names enclosed_scope
723 = bindLocatedLocalsRn doc rdr_names $ \ names ->
724 enclosed_scope names `thenM` \ (thing, fvs) ->
725 returnM (thing, delListFromNameSet fvs names)
727 -------------------------------------
728 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
729 -> ([LHsTyVarBndr Name] -> RnM a)
731 -- Haskell-98 binding of type variables; e.g. within a data type decl
732 bindTyVarsRn doc_str tyvar_names enclosed_scope
734 located_tyvars = hsLTyVarLocNames tyvar_names
736 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
737 enclosed_scope (zipWith replace tyvar_names names)
739 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
741 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
742 -- Find the type variables in the pattern type
743 -- signatures that must be brought into scope
744 bindPatSigTyVars tys thing_inside
745 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
746 ; if not scoped_tyvars then
749 do { name_env <- getLocalRdrEnv
750 ; let locd_tvs = [ tv | ty <- tys
751 , tv <- extractHsTyRdrTyVars ty
752 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
753 nubbed_tvs = nubBy eqLocated locd_tvs
754 -- The 'nub' is important. For example:
755 -- f (x :: t) (y :: t) = ....
756 -- We don't want to complain about binding t twice!
758 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
760 doc_sig = text "In a pattern type-signature"
762 bindPatSigTyVarsFV :: [LHsType RdrName]
765 bindPatSigTyVarsFV tys thing_inside
766 = bindPatSigTyVars tys $ \ tvs ->
767 thing_inside `thenM` \ (result,fvs) ->
768 returnM (result, fvs `delListFromNameSet` tvs)
770 bindSigTyVarsFV :: [Name]
773 bindSigTyVarsFV tvs thing_inside
774 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
775 ; if not scoped_tyvars then
778 bindLocalNamesFV tvs thing_inside }
780 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
781 -- This function is used only in rnSourceDecl on InstDecl
782 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
784 -------------------------------------
785 checkDupNames :: SDoc
788 checkDupNames doc_str rdr_names_w_loc
789 = -- Check for duplicated names in a binding group
790 mappM_ (dupNamesErr doc_str) dups
792 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
794 -------------------------------------
795 checkShadowing doc_str loc_rdr_names
796 = getLocalRdrEnv `thenM` \ local_env ->
797 getGlobalRdrEnv `thenM` \ global_env ->
799 check_shadow (L loc rdr_name)
800 | rdr_name `elemLocalRdrEnv` local_env
801 || not (null (lookupGRE_RdrName rdr_name global_env ))
802 = addWarnAt loc (shadowedNameWarn doc_str rdr_name)
803 | otherwise = returnM ()
805 mappM_ check_shadow loc_rdr_names
809 %************************************************************************
811 \subsection{Free variable manipulation}
813 %************************************************************************
817 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
819 (ys, fvs_s) = unzip stuff
821 returnM (ys, plusFVs fvs_s)
825 %************************************************************************
827 \subsection{Envt utility functions}
829 %************************************************************************
832 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
833 warnUnusedModules mods
834 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
836 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
837 mk_warn m = vcat [ptext SLIT("Module") <+> quotes (ppr m)
838 <+> text "is imported, but nothing from it is used,",
839 nest 2 (ptext SLIT("except perhaps instances visible in")
841 ptext SLIT("To suppress this warning, use:")
842 <+> ptext SLIT("import") <+> ppr m <> parens empty ]
845 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
846 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
847 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
849 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM ()
850 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds (warnUnusedLocals names)
851 warnUnusedMatches names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
853 -------------------------
856 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
858 warnUnusedLocals names
859 = warnUnusedBinds [(n,LocalDef) | n<-names]
861 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
862 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
863 where reportable (name,_)
864 | isWiredInName name = False -- Don't report unused wired-in names
865 -- Otherwise we get a zillion warnings
867 | otherwise = reportIfUnused (nameOccName name)
869 -------------------------
871 warnUnusedName :: (Name, Provenance) -> RnM ()
872 warnUnusedName (name, LocalDef)
873 = addUnusedWarning name (srcLocSpan (nameSrcLoc name))
874 (ptext SLIT("Defined but not used"))
876 warnUnusedName (name, Imported is)
879 warn spec = addUnusedWarning name span msg
881 span = importSpecLoc spec
882 pp_mod = quotes (ppr (importSpecModule spec))
883 msg = ptext SLIT("Imported from") <+> pp_mod <+> ptext SLIT("but not used")
885 addUnusedWarning name span msg
888 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
889 <+> quotes (ppr name)]
893 addNameClashErrRn rdr_name names
894 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
895 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
898 msg1 = ptext SLIT("either") <+> mk_ref np1
899 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
900 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
902 shadowedNameWarn doc shadow
903 = hsep [ptext SLIT("This binding for"),
905 ptext SLIT("shadows an existing binding")]
908 unknownNameErr rdr_name
909 = sep [ptext SLIT("Not in scope:"),
910 nest 2 $ pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
911 <+> quotes (ppr rdr_name)]
913 unknownSubordinateErr doc op -- Doc is "method of class" or
914 -- "field of constructor"
915 = quotes (ppr op) <+> ptext SLIT("is not a (visible)") <+> doc
918 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
919 -- The rdrNameOcc is because we don't want to print Prelude.(,)
921 dupNamesErr :: SDoc -> [Located RdrName] -> RnM ()
922 dupNamesErr descriptor located_names
924 vcat [ptext SLIT("Conflicting definitions for") <+> quotes (ppr name1),
925 locations, descriptor]
927 L _ name1 = head located_names
928 locs = map getLoc located_names
929 big_loc = foldr1 combineSrcSpans locs
930 one_line = isOneLineSpan big_loc
931 locations | one_line = empty
932 | otherwise = ptext SLIT("Bound at:") <+>
933 vcat (map ppr (sortLe (<=) locs))
935 badQualBndrErr rdr_name
936 = ptext SLIT("Qualified name in binding position:") <+> ppr rdr_name