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)
575 = do { glaExts <- doptM Opt_GlasgowExts
576 ; when (not glaExts) (addWarnAt loc (infixTyConWarn n))
580 dataTcOccs :: RdrName -> [RdrName]
581 -- If the input is a data constructor, return both it and a type
582 -- constructor. This is useful when we aren't sure which we are
585 | Just n <- isExact_maybe rdr_name -- Ghastly special case
586 , n `hasKey` consDataConKey = [rdr_name] -- see note below
587 | isDataOcc occ = [rdr_name_tc, rdr_name]
588 | otherwise = [rdr_name]
590 occ = rdrNameOcc rdr_name
591 rdr_name_tc = setRdrNameSpace rdr_name tcName
593 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
594 -- and setRdrNameSpace generates an Orig, which is fine
595 -- But it's not fine for (:), because there *is* no corresponding type
596 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
597 -- appear to be in scope (because Orig's simply allocate a new name-cache
598 -- entry) and then we get an error when we use dataTcOccs in
599 -- TcRnDriver.tcRnGetInfo. Large sigh.
602 %************************************************************************
605 Dealing with rebindable syntax is driven by the
606 Opt_NoImplicitPrelude dynamic flag.
608 In "deriving" code we don't want to use rebindable syntax
609 so we switch off the flag locally
612 %************************************************************************
614 Haskell 98 says that when you say "3" you get the "fromInteger" from the
615 Standard Prelude, regardless of what is in scope. However, to experiment
616 with having a language that is less coupled to the standard prelude, we're
617 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
618 happens to be in scope. Then you can
620 import MyPrelude as Prelude
621 to get the desired effect.
623 At the moment this just happens for
624 * fromInteger, fromRational on literals (in expressions and patterns)
625 * negate (in expressions)
626 * minus (arising from n+k patterns)
629 We store the relevant Name in the HsSyn tree, in
630 * HsIntegral/HsFractional/HsIsString
634 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
635 fromRationalName etc), but the renamer changes this to the appropriate user
636 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
638 We treat the orignal (standard) names as free-vars too, because the type checker
639 checks the type of the user thing against the type of the standard thing.
642 lookupSyntaxName :: Name -- The standard name
643 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
644 lookupSyntaxName std_name
645 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
646 if implicit_prelude then normal_case
648 -- Get the similarly named thing from the local environment
649 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
650 returnM (HsVar usr_name, unitFV usr_name)
652 normal_case = returnM (HsVar std_name, emptyFVs)
654 lookupSyntaxTable :: [Name] -- Standard names
655 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
656 lookupSyntaxTable std_names
657 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
658 if implicit_prelude then normal_case
660 -- Get the similarly named thing from the local environment
661 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
663 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
665 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
669 %*********************************************************
673 %*********************************************************
676 newLocalsRn :: [Located RdrName] -> RnM [Name]
677 newLocalsRn rdr_names_w_loc
678 = newUniqueSupply `thenM` \ us ->
679 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
681 mk (L loc rdr_name) uniq
682 | Just name <- isExact_maybe rdr_name = name
683 -- This happens in code generated by Template Haskell
684 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
685 -- We only bind unqualified names here
686 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
687 mkInternalName uniq (rdrNameOcc rdr_name) loc
689 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
693 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
694 = -- Check for duplicate names
695 checkDupNames doc_str rdr_names_w_loc `thenM_`
697 -- Warn about shadowing, but only in source modules
698 ifOptM Opt_WarnNameShadowing
699 (checkShadowing doc_str rdr_names_w_loc) `thenM_`
701 -- Make fresh Names and extend the environment
702 newLocalsRn rdr_names_w_loc `thenM` \ names ->
703 getLocalRdrEnv `thenM` \ local_env ->
704 setLocalRdrEnv (extendLocalRdrEnv local_env names)
705 (enclosed_scope names)
708 bindLocalNames :: [Name] -> RnM a -> RnM a
709 bindLocalNames names enclosed_scope
710 = getLocalRdrEnv `thenM` \ name_env ->
711 setLocalRdrEnv (extendLocalRdrEnv name_env names)
714 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
715 bindLocalNamesFV names enclosed_scope
716 = do { (result, fvs) <- bindLocalNames names enclosed_scope
717 ; returnM (result, delListFromNameSet fvs names) }
720 -------------------------------------
721 -- binLocalsFVRn is the same as bindLocalsRn
722 -- except that it deals with free vars
723 bindLocatedLocalsFV :: SDoc -> [Located RdrName] -> ([Name] -> RnM (a,FreeVars))
725 bindLocatedLocalsFV doc rdr_names enclosed_scope
726 = bindLocatedLocalsRn doc rdr_names $ \ names ->
727 enclosed_scope names `thenM` \ (thing, fvs) ->
728 returnM (thing, delListFromNameSet fvs names)
730 -------------------------------------
731 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
732 -> ([LHsTyVarBndr Name] -> RnM a)
734 -- Haskell-98 binding of type variables; e.g. within a data type decl
735 bindTyVarsRn doc_str tyvar_names enclosed_scope
737 located_tyvars = hsLTyVarLocNames tyvar_names
739 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
740 enclosed_scope (zipWith replace tyvar_names names)
742 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
744 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
745 -- Find the type variables in the pattern type
746 -- signatures that must be brought into scope
747 bindPatSigTyVars tys thing_inside
748 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
749 ; if not scoped_tyvars then
752 do { name_env <- getLocalRdrEnv
753 ; let locd_tvs = [ tv | ty <- tys
754 , tv <- extractHsTyRdrTyVars ty
755 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
756 nubbed_tvs = nubBy eqLocated locd_tvs
757 -- The 'nub' is important. For example:
758 -- f (x :: t) (y :: t) = ....
759 -- We don't want to complain about binding t twice!
761 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
763 doc_sig = text "In a pattern type-signature"
765 bindPatSigTyVarsFV :: [LHsType RdrName]
768 bindPatSigTyVarsFV tys thing_inside
769 = bindPatSigTyVars tys $ \ tvs ->
770 thing_inside `thenM` \ (result,fvs) ->
771 returnM (result, fvs `delListFromNameSet` tvs)
773 bindSigTyVarsFV :: [Name]
776 bindSigTyVarsFV tvs thing_inside
777 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
778 ; if not scoped_tyvars then
781 bindLocalNamesFV tvs thing_inside }
783 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
784 -- This function is used only in rnSourceDecl on InstDecl
785 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
787 -------------------------------------
788 checkDupNames :: SDoc
791 checkDupNames doc_str rdr_names_w_loc
792 = -- Check for duplicated names in a binding group
793 mappM_ (dupNamesErr doc_str) dups
795 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
797 -------------------------------------
798 checkShadowing doc_str loc_rdr_names
799 = getLocalRdrEnv `thenM` \ local_env ->
800 getGlobalRdrEnv `thenM` \ global_env ->
802 check_shadow (L loc rdr_name)
803 | rdr_name `elemLocalRdrEnv` local_env
804 || not (null (lookupGRE_RdrName rdr_name global_env ))
805 = addWarnAt loc (shadowedNameWarn doc_str rdr_name)
806 | otherwise = returnM ()
808 mappM_ check_shadow loc_rdr_names
812 %************************************************************************
814 \subsection{Free variable manipulation}
816 %************************************************************************
820 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
822 (ys, fvs_s) = unzip stuff
824 returnM (ys, plusFVs fvs_s)
828 %************************************************************************
830 \subsection{Envt utility functions}
832 %************************************************************************
835 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
836 warnUnusedModules mods
837 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
839 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
840 mk_warn m = vcat [ptext SLIT("Module") <+> quotes (ppr m)
841 <+> text "is imported, but nothing from it is used,",
842 nest 2 (ptext SLIT("except perhaps instances visible in")
844 ptext SLIT("To suppress this warning, use:")
845 <+> ptext SLIT("import") <+> ppr m <> parens empty ]
848 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
849 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
850 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
852 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM ()
853 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds (warnUnusedLocals names)
854 warnUnusedMatches names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
856 -------------------------
859 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
861 warnUnusedLocals names
862 = warnUnusedBinds [(n,LocalDef) | n<-names]
864 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
865 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
866 where reportable (name,_)
867 | isWiredInName name = False -- Don't report unused wired-in names
868 -- Otherwise we get a zillion warnings
870 | otherwise = reportIfUnused (nameOccName name)
872 -------------------------
874 warnUnusedName :: (Name, Provenance) -> RnM ()
875 warnUnusedName (name, LocalDef)
876 = addUnusedWarning name (srcLocSpan (nameSrcLoc name))
877 (ptext SLIT("Defined but not used"))
879 warnUnusedName (name, Imported is)
882 warn spec = addUnusedWarning name span msg
884 span = importSpecLoc spec
885 pp_mod = quotes (ppr (importSpecModule spec))
886 msg = ptext SLIT("Imported from") <+> pp_mod <+> ptext SLIT("but not used")
888 addUnusedWarning name span msg
891 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
892 <+> quotes (ppr name)]
896 addNameClashErrRn rdr_name names
897 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
898 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
901 msg1 = ptext SLIT("either") <+> mk_ref np1
902 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
903 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
905 shadowedNameWarn doc shadow
906 = hsep [ptext SLIT("This binding for"),
908 ptext SLIT("shadows an existing binding")]
911 unknownNameErr rdr_name
912 = sep [ptext SLIT("Not in scope:"),
913 nest 2 $ pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
914 <+> quotes (ppr rdr_name)]
916 unknownSubordinateErr doc op -- Doc is "method of class" or
917 -- "field of constructor"
918 = quotes (ppr op) <+> ptext SLIT("is not a (visible)") <+> doc
921 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
922 -- The rdrNameOcc is because we don't want to print Prelude.(,)
924 dupNamesErr :: SDoc -> [Located RdrName] -> RnM ()
925 dupNamesErr descriptor located_names
927 vcat [ptext SLIT("Conflicting definitions for") <+> quotes (ppr name1),
928 locations, descriptor]
930 L _ name1 = head located_names
931 locs = map getLoc located_names
932 big_loc = foldr1 combineSrcSpans locs
933 one_line = isOneLineSpan big_loc
934 locations | one_line = empty
935 | otherwise = ptext SLIT("Bound at:") <+>
936 vcat (map ppr (sortLe (<=) locs))
938 badQualBndrErr rdr_name
939 = ptext SLIT("Qualified name in binding position:") <+> ppr rdr_name
942 = vcat [ftext FSLIT("Accepting non-standard infix type constructor") <+> quotes (ppr op),
943 ftext FSLIT("Use -fglasgow-exts to avoid this warning")]