2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
4 \section[RnEnv]{Environment manipulation for the renamer monad}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 newTopSrcBinder, lookupFamInstDeclBndr,
16 lookupLocatedBndrRn, lookupBndrRn,
17 lookupLocatedTopBndrRn, lookupTopBndrRn,
18 lookupLocatedOccRn, lookupOccRn,
19 lookupLocatedGlobalOccRn, lookupGlobalOccRn,
20 lookupLocalDataTcNames, lookupSrcOcc_maybe,
21 lookupFixityRn, lookupTyFixityRn, lookupLocatedSigOccRn,
22 lookupInstDeclBndr, lookupRecordBndr, lookupConstructorFields,
23 lookupSyntaxName, lookupSyntaxTable, lookupImportedName,
24 lookupGreRn, lookupGreRn_maybe,
27 newLocalsRn, newIPNameRn,
28 bindLocalNames, bindLocalNamesFV,
29 bindLocatedLocalsFV, bindLocatedLocalsRn,
30 bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
31 bindTyVarsRn, extendTyVarEnvFVRn,
34 checkDupNames, mapFvRn,
35 warnUnusedMatches, warnUnusedModules, warnUnusedImports,
36 warnUnusedTopBinds, warnUnusedLocalBinds,
37 dataTcOccs, unknownNameErr,
40 #include "HsVersions.h"
42 import LoadIface ( loadInterfaceForName, loadSrcInterface )
43 import IfaceEnv ( lookupOrig, newGlobalBinder, newIPName )
44 import HsSyn ( FixitySig(..), HsExpr(..), SyntaxExpr, SyntaxTable,
45 LHsTyVarBndr, LHsType,
46 Fixity, hsLTyVarLocNames, replaceTyVarName )
47 import RdrHsSyn ( extractHsTyRdrTyVars )
48 import RdrName ( RdrName, isQual, isUnqual, isOrig_maybe,
50 mkRdrUnqual, setRdrNameSpace, rdrNameOcc,
51 pprGlobalRdrEnv, lookupGRE_RdrName,
52 isExact_maybe, isSrcRdrName,
54 GlobalRdrElt(..), GlobalRdrEnv, lookupGlobalRdrEnv,
55 isLocalGRE, extendLocalRdrEnv, elemLocalRdrEnv, lookupLocalRdrEnv,
56 Provenance(..), pprNameProvenance,
57 importSpecLoc, importSpecModule
59 import HscTypes ( availNames, ModIface(..), FixItem(..), lookupFixity )
60 import TcEnv ( tcLookupDataCon )
62 import Name ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
63 nameSrcLoc, nameOccName, nameModule, isExternalName )
66 import DataCon ( dataConFieldLabels )
67 import OccName ( tcName, isDataOcc, pprNonVarNameSpace, occNameSpace,
69 import Module ( Module, ModuleName )
70 import PrelNames ( mkUnboundName, rOOT_MAIN, iNTERACTIVE, consDataConKey, hasKey )
72 import BasicTypes ( IPName, mapIPName )
73 import SrcLoc ( SrcSpan, srcSpanStart, Located(..), eqLocated, unLoc,
74 srcLocSpan, getLoc, combineSrcSpans, isOneLineSpan )
76 import Util ( sortLe )
78 import ListSetOps ( removeDups )
84 %*********************************************************
88 %*********************************************************
91 newTopSrcBinder :: Module -> Located RdrName -> RnM Name
92 newTopSrcBinder this_mod (L loc rdr_name)
93 | Just name <- isExact_maybe rdr_name
94 = -- This is here to catch
95 -- (a) Exact-name binders created by Template Haskell
96 -- (b) The PrelBase defn of (say) [] and similar, for which
97 -- the parser reads the special syntax and returns an Exact RdrName
98 -- We are at a binding site for the name, so check first that it
99 -- the current module is the correct one; otherwise GHC can get
100 -- very confused indeed. This test rejects code like
101 -- data T = (,) Int Int
102 -- unless we are in GHC.Tup
103 ASSERT2( isExternalName name, ppr name )
104 do { checkM (this_mod == nameModule name)
105 (addErrAt loc (badOrigBinding rdr_name))
109 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
110 = do { checkM (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
111 (addErrAt loc (badOrigBinding rdr_name))
112 -- When reading External Core we get Orig names as binders,
113 -- but they should agree with the module gotten from the monad
115 -- We can get built-in syntax showing up here too, sadly. If you type
117 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
118 -- uses setRdrNameSpace to make it into a data constructors. At that point
119 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
120 -- Hence the badOrigBinding error message.
122 -- Except for the ":Main.main = ..." definition inserted into
123 -- the Main module; ugh!
125 -- Because of this latter case, we call newGlobalBinder with a module from
126 -- the RdrName, not from the environment. In principle, it'd be fine to
127 -- have an arbitrary mixture of external core definitions in a single module,
128 -- (apart from module-initialisation issues, perhaps).
129 ; newGlobalBinder rdr_mod rdr_occ loc }
130 --TODO, should pass the whole span
133 = do { checkM (not (isQual rdr_name))
134 (addErrAt loc (badQualBndrErr rdr_name))
135 -- Binders should not be qualified; if they are, and with a different
136 -- module name, we we get a confusing "M.T is not in scope" error later
137 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
140 %*********************************************************
142 Source code occurrences
144 %*********************************************************
146 Looking up a name in the RnEnv.
149 lookupLocatedBndrRn :: Located RdrName -> RnM (Located Name)
150 lookupLocatedBndrRn = wrapLocM lookupBndrRn
152 lookupBndrRn :: RdrName -> RnM Name
153 -- NOTE: assumes that the SrcSpan of the binder has already been setSrcSpan'd
154 lookupBndrRn rdr_name
155 = getLocalRdrEnv `thenM` \ local_env ->
156 case lookupLocalRdrEnv local_env rdr_name of
157 Just name -> returnM name
158 Nothing -> lookupTopBndrRn rdr_name
160 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
161 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
163 lookupTopBndrRn :: RdrName -> RnM Name
164 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
165 -- and there may be several imported 'f's too, which must not confuse us.
166 -- For example, this is OK:
168 -- infix 9 f -- The 'f' here does not need to be qualified
169 -- f x = x -- Nor here, of course
170 -- So we have to filter out the non-local ones.
172 -- A separate function (importsFromLocalDecls) reports duplicate top level
173 -- decls, so here it's safe just to choose an arbitrary one.
175 -- There should never be a qualified name in a binding position in Haskell,
176 -- but there can be if we have read in an external-Core file.
177 -- The Haskell parser checks for the illegal qualified name in Haskell
178 -- source files, so we don't need to do so here.
180 lookupTopBndrRn rdr_name
181 | Just name <- isExact_maybe rdr_name
184 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
185 -- This deals with the case of derived bindings, where
186 -- we don't bother to call newTopSrcBinder first
187 -- We assume there is no "parent" name
188 = do { loc <- getSrcSpanM
189 ; newGlobalBinder rdr_mod rdr_occ loc }
192 = do { mb_gre <- lookupGreLocalRn rdr_name
195 traceRn $ text "lookupTopBndrRn"
197 Just gre -> returnM (gre_name gre) }
199 -- lookupLocatedSigOccRn is used for type signatures and pragmas
205 -- It's clear that the 'f' in the signature must refer to A.f
206 -- The Haskell98 report does not stipulate this, but it will!
207 -- So we must treat the 'f' in the signature in the same way
208 -- as the binding occurrence of 'f', using lookupBndrRn
210 -- However, consider this case:
214 -- We don't want to say 'f' is out of scope; instead, we want to
215 -- return the imported 'f', so that later on the reanamer will
216 -- correctly report "misplaced type sig".
217 lookupLocatedSigOccRn :: Located RdrName -> RnM (Located Name)
218 lookupLocatedSigOccRn = wrapLocM $ \ rdr_name -> do
219 { local_env <- getLocalRdrEnv
220 ; case lookupLocalRdrEnv local_env rdr_name of {
223 { mb_gre <- lookupGreLocalRn rdr_name
225 Just gre -> return (gre_name gre)
226 Nothing -> lookupGlobalOccRn rdr_name
229 -----------------------------------------------
230 lookupInstDeclBndr :: Name -> Located RdrName -> RnM (Located Name)
231 -- This is called on the method name on the left-hand side of an
232 -- instance declaration binding. eg. instance Functor T where
234 -- ^^^^ called on this
235 -- Regardless of how many unqualified fmaps are in scope, we want
236 -- the one that comes from the Functor class.
238 -- Furthermore, note that we take no account of whether the
239 -- name is only in scope qualified. I.e. even if method op is
240 -- in scope as M.op, we still allow plain 'op' on the LHS of
242 lookupInstDeclBndr cls rdr = lookup_located_sub_bndr is_op doc rdr
244 doc = ptext SLIT("method of class") <+> quotes (ppr cls)
245 is_op gre@(GRE {gre_par = ParentIs n}) = n == cls
248 -----------------------------------------------
249 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
250 -- Used for record construction and pattern matching
251 -- When the -fdisambiguate-record-fields flag is on, take account of the
252 -- constructor name to disambiguate which field to use; it's just the
253 -- same as for instance decls
254 lookupRecordBndr Nothing rdr_name
255 = lookupLocatedGlobalOccRn rdr_name
256 lookupRecordBndr (Just (L _ data_con)) rdr_name
257 = do { flag_on <- doptM Opt_DisambiguateRecordFields
259 then lookupLocatedGlobalOccRn rdr_name
261 fields <- lookupConstructorFields data_con
262 ; let is_field gre = gre_name gre `elem` fields
263 ; lookup_located_sub_bndr is_field doc rdr_name
266 doc = ptext SLIT("field of constructor") <+> quotes (ppr data_con)
269 lookupConstructorFields :: Name -> RnM [Name]
270 -- Look up the fields of a given constructor
271 -- * For constructors from this module, use the record field env,
272 -- which is itself gathered from the (as yet un-typechecked)
275 -- * For constructors from imported modules, use the *type* environment
276 -- since imported modles are already compiled, the info is conveniently
279 lookupConstructorFields con_name
280 = do { this_mod <- getModule
281 ; if nameIsLocalOrFrom this_mod con_name then
282 do { field_env <- getRecFieldEnv
283 ; return (lookupNameEnv field_env con_name `orElse` []) }
285 do { con <- tcLookupDataCon con_name
286 ; return (dataConFieldLabels con) } }
288 -----------------------------------------------
289 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
290 -> SDoc -> Located RdrName
291 -> RnM (Located Name)
292 lookup_located_sub_bndr is_good doc rdr_name
293 = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
295 lookup_sub_bndr is_good doc rdr_name
296 | isUnqual rdr_name -- Find all the things the rdr-name maps to
297 = do { -- and pick the one with the right parent name
298 ; env <- getGlobalRdrEnv
299 ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) of
300 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
301 -- The latter does pickGREs, but we want to allow 'x'
302 -- even if only 'M.x' is in scope
303 [gre] -> return (gre_name gre)
304 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
305 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
306 ; return (mkUnboundName rdr_name) }
307 gres -> do { addNameClashErrRn rdr_name gres
308 ; return (gre_name (head gres)) }
311 | otherwise -- Occurs in derived instances, where we just
312 -- refer directly to the right method
313 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
314 -- NB: qualified names are rejected by the parser
315 lookupImportedName rdr_name
317 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
318 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
320 -- Looking up family names in type instances is a subtle affair. The family
321 -- may be imported, in which case we need to lookup the occurence of a global
322 -- name. Alternatively, the family may be in the same binding group (and in
323 -- fact in a declaration processed later), and we need to create a new top
326 -- So, also this is strictly speaking an occurence, we cannot raise an error
327 -- message yet for instances without a family declaration. This will happen
328 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
330 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
331 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
332 = do { mb_gre <- lookupGreRn_maybe rdr_name
334 Just gre -> returnM (gre_name gre) ;
335 Nothing -> newTopSrcBinder mod lrdr_name }
337 --------------------------------------------------
339 --------------------------------------------------
341 getLookupOccRn :: RnM (Name -> Maybe Name)
343 = getLocalRdrEnv `thenM` \ local_env ->
344 return (lookupLocalRdrEnv local_env . mkRdrUnqual . nameOccName)
346 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
347 lookupLocatedOccRn = wrapLocM lookupOccRn
349 -- lookupOccRn looks up an occurrence of a RdrName
350 lookupOccRn :: RdrName -> RnM Name
352 = getLocalRdrEnv `thenM` \ local_env ->
353 case lookupLocalRdrEnv local_env rdr_name of
354 Just name -> returnM name
355 Nothing -> lookupGlobalOccRn rdr_name
357 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
358 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
360 lookupGlobalOccRn :: RdrName -> RnM Name
361 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
362 -- environment. It's used only for
363 -- record field names
364 -- class op names in class and instance decls
366 lookupGlobalOccRn rdr_name
367 | not (isSrcRdrName rdr_name)
368 = lookupImportedName rdr_name
371 = -- First look up the name in the normal environment.
372 lookupGreRn_maybe rdr_name `thenM` \ mb_gre ->
374 Just gre -> returnM (gre_name gre) ;
377 -- We allow qualified names on the command line to refer to
378 -- *any* name exported by any module in scope, just as if
379 -- there was an "import qualified M" declaration for every
381 getModule `thenM` \ mod ->
382 if isQual rdr_name && mod == iNTERACTIVE then
383 -- This test is not expensive,
384 lookupQualifiedName rdr_name -- and only happens for failed lookups
386 traceRn $ text "lookupGlobalOccRn"
387 unboundName rdr_name }
389 lookupImportedName :: RdrName -> TcRnIf m n Name
390 -- Lookup the occurrence of an imported name
391 -- The RdrName is *always* qualified or Exact
392 -- Treat it as an original name, and conjure up the Name
393 -- Usually it's Exact or Orig, but it can be Qual if it
394 -- comes from an hi-boot file. (This minor infelicity is
395 -- just to reduce duplication in the parser.)
396 lookupImportedName rdr_name
397 | Just n <- isExact_maybe rdr_name
398 -- This happens in derived code
401 -- Always Orig, even when reading a .hi-boot file
402 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
403 = lookupOrig rdr_mod rdr_occ
406 = pprPanic "RnEnv.lookupImportedName" (ppr rdr_name)
408 unboundName :: RdrName -> RnM Name
410 = do { addErr (unknownNameErr rdr_name)
411 ; env <- getGlobalRdrEnv;
412 ; traceRn (vcat [unknownNameErr rdr_name,
413 ptext SLIT("Global envt is:"),
414 nest 3 (pprGlobalRdrEnv env)])
415 ; returnM (mkUnboundName rdr_name) }
417 --------------------------------------------------
418 -- Lookup in the Global RdrEnv of the module
419 --------------------------------------------------
421 lookupSrcOcc_maybe :: RdrName -> RnM (Maybe Name)
422 -- No filter function; does not report an error on failure
423 lookupSrcOcc_maybe rdr_name
424 = do { mb_gre <- lookupGreRn_maybe rdr_name
426 Nothing -> returnM Nothing
427 Just gre -> returnM (Just (gre_name gre)) }
429 -------------------------
430 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
431 -- Just look up the RdrName in the GlobalRdrEnv
432 lookupGreRn_maybe rdr_name
433 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
435 lookupGreRn :: RdrName -> RnM GlobalRdrElt
436 -- If not found, add error message, and return a fake GRE
438 = do { mb_gre <- lookupGreRn_maybe rdr_name
440 Just gre -> return gre ;
442 { traceRn $ text "lookupGreRn"
443 ; name <- unboundName rdr_name
444 ; return (GRE { gre_name = name, gre_par = NoParent,
445 gre_prov = LocalDef }) }}}
447 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
448 -- Similar, but restricted to locally-defined things
449 lookupGreLocalRn rdr_name
450 = lookupGreRn_help rdr_name lookup_fn
452 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
454 lookupGreRn_help :: RdrName -- Only used in error message
455 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
456 -> RnM (Maybe GlobalRdrElt)
457 -- Checks for exactly one match; reports deprecations
458 -- Returns Nothing, without error, if too few
459 lookupGreRn_help rdr_name lookup
460 = do { env <- getGlobalRdrEnv
462 [] -> returnM Nothing
463 [gre] -> returnM (Just gre)
464 gres -> do { addNameClashErrRn rdr_name gres
465 ; returnM (Just (head gres)) } }
467 ------------------------------
469 ------------------------------
471 -- A qualified name on the command line can refer to any module at all: we
472 -- try to load the interface if we don't already have it.
473 lookupQualifiedName :: RdrName -> RnM Name
474 lookupQualifiedName rdr_name
475 | Just (mod,occ) <- isQual_maybe rdr_name
476 -- Note: we want to behave as we would for a source file import here,
477 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
478 = loadSrcInterface doc mod False `thenM` \ iface ->
481 (mod,avails) <- mi_exports iface,
483 name <- availNames avail,
485 ((mod,occ):ns) -> ASSERT (null ns)
487 _ -> unboundName rdr_name
490 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
492 doc = ptext SLIT("Need to find") <+> ppr rdr_name
495 %*********************************************************
499 %*********************************************************
502 lookupLocalDataTcNames :: RdrName -> RnM [Name]
503 -- GHC extension: look up both the tycon and data con
504 -- for con-like things
505 -- Complain if neither is in scope
506 lookupLocalDataTcNames rdr_name
507 | Just n <- isExact_maybe rdr_name
508 -- Special case for (:), which doesn't get into the GlobalRdrEnv
509 = return [n] -- For this we don't need to try the tycon too
511 = do { mb_gres <- mapM lookupGreLocalRn (dataTcOccs rdr_name)
512 ; case [gre_name gre | Just gre <- mb_gres] of
513 [] -> do { addErr (unknownNameErr rdr_name)
515 names -> return names
518 --------------------------------
519 bindLocalFixities :: [FixitySig RdrName] -> RnM a -> RnM a
520 -- Used for nested fixity decls
521 -- No need to worry about type constructors here,
522 -- Should check for duplicates but we don't
523 bindLocalFixities fixes thing_inside
524 | null fixes = thing_inside
525 | otherwise = mappM rn_sig fixes `thenM` \ new_bit ->
526 extendFixityEnv new_bit thing_inside
528 rn_sig (FixitySig lv@(L loc v) fix)
529 = addLocM lookupBndrRn lv `thenM` \ new_v ->
530 returnM (new_v, (FixItem (rdrNameOcc v) fix loc))
533 --------------------------------
534 lookupFixity is a bit strange.
536 * Nested local fixity decls are put in the local fixity env, which we
537 find with getFixtyEnv
539 * Imported fixities are found in the HIT or PIT
541 * Top-level fixity decls in this module may be for Names that are
542 either Global (constructors, class operations)
543 or Local/Exported (everything else)
544 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
545 We put them all in the local fixity environment
548 lookupFixityRn :: Name -> RnM Fixity
550 = getModule `thenM` \ this_mod ->
551 if nameIsLocalOrFrom this_mod name
552 then -- It's defined in this module
553 getFixityEnv `thenM` \ local_fix_env ->
554 traceRn (text "lookupFixityRn" <+> (ppr name $$ ppr local_fix_env)) `thenM_`
555 returnM (lookupFixity local_fix_env name)
557 else -- It's imported
558 -- For imported names, we have to get their fixities by doing a
559 -- loadInterfaceForName, and consulting the Ifaces that comes back
560 -- from that, because the interface file for the Name might not
561 -- have been loaded yet. Why not? Suppose you import module A,
562 -- which exports a function 'f', thus;
563 -- module CurrentModule where
565 -- module A( f ) where
567 -- Then B isn't loaded right away (after all, it's possible that
568 -- nothing from B will be used). When we come across a use of
569 -- 'f', we need to know its fixity, and it's then, and only
570 -- then, that we load B.hi. That is what's happening here.
572 -- loadInterfaceForName will find B.hi even if B is a hidden module,
573 -- and that's what we want.
574 loadInterfaceForName doc name `thenM` \ iface ->
575 returnM (mi_fix_fn iface (nameOccName name))
577 doc = ptext SLIT("Checking fixity for") <+> ppr name
580 lookupTyFixityRn :: Located Name -> RnM Fixity
581 lookupTyFixityRn (L loc n) = lookupFixityRn n
584 dataTcOccs :: RdrName -> [RdrName]
585 -- If the input is a data constructor, return both it and a type
586 -- constructor. This is useful when we aren't sure which we are
589 | Just n <- isExact_maybe rdr_name -- Ghastly special case
590 , n `hasKey` consDataConKey = [rdr_name] -- see note below
591 | isDataOcc occ = [rdr_name_tc, rdr_name]
592 | otherwise = [rdr_name]
594 occ = rdrNameOcc rdr_name
595 rdr_name_tc = setRdrNameSpace rdr_name tcName
597 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
598 -- and setRdrNameSpace generates an Orig, which is fine
599 -- But it's not fine for (:), because there *is* no corresponding type
600 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
601 -- appear to be in scope (because Orig's simply allocate a new name-cache
602 -- entry) and then we get an error when we use dataTcOccs in
603 -- TcRnDriver.tcRnGetInfo. Large sigh.
606 %************************************************************************
609 Dealing with rebindable syntax is driven by the
610 Opt_NoImplicitPrelude dynamic flag.
612 In "deriving" code we don't want to use rebindable syntax
613 so we switch off the flag locally
616 %************************************************************************
618 Haskell 98 says that when you say "3" you get the "fromInteger" from the
619 Standard Prelude, regardless of what is in scope. However, to experiment
620 with having a language that is less coupled to the standard prelude, we're
621 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
622 happens to be in scope. Then you can
624 import MyPrelude as Prelude
625 to get the desired effect.
627 At the moment this just happens for
628 * fromInteger, fromRational on literals (in expressions and patterns)
629 * negate (in expressions)
630 * minus (arising from n+k patterns)
633 We store the relevant Name in the HsSyn tree, in
634 * HsIntegral/HsFractional/HsIsString
638 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
639 fromRationalName etc), but the renamer changes this to the appropriate user
640 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
642 We treat the orignal (standard) names as free-vars too, because the type checker
643 checks the type of the user thing against the type of the standard thing.
646 lookupSyntaxName :: Name -- The standard name
647 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
648 lookupSyntaxName std_name
649 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
650 if implicit_prelude then normal_case
652 -- Get the similarly named thing from the local environment
653 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
654 returnM (HsVar usr_name, unitFV usr_name)
656 normal_case = returnM (HsVar std_name, emptyFVs)
658 lookupSyntaxTable :: [Name] -- Standard names
659 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
660 lookupSyntaxTable std_names
661 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
662 if implicit_prelude then normal_case
664 -- Get the similarly named thing from the local environment
665 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
667 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
669 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
673 %*********************************************************
677 %*********************************************************
680 newLocalsRn :: [Located RdrName] -> RnM [Name]
681 newLocalsRn rdr_names_w_loc
682 = newUniqueSupply `thenM` \ us ->
683 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
685 mk (L loc rdr_name) uniq
686 | Just name <- isExact_maybe rdr_name = name
687 -- This happens in code generated by Template Haskell
688 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
689 -- We only bind unqualified names here
690 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
691 mkInternalName uniq (rdrNameOcc rdr_name) loc
693 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
697 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
698 = -- Check for duplicate names
699 checkDupNames doc_str rdr_names_w_loc `thenM_`
701 -- Warn about shadowing, but only in source modules
702 ifOptM Opt_WarnNameShadowing
703 (checkShadowing doc_str rdr_names_w_loc) `thenM_`
705 -- Make fresh Names and extend the environment
706 newLocalsRn rdr_names_w_loc `thenM` \ names ->
707 getLocalRdrEnv `thenM` \ local_env ->
708 setLocalRdrEnv (extendLocalRdrEnv local_env names)
709 (enclosed_scope names)
712 bindLocalNames :: [Name] -> RnM a -> RnM a
713 bindLocalNames names enclosed_scope
714 = getLocalRdrEnv `thenM` \ name_env ->
715 setLocalRdrEnv (extendLocalRdrEnv name_env names)
718 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
719 bindLocalNamesFV names enclosed_scope
720 = do { (result, fvs) <- bindLocalNames names enclosed_scope
721 ; returnM (result, delListFromNameSet fvs names) }
724 -------------------------------------
725 -- binLocalsFVRn is the same as bindLocalsRn
726 -- except that it deals with free vars
727 bindLocatedLocalsFV :: SDoc -> [Located RdrName] -> ([Name] -> RnM (a,FreeVars))
729 bindLocatedLocalsFV doc rdr_names enclosed_scope
730 = bindLocatedLocalsRn doc rdr_names $ \ names ->
731 enclosed_scope names `thenM` \ (thing, fvs) ->
732 returnM (thing, delListFromNameSet fvs names)
734 -------------------------------------
735 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
736 -> ([LHsTyVarBndr Name] -> RnM a)
738 -- Haskell-98 binding of type variables; e.g. within a data type decl
739 bindTyVarsRn doc_str tyvar_names enclosed_scope
741 located_tyvars = hsLTyVarLocNames tyvar_names
743 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
744 enclosed_scope (zipWith replace tyvar_names names)
746 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
748 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
749 -- Find the type variables in the pattern type
750 -- signatures that must be brought into scope
751 bindPatSigTyVars tys thing_inside
752 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
753 ; if not scoped_tyvars then
756 do { name_env <- getLocalRdrEnv
757 ; let locd_tvs = [ tv | ty <- tys
758 , tv <- extractHsTyRdrTyVars ty
759 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
760 nubbed_tvs = nubBy eqLocated locd_tvs
761 -- The 'nub' is important. For example:
762 -- f (x :: t) (y :: t) = ....
763 -- We don't want to complain about binding t twice!
765 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
767 doc_sig = text "In a pattern type-signature"
769 bindPatSigTyVarsFV :: [LHsType RdrName]
772 bindPatSigTyVarsFV tys thing_inside
773 = bindPatSigTyVars tys $ \ tvs ->
774 thing_inside `thenM` \ (result,fvs) ->
775 returnM (result, fvs `delListFromNameSet` tvs)
777 bindSigTyVarsFV :: [Name]
780 bindSigTyVarsFV tvs thing_inside
781 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
782 ; if not scoped_tyvars then
785 bindLocalNamesFV tvs thing_inside }
787 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
788 -- This function is used only in rnSourceDecl on InstDecl
789 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
791 -------------------------------------
792 checkDupNames :: SDoc
795 checkDupNames doc_str rdr_names_w_loc
796 = -- Check for duplicated names in a binding group
797 mappM_ (dupNamesErr doc_str) dups
799 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
801 -------------------------------------
802 checkShadowing doc_str loc_rdr_names
803 = getLocalRdrEnv `thenM` \ local_env ->
804 getGlobalRdrEnv `thenM` \ global_env ->
806 check_shadow (L loc rdr_name)
807 | rdr_name `elemLocalRdrEnv` local_env
808 || not (null (lookupGRE_RdrName rdr_name global_env ))
809 = addWarnAt loc (shadowedNameWarn doc_str rdr_name)
810 | otherwise = returnM ()
812 mappM_ check_shadow loc_rdr_names
816 %************************************************************************
818 \subsection{Free variable manipulation}
820 %************************************************************************
824 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
826 (ys, fvs_s) = unzip stuff
828 returnM (ys, plusFVs fvs_s)
832 %************************************************************************
834 \subsection{Envt utility functions}
836 %************************************************************************
839 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
840 warnUnusedModules mods
841 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
843 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
844 mk_warn m = vcat [ptext SLIT("Module") <+> quotes (ppr m)
845 <+> text "is imported, but nothing from it is used,",
846 nest 2 (ptext SLIT("except perhaps instances visible in")
848 ptext SLIT("To suppress this warning, use:")
849 <+> ptext SLIT("import") <+> ppr m <> parens empty ]
852 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
853 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
854 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
856 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM ()
857 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds (warnUnusedLocals names)
858 warnUnusedMatches names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
860 -------------------------
863 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
865 warnUnusedLocals names
866 = warnUnusedBinds [(n,LocalDef) | n<-names]
868 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
869 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
870 where reportable (name,_)
871 | isWiredInName name = False -- Don't report unused wired-in names
872 -- Otherwise we get a zillion warnings
874 | otherwise = reportIfUnused (nameOccName name)
876 -------------------------
878 warnUnusedName :: (Name, Provenance) -> RnM ()
879 warnUnusedName (name, LocalDef)
880 = addUnusedWarning name (srcLocSpan (nameSrcLoc name))
881 (ptext SLIT("Defined but not used"))
883 warnUnusedName (name, Imported is)
886 warn spec = addUnusedWarning name span msg
888 span = importSpecLoc spec
889 pp_mod = quotes (ppr (importSpecModule spec))
890 msg = ptext SLIT("Imported from") <+> pp_mod <+> ptext SLIT("but not used")
892 addUnusedWarning name span msg
895 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
896 <+> quotes (ppr name)]
900 addNameClashErrRn rdr_name names
901 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
902 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
905 msg1 = ptext SLIT("either") <+> mk_ref np1
906 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
907 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
909 shadowedNameWarn doc shadow
910 = hsep [ptext SLIT("This binding for"),
912 ptext SLIT("shadows an existing binding")]
915 unknownNameErr rdr_name
916 = sep [ptext SLIT("Not in scope:"),
917 nest 2 $ pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
918 <+> quotes (ppr rdr_name)]
920 unknownSubordinateErr doc op -- Doc is "method of class" or
921 -- "field of constructor"
922 = quotes (ppr op) <+> ptext SLIT("is not a (visible)") <+> doc
925 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
926 -- The rdrNameOcc is because we don't want to print Prelude.(,)
928 dupNamesErr :: SDoc -> [Located RdrName] -> RnM ()
929 dupNamesErr descriptor located_names
931 vcat [ptext SLIT("Conflicting definitions for") <+> quotes (ppr name1),
932 locations, descriptor]
934 L _ name1 = head located_names
935 locs = map getLoc located_names
936 big_loc = foldr1 combineSrcSpans locs
937 one_line = isOneLineSpan big_loc
938 locations | one_line = empty
939 | otherwise = ptext SLIT("Bound at:") <+>
940 vcat (map ppr (sortLe (<=) locs))
942 badQualBndrErr rdr_name
943 = ptext SLIT("Qualified name in binding position:") <+> ppr rdr_name