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
236 (ptext SLIT("method of class")) rdr
238 doc = ptext SLIT("method of class") <+> quotes (ppr cls)
239 is_op gre@(GRE {gre_par = ParentIs n}) = n == cls
242 -----------------------------------------------
243 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
244 -- Used for record construction and pattern matching
245 -- When the -fdisambiguate-record-fields flag is on, take account of the
246 -- constructor name to disambiguate which field to use; it's just the
247 -- same as for instance decls
248 lookupRecordBndr Nothing rdr_name
249 = lookupLocatedGlobalOccRn rdr_name
250 lookupRecordBndr (Just (L _ data_con)) rdr_name
251 = do { flag_on <- doptM Opt_DisambiguateRecordFields
253 then lookupLocatedGlobalOccRn rdr_name
255 fields <- lookupConstructorFields data_con
256 ; let is_field gre = gre_name gre `elem` fields
257 ; lookup_located_sub_bndr is_field doc rdr_name
260 doc = ptext SLIT("field of constructor") <+> quotes (ppr data_con)
263 lookupConstructorFields :: Name -> RnM [Name]
264 -- Look up the fields of a given constructor
265 -- * For constructors from this module, use the record field env,
266 -- which is itself gathered from the (as yet un-typechecked)
269 -- * For constructors from imported modules, use the *type* environment
270 -- since imported modles are already compiled, the info is conveniently
273 lookupConstructorFields con_name
274 = do { this_mod <- getModule
275 ; if nameIsLocalOrFrom this_mod con_name then
276 do { field_env <- getRecFieldEnv
277 ; return (lookupNameEnv field_env con_name `orElse` []) }
279 do { con <- tcLookupDataCon con_name
280 ; return (dataConFieldLabels con) } }
282 -----------------------------------------------
283 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
284 -> SDoc -> Located RdrName
285 -> RnM (Located Name)
286 lookup_located_sub_bndr is_good doc rdr_name
287 = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
289 lookup_sub_bndr is_good doc rdr_name
290 | isUnqual rdr_name -- Find all the things the rdr-name maps to
291 = do { -- and pick the one with the right parent name
292 ; env <- getGlobalRdrEnv
293 ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) of
294 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
295 -- The latter does pickGREs, but we want to allow 'x'
296 -- even if only 'M.x' is in scope
297 [gre] -> return (gre_name gre)
298 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
299 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
300 ; return (mkUnboundName rdr_name) }
301 gres -> do { addNameClashErrRn rdr_name gres
302 ; return (gre_name (head gres)) }
305 | otherwise -- Occurs in derived instances, where we just
306 -- refer directly to the right method
307 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
308 -- NB: qualified names are rejected by the parser
309 lookupImportedName rdr_name
311 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
312 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
314 -- Looking up family names in type instances is a subtle affair. The family
315 -- may be imported, in which case we need to lookup the occurence of a global
316 -- name. Alternatively, the family may be in the same binding group (and in
317 -- fact in a declaration processed later), and we need to create a new top
320 -- So, also this is strictly speaking an occurence, we cannot raise an error
321 -- message yet for instances without a family declaration. This will happen
322 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
324 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
325 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
326 = do { mb_gre <- lookupGreRn_maybe rdr_name
328 Just gre -> returnM (gre_name gre) ;
329 Nothing -> newTopSrcBinder mod lrdr_name }
331 --------------------------------------------------
333 --------------------------------------------------
335 getLookupOccRn :: RnM (Name -> Maybe Name)
337 = getLocalRdrEnv `thenM` \ local_env ->
338 return (lookupLocalRdrEnv local_env . mkRdrUnqual . nameOccName)
340 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
341 lookupLocatedOccRn = wrapLocM lookupOccRn
343 -- lookupOccRn looks up an occurrence of a RdrName
344 lookupOccRn :: RdrName -> RnM Name
346 = getLocalRdrEnv `thenM` \ local_env ->
347 case lookupLocalRdrEnv local_env rdr_name of
348 Just name -> returnM name
349 Nothing -> lookupGlobalOccRn rdr_name
351 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
352 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
354 lookupGlobalOccRn :: RdrName -> RnM Name
355 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
356 -- environment. It's used only for
357 -- record field names
358 -- class op names in class and instance decls
360 lookupGlobalOccRn rdr_name
361 | not (isSrcRdrName rdr_name)
362 = lookupImportedName rdr_name
365 = -- First look up the name in the normal environment.
366 lookupGreRn_maybe rdr_name `thenM` \ mb_gre ->
368 Just gre -> returnM (gre_name gre) ;
371 -- We allow qualified names on the command line to refer to
372 -- *any* name exported by any module in scope, just as if
373 -- there was an "import qualified M" declaration for every
375 getModule `thenM` \ mod ->
376 if isQual rdr_name && mod == iNTERACTIVE then
377 -- This test is not expensive,
378 lookupQualifiedName rdr_name -- and only happens for failed lookups
380 traceRn $ text "lookupGlobalOccRn"
381 unboundName rdr_name }
383 lookupImportedName :: RdrName -> TcRnIf m n Name
384 -- Lookup the occurrence of an imported name
385 -- The RdrName is *always* qualified or Exact
386 -- Treat it as an original name, and conjure up the Name
387 -- Usually it's Exact or Orig, but it can be Qual if it
388 -- comes from an hi-boot file. (This minor infelicity is
389 -- just to reduce duplication in the parser.)
390 lookupImportedName rdr_name
391 | Just n <- isExact_maybe rdr_name
392 -- This happens in derived code
395 -- Always Orig, even when reading a .hi-boot file
396 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
397 = lookupOrig rdr_mod rdr_occ
400 = pprPanic "RnEnv.lookupImportedName" (ppr rdr_name)
402 unboundName :: RdrName -> RnM Name
404 = do { addErr (unknownNameErr rdr_name)
405 ; env <- getGlobalRdrEnv;
406 ; traceRn (vcat [unknownNameErr rdr_name,
407 ptext SLIT("Global envt is:"),
408 nest 3 (pprGlobalRdrEnv env)])
409 ; returnM (mkUnboundName rdr_name) }
411 --------------------------------------------------
412 -- Lookup in the Global RdrEnv of the module
413 --------------------------------------------------
415 lookupSrcOcc_maybe :: RdrName -> RnM (Maybe Name)
416 -- No filter function; does not report an error on failure
417 lookupSrcOcc_maybe rdr_name
418 = do { mb_gre <- lookupGreRn_maybe rdr_name
420 Nothing -> returnM Nothing
421 Just gre -> returnM (Just (gre_name gre)) }
423 -------------------------
424 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
425 -- Just look up the RdrName in the GlobalRdrEnv
426 lookupGreRn_maybe rdr_name
427 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
429 lookupGreRn :: RdrName -> RnM GlobalRdrElt
430 -- If not found, add error message, and return a fake GRE
432 = do { mb_gre <- lookupGreRn_maybe rdr_name
434 Just gre -> return gre ;
436 { traceRn $ text "lookupGreRn"
437 ; name <- unboundName rdr_name
438 ; return (GRE { gre_name = name, gre_par = NoParent,
439 gre_prov = LocalDef }) }}}
441 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
442 -- Similar, but restricted to locally-defined things
443 lookupGreLocalRn rdr_name
444 = lookupGreRn_help rdr_name lookup_fn
446 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
448 lookupGreRn_help :: RdrName -- Only used in error message
449 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
450 -> RnM (Maybe GlobalRdrElt)
451 -- Checks for exactly one match; reports deprecations
452 -- Returns Nothing, without error, if too few
453 lookupGreRn_help rdr_name lookup
454 = do { env <- getGlobalRdrEnv
456 [] -> returnM Nothing
457 [gre] -> returnM (Just gre)
458 gres -> do { addNameClashErrRn rdr_name gres
459 ; returnM (Just (head gres)) } }
461 ------------------------------
463 ------------------------------
465 -- A qualified name on the command line can refer to any module at all: we
466 -- try to load the interface if we don't already have it.
467 lookupQualifiedName :: RdrName -> RnM Name
468 lookupQualifiedName rdr_name
469 | Just (mod,occ) <- isQual_maybe rdr_name
470 -- Note: we want to behave as we would for a source file import here,
471 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
472 = loadSrcInterface doc mod False `thenM` \ iface ->
475 (mod,avails) <- mi_exports iface,
477 name <- availNames avail,
479 ((mod,occ):ns) -> ASSERT (null ns)
481 _ -> unboundName rdr_name
484 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
486 doc = ptext SLIT("Need to find") <+> ppr rdr_name
489 %*********************************************************
493 %*********************************************************
496 lookupLocalDataTcNames :: RdrName -> RnM [Name]
497 -- GHC extension: look up both the tycon and data con
498 -- for con-like things
499 -- Complain if neither is in scope
500 lookupLocalDataTcNames rdr_name
501 | Just n <- isExact_maybe rdr_name
502 -- Special case for (:), which doesn't get into the GlobalRdrEnv
503 = return [n] -- For this we don't need to try the tycon too
505 = do { mb_gres <- mapM lookupGreLocalRn (dataTcOccs rdr_name)
506 ; case [gre_name gre | Just gre <- mb_gres] of
507 [] -> do { addErr (unknownNameErr rdr_name)
509 names -> return names
512 --------------------------------
513 bindLocalFixities :: [FixitySig RdrName] -> RnM a -> RnM a
514 -- Used for nested fixity decls
515 -- No need to worry about type constructors here,
516 -- Should check for duplicates but we don't
517 bindLocalFixities fixes thing_inside
518 | null fixes = thing_inside
519 | otherwise = mappM rn_sig fixes `thenM` \ new_bit ->
520 extendFixityEnv new_bit thing_inside
522 rn_sig (FixitySig lv@(L loc v) fix)
523 = addLocM lookupBndrRn lv `thenM` \ new_v ->
524 returnM (new_v, (FixItem (rdrNameOcc v) fix loc))
527 --------------------------------
528 lookupFixity is a bit strange.
530 * Nested local fixity decls are put in the local fixity env, which we
531 find with getFixtyEnv
533 * Imported fixities are found in the HIT or PIT
535 * Top-level fixity decls in this module may be for Names that are
536 either Global (constructors, class operations)
537 or Local/Exported (everything else)
538 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
539 We put them all in the local fixity environment
542 lookupFixityRn :: Name -> RnM Fixity
544 = getModule `thenM` \ this_mod ->
545 if nameIsLocalOrFrom this_mod name
546 then -- It's defined in this module
547 getFixityEnv `thenM` \ local_fix_env ->
548 traceRn (text "lookupFixityRn" <+> (ppr name $$ ppr local_fix_env)) `thenM_`
549 returnM (lookupFixity local_fix_env name)
551 else -- It's imported
552 -- For imported names, we have to get their fixities by doing a
553 -- loadInterfaceForName, and consulting the Ifaces that comes back
554 -- from that, because the interface file for the Name might not
555 -- have been loaded yet. Why not? Suppose you import module A,
556 -- which exports a function 'f', thus;
557 -- module CurrentModule where
559 -- module A( f ) where
561 -- Then B isn't loaded right away (after all, it's possible that
562 -- nothing from B will be used). When we come across a use of
563 -- 'f', we need to know its fixity, and it's then, and only
564 -- then, that we load B.hi. That is what's happening here.
566 -- loadInterfaceForName will find B.hi even if B is a hidden module,
567 -- and that's what we want.
568 loadInterfaceForName doc name `thenM` \ iface ->
569 returnM (mi_fix_fn iface (nameOccName name))
571 doc = ptext SLIT("Checking fixity for") <+> ppr name
574 lookupTyFixityRn :: Located Name -> RnM Fixity
575 lookupTyFixityRn (L loc n)
576 = do { glaExts <- doptM Opt_GlasgowExts
577 ; when (not glaExts) (addWarnAt loc (infixTyConWarn n))
581 dataTcOccs :: RdrName -> [RdrName]
582 -- If the input is a data constructor, return both it and a type
583 -- constructor. This is useful when we aren't sure which we are
586 | Just n <- isExact_maybe rdr_name -- Ghastly special case
587 , n `hasKey` consDataConKey = [rdr_name] -- see note below
588 | isDataOcc occ = [rdr_name_tc, rdr_name]
589 | otherwise = [rdr_name]
591 occ = rdrNameOcc rdr_name
592 rdr_name_tc = setRdrNameSpace rdr_name tcName
594 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
595 -- and setRdrNameSpace generates an Orig, which is fine
596 -- But it's not fine for (:), because there *is* no corresponding type
597 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
598 -- appear to be in scope (because Orig's simply allocate a new name-cache
599 -- entry) and then we get an error when we use dataTcOccs in
600 -- TcRnDriver.tcRnGetInfo. Large sigh.
603 %************************************************************************
606 Dealing with rebindable syntax is driven by the
607 Opt_NoImplicitPrelude dynamic flag.
609 In "deriving" code we don't want to use rebindable syntax
610 so we switch off the flag locally
613 %************************************************************************
615 Haskell 98 says that when you say "3" you get the "fromInteger" from the
616 Standard Prelude, regardless of what is in scope. However, to experiment
617 with having a language that is less coupled to the standard prelude, we're
618 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
619 happens to be in scope. Then you can
621 import MyPrelude as Prelude
622 to get the desired effect.
624 At the moment this just happens for
625 * fromInteger, fromRational on literals (in expressions and patterns)
626 * negate (in expressions)
627 * minus (arising from n+k patterns)
630 We store the relevant Name in the HsSyn tree, in
631 * HsIntegral/HsFractional/HsIsString
635 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
636 fromRationalName etc), but the renamer changes this to the appropriate user
637 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
639 We treat the orignal (standard) names as free-vars too, because the type checker
640 checks the type of the user thing against the type of the standard thing.
643 lookupSyntaxName :: Name -- The standard name
644 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
645 lookupSyntaxName std_name
646 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
647 if implicit_prelude then normal_case
649 -- Get the similarly named thing from the local environment
650 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
651 returnM (HsVar usr_name, unitFV usr_name)
653 normal_case = returnM (HsVar std_name, emptyFVs)
655 lookupSyntaxTable :: [Name] -- Standard names
656 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
657 lookupSyntaxTable std_names
658 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
659 if implicit_prelude then normal_case
661 -- Get the similarly named thing from the local environment
662 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
664 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
666 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
670 %*********************************************************
674 %*********************************************************
677 newLocalsRn :: [Located RdrName] -> RnM [Name]
678 newLocalsRn rdr_names_w_loc
679 = newUniqueSupply `thenM` \ us ->
680 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
682 mk (L loc rdr_name) uniq
683 | Just name <- isExact_maybe rdr_name = name
684 -- This happens in code generated by Template Haskell
685 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
686 -- We only bind unqualified names here
687 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
688 mkInternalName uniq (rdrNameOcc rdr_name) loc
690 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
694 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
695 = -- Check for duplicate names
696 checkDupNames doc_str rdr_names_w_loc `thenM_`
698 -- Warn about shadowing, but only in source modules
699 ifOptM Opt_WarnNameShadowing
700 (checkShadowing doc_str rdr_names_w_loc) `thenM_`
702 -- Make fresh Names and extend the environment
703 newLocalsRn rdr_names_w_loc `thenM` \ names ->
704 getLocalRdrEnv `thenM` \ local_env ->
705 setLocalRdrEnv (extendLocalRdrEnv local_env names)
706 (enclosed_scope names)
709 bindLocalNames :: [Name] -> RnM a -> RnM a
710 bindLocalNames names enclosed_scope
711 = getLocalRdrEnv `thenM` \ name_env ->
712 setLocalRdrEnv (extendLocalRdrEnv name_env names)
715 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
716 bindLocalNamesFV names enclosed_scope
717 = do { (result, fvs) <- bindLocalNames names enclosed_scope
718 ; returnM (result, delListFromNameSet fvs names) }
721 -------------------------------------
722 -- binLocalsFVRn is the same as bindLocalsRn
723 -- except that it deals with free vars
724 bindLocatedLocalsFV :: SDoc -> [Located RdrName] -> ([Name] -> RnM (a,FreeVars))
726 bindLocatedLocalsFV doc rdr_names enclosed_scope
727 = bindLocatedLocalsRn doc rdr_names $ \ names ->
728 enclosed_scope names `thenM` \ (thing, fvs) ->
729 returnM (thing, delListFromNameSet fvs names)
731 -------------------------------------
732 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
733 -> ([LHsTyVarBndr Name] -> RnM a)
735 -- Haskell-98 binding of type variables; e.g. within a data type decl
736 bindTyVarsRn doc_str tyvar_names enclosed_scope
738 located_tyvars = hsLTyVarLocNames tyvar_names
740 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
741 enclosed_scope (zipWith replace tyvar_names names)
743 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
745 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
746 -- Find the type variables in the pattern type
747 -- signatures that must be brought into scope
748 bindPatSigTyVars tys thing_inside
749 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
750 ; if not scoped_tyvars then
753 do { name_env <- getLocalRdrEnv
754 ; let locd_tvs = [ tv | ty <- tys
755 , tv <- extractHsTyRdrTyVars ty
756 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
757 nubbed_tvs = nubBy eqLocated locd_tvs
758 -- The 'nub' is important. For example:
759 -- f (x :: t) (y :: t) = ....
760 -- We don't want to complain about binding t twice!
762 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
764 doc_sig = text "In a pattern type-signature"
766 bindPatSigTyVarsFV :: [LHsType RdrName]
769 bindPatSigTyVarsFV tys thing_inside
770 = bindPatSigTyVars tys $ \ tvs ->
771 thing_inside `thenM` \ (result,fvs) ->
772 returnM (result, fvs `delListFromNameSet` tvs)
774 bindSigTyVarsFV :: [Name]
777 bindSigTyVarsFV tvs thing_inside
778 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
779 ; if not scoped_tyvars then
782 bindLocalNamesFV tvs thing_inside }
784 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
785 -- This function is used only in rnSourceDecl on InstDecl
786 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
788 -------------------------------------
789 checkDupNames :: SDoc
792 checkDupNames doc_str rdr_names_w_loc
793 = -- Check for duplicated names in a binding group
794 mappM_ (dupNamesErr doc_str) dups
796 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
798 -------------------------------------
799 checkShadowing doc_str loc_rdr_names
800 = getLocalRdrEnv `thenM` \ local_env ->
801 getGlobalRdrEnv `thenM` \ global_env ->
803 check_shadow (L loc rdr_name)
804 | rdr_name `elemLocalRdrEnv` local_env
805 || not (null (lookupGRE_RdrName rdr_name global_env ))
806 = addWarnAt loc (shadowedNameWarn doc_str rdr_name)
807 | otherwise = returnM ()
809 mappM_ check_shadow loc_rdr_names
813 %************************************************************************
815 \subsection{Free variable manipulation}
817 %************************************************************************
821 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
823 (ys, fvs_s) = unzip stuff
825 returnM (ys, plusFVs fvs_s)
829 %************************************************************************
831 \subsection{Envt utility functions}
833 %************************************************************************
836 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
837 warnUnusedModules mods
838 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
840 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
841 mk_warn m = vcat [ptext SLIT("Module") <+> quotes (ppr m)
842 <+> text "is imported, but nothing from it is used,",
843 nest 2 (ptext SLIT("except perhaps instances visible in")
845 ptext SLIT("To suppress this warning, use:")
846 <+> ptext SLIT("import") <+> ppr m <> parens empty ]
849 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
850 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
851 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
853 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM ()
854 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds (warnUnusedLocals names)
855 warnUnusedMatches names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
857 -------------------------
860 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
862 warnUnusedLocals names
863 = warnUnusedBinds [(n,LocalDef) | n<-names]
865 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
866 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
867 where reportable (name,_)
868 | isWiredInName name = False -- Don't report unused wired-in names
869 -- Otherwise we get a zillion warnings
871 | otherwise = reportIfUnused (nameOccName name)
873 -------------------------
875 warnUnusedName :: (Name, Provenance) -> RnM ()
876 warnUnusedName (name, LocalDef)
877 = addUnusedWarning name (srcLocSpan (nameSrcLoc name))
878 (ptext SLIT("Defined but not used"))
880 warnUnusedName (name, Imported is)
883 warn spec = addUnusedWarning name span msg
885 span = importSpecLoc spec
886 pp_mod = quotes (ppr (importSpecModule spec))
887 msg = ptext SLIT("Imported from") <+> pp_mod <+> ptext SLIT("but not used")
889 addUnusedWarning name span msg
892 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
893 <+> quotes (ppr name)]
897 addNameClashErrRn rdr_name names
898 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
899 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
902 msg1 = ptext SLIT("either") <+> mk_ref np1
903 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
904 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
906 shadowedNameWarn doc shadow
907 = hsep [ptext SLIT("This binding for"),
909 ptext SLIT("shadows an existing binding")]
912 unknownNameErr rdr_name
913 = sep [ptext SLIT("Not in scope:"),
914 nest 2 $ pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
915 <+> quotes (ppr rdr_name)]
917 unknownSubordinateErr doc op -- Doc is "method of class" or
918 -- "field of constructor"
919 = quotes (ppr op) <+> ptext SLIT("is not a (visible)") <+> doc
922 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
923 -- The rdrNameOcc is because we don't want to print Prelude.(,)
925 dupNamesErr :: SDoc -> [Located RdrName] -> RnM ()
926 dupNamesErr descriptor located_names
928 vcat [ptext SLIT("Conflicting definitions for") <+> quotes (ppr name1),
929 locations, descriptor]
931 L _ name1 = head located_names
932 locs = map getLoc located_names
933 big_loc = foldr1 combineSrcSpans locs
934 one_line = isOneLineSpan big_loc
935 locations | one_line = empty
936 | otherwise = ptext SLIT("Bound at:") <+>
937 vcat (map ppr (sortLe (<=) locs))
939 badQualBndrErr rdr_name
940 = ptext SLIT("Qualified name in binding position:") <+> ppr rdr_name
943 = vcat [ftext FSLIT("Accepting non-standard infix type constructor") <+> quotes (ppr op),
944 ftext FSLIT("Use -fglasgow-exts to avoid this warning")]