2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
4 \section[RnEnv]{Environment manipulation for the renamer monad}
8 newTopSrcBinder, lookupFamInstDeclBndr,
9 lookupLocatedTopBndrRn, lookupTopBndrRn,
10 lookupLocatedOccRn, lookupOccRn,
11 lookupLocatedGlobalOccRn,
12 lookupGlobalOccRn, lookupGlobalOccRn_maybe,
13 lookupLocalDataTcNames, lookupSigOccRn,
14 lookupFixityRn, lookupTyFixityRn,
15 lookupInstDeclBndr, lookupSubBndr, lookupConstructorFields,
16 lookupSyntaxName, lookupSyntaxTable,
17 lookupGreRn, lookupGreLocalRn, lookupGreRn_maybe,
18 getLookupOccRn, addUsedRdrNames,
20 newLocalBndrRn, newLocalBndrsRn, newIPNameRn,
21 bindLocalName, bindLocalNames, bindLocalNamesFV,
22 MiniFixityEnv, emptyFsEnv, extendFsEnv, lookupFsEnv,
24 bindLocatedLocalsFV, bindLocatedLocalsRn,
25 bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
26 bindTyVarsRn, bindTyVarsFV, extendTyVarEnvFVRn,
28 checkDupRdrNames, checkDupAndShadowedRdrNames,
29 checkDupNames, checkDupAndShadowedNames,
30 addFvRn, mapFvRn, mapMaybeFvRn, mapFvRnCPS,
32 warnUnusedTopBinds, warnUnusedLocalBinds,
33 dataTcOccs, unknownNameErr, kindSigErr, perhapsForallMsg
36 #include "HsVersions.h"
38 import LoadIface ( loadInterfaceForName, loadSrcInterface )
39 import IfaceEnv ( lookupOrig, newGlobalBinder, newIPName )
41 import RdrHsSyn ( extractHsTyRdrTyVars )
43 import HscTypes ( availNames, ModIface(..), FixItem(..), lookupFixity)
44 import TcEnv ( tcLookupDataCon, tcLookupField, isBrackStage )
46 import Id ( isRecordSelector )
47 import Name ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
48 nameSrcLoc, nameSrcSpan, nameOccName, nameModule, isExternalName )
52 import DataCon ( dataConFieldLabels )
54 import PrelNames ( mkUnboundName, rOOT_MAIN, iNTERACTIVE,
55 consDataConKey, forall_tv_RDR )
58 import ErrUtils ( Message )
63 import ListSetOps ( removeDups )
68 import qualified Data.Set as Set
73 thenM :: Monad a => a b -> (b -> a c) -> a c
77 %*********************************************************
81 %*********************************************************
84 newTopSrcBinder :: Located RdrName -> RnM Name
85 newTopSrcBinder (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 { this_mod <- getModule
98 ; unless (this_mod == nameModule name)
99 (addErrAt loc (badOrigBinding rdr_name))
103 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
104 = do { this_mod <- getModule
105 ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
106 (addErrAt loc (badOrigBinding rdr_name))
107 -- When reading External Core we get Orig names as binders,
108 -- but they should agree with the module gotten from the monad
110 -- We can get built-in syntax showing up here too, sadly. If you type
112 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
113 -- uses setRdrNameSpace to make it into a data constructors. At that point
114 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
115 -- Hence the badOrigBinding error message.
117 -- Except for the ":Main.main = ..." definition inserted into
118 -- the Main module; ugh!
120 -- Because of this latter case, we call newGlobalBinder with a module from
121 -- the RdrName, not from the environment. In principle, it'd be fine to
122 -- have an arbitrary mixture of external core definitions in a single module,
123 -- (apart from module-initialisation issues, perhaps).
124 ; newGlobalBinder rdr_mod rdr_occ loc }
125 --TODO, should pass the whole span
128 = do { unless (not (isQual rdr_name))
129 (addErrAt loc (badQualBndrErr rdr_name))
130 -- Binders should not be qualified; if they are, and with a different
131 -- module name, we we get a confusing "M.T is not in scope" error later
134 ; if isBrackStage stage then
135 -- We are inside a TH bracket, so make an *Internal* name
136 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
137 do { uniq <- newUnique
138 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
141 do { this_mod <- getModule
142 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } }
145 %*********************************************************
147 Source code occurrences
149 %*********************************************************
151 Looking up a name in the RnEnv.
153 Note [Type and class operator definitions]
154 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
155 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
157 class a :*: b where ...
158 data (:*:) a b = ....
159 class (:*:) a b where ...
160 The latter two mean that we are not just looking for a
161 *syntactically-infix* declaration, but one that uses an operator
162 OccName. We use OccName.isSymOcc to detect that case, which isn't
163 terribly efficient, but there seems to be no better way.
166 lookupTopBndrRn :: RdrName -> RnM Name
167 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
170 Nothing -> do traceRn $ text "lookupTopBndrRn"
173 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
174 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
176 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
177 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
178 -- and there may be several imported 'f's too, which must not confuse us.
179 -- For example, this is OK:
181 -- infix 9 f -- The 'f' here does not need to be qualified
182 -- f x = x -- Nor here, of course
183 -- So we have to filter out the non-local ones.
185 -- A separate function (importsFromLocalDecls) reports duplicate top level
186 -- decls, so here it's safe just to choose an arbitrary one.
188 -- There should never be a qualified name in a binding position in Haskell,
189 -- but there can be if we have read in an external-Core file.
190 -- The Haskell parser checks for the illegal qualified name in Haskell
191 -- source files, so we don't need to do so here.
193 lookupTopBndrRn_maybe rdr_name
194 | Just name <- isExact_maybe rdr_name
197 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
198 -- This deals with the case of derived bindings, where
199 -- we don't bother to call newTopSrcBinder first
200 -- We assume there is no "parent" name
201 = do { loc <- getSrcSpanM
202 ; n <- newGlobalBinder rdr_mod rdr_occ loc
206 = do { -- Check for operators in type or class declarations
207 -- See Note [Type and class operator definitions]
208 let occ = rdrNameOcc rdr_name
209 ; when (isTcOcc occ && isSymOcc occ)
210 (do { op_ok <- xoptM Opt_TypeOperators
211 ; unless op_ok (addErr (opDeclErr rdr_name)) })
213 ; mb_gre <- lookupGreLocalRn rdr_name
215 Nothing -> return Nothing
216 Just gre -> return (Just $ gre_name gre) }
219 -----------------------------------------------
220 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
221 -- This is called on the method name on the left-hand side of an
222 -- instance declaration binding. eg. instance Functor T where
224 -- ^^^^ called on this
225 -- Regardless of how many unqualified fmaps are in scope, we want
226 -- the one that comes from the Functor class.
228 -- Furthermore, note that we take no account of whether the
229 -- name is only in scope qualified. I.e. even if method op is
230 -- in scope as M.op, we still allow plain 'op' on the LHS of
232 lookupInstDeclBndr cls rdr
233 = do { when (isQual rdr)
234 (addErr (badQualBndrErr rdr))
235 -- In an instance decl you aren't allowed
236 -- to use a qualified name for the method
237 -- (Although it'd make perfect sense.)
238 ; lookupSubBndr (ParentIs cls) doc rdr }
240 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
242 -----------------------------------------------
243 lookupConstructorFields :: Name -> RnM [Name]
244 -- Look up the fields of a given constructor
245 -- * For constructors from this module, use the record field env,
246 -- which is itself gathered from the (as yet un-typechecked)
249 -- * For constructors from imported modules, use the *type* environment
250 -- since imported modles are already compiled, the info is conveniently
253 lookupConstructorFields con_name
254 = do { this_mod <- getModule
255 ; if nameIsLocalOrFrom this_mod con_name then
256 do { RecFields field_env _ <- getRecFieldEnv
257 ; return (lookupNameEnv field_env con_name `orElse` []) }
259 do { con <- tcLookupDataCon con_name
260 ; return (dataConFieldLabels con) } }
262 -----------------------------------------------
263 -- Used for record construction and pattern matching
264 -- When the -XDisambiguateRecordFields flag is on, take account of the
265 -- constructor name to disambiguate which field to use; it's just the
266 -- same as for instance decls
268 -- NB: Consider this:
269 -- module Foo where { data R = R { fld :: Int } }
270 -- module Odd where { import Foo; fld x = x { fld = 3 } }
271 -- Arguably this should work, because the reference to 'fld' is
272 -- unambiguous because there is only one field id 'fld' in scope.
273 -- But currently it's rejected.
275 lookupSubBndr :: Parent -- NoParent => just look it up as usual
276 -- ParentIs p => use p to disambiguate
279 lookupSubBndr parent doc rdr_name
280 | Just n <- isExact_maybe rdr_name -- This happens in derived code
283 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
284 = lookupOrig rdr_mod rdr_occ
286 | otherwise -- Find all the things the rdr-name maps to
287 = do { -- and pick the one with the right parent name
288 ; env <- getGlobalRdrEnv
289 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
290 ; case pick parent gres of
291 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
292 -- The latter does pickGREs, but we want to allow 'x'
293 -- even if only 'M.x' is in scope
294 [gre] -> do { addUsedRdrNames (used_rdr_names gre)
295 ; return (gre_name gre) }
296 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
297 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> (ppr rdr_name $$ ppr gres))
298 ; return (mkUnboundName rdr_name) }
299 gres -> do { addNameClashErrRn rdr_name gres
300 ; return (gre_name (head gres)) } }
302 pick NoParent gres -- Normal lookup
303 = pickGREs rdr_name gres
304 pick (ParentIs p) gres -- Disambiguating lookup
305 | isUnqual rdr_name = filter (right_parent p) gres
306 | otherwise = filter (right_parent p) (pickGREs rdr_name gres)
308 right_parent p (GRE { gre_par = ParentIs p' }) = p==p'
309 right_parent _ _ = False
311 -- Note [Usage for sub-bndrs]
313 | isQual rdr_name = [rdr_name]
314 | otherwise = case gre_prov gre of
315 LocalDef -> [rdr_name]
316 Imported is -> map mk_qual_rdr is
317 mk_qual_rdr imp_spec = mkRdrQual (is_as (is_decl imp_spec)) rdr_occ
318 rdr_occ = rdrNameOcc rdr_name
320 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
321 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
323 -- If the family is declared locally, it will not yet be in the main
324 -- environment; hence, we pass in an extra one here, which we check first.
325 -- See "Note [Looking up family names in family instances]" in 'RnNames'.
327 lookupFamInstDeclBndr :: GlobalRdrEnv -> Located RdrName -> RnM Name
328 lookupFamInstDeclBndr tyclGroupEnv (L loc rdr_name)
330 case lookupGRE_RdrName rdr_name tyclGroupEnv of
331 (gre:_) -> return $ gre_name gre
332 -- if there is more than one, an error will be raised elsewhere
333 [] -> lookupOccRn rdr_name
336 Note [Usage for sub-bndrs]
337 ~~~~~~~~~~~~~~~~~~~~~~~~~~
339 import qualified M( C( f ) )
342 then is the qualified import M.f used? Obviously yes.
343 But the RdrName used in the instance decl is unqualified. In effect,
344 we fill in the qualification by looking for f's whose class is M.C
345 But when adding to the UsedRdrNames we must make that qualification
346 explicit, otherwise we get "Redundant import of M.C".
348 --------------------------------------------------
350 --------------------------------------------------
353 getLookupOccRn :: RnM (Name -> Maybe Name)
355 = getLocalRdrEnv `thenM` \ local_env ->
356 return (lookupLocalRdrOcc local_env . nameOccName)
358 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
359 lookupLocatedOccRn = wrapLocM lookupOccRn
361 -- lookupOccRn looks up an occurrence of a RdrName
362 lookupOccRn :: RdrName -> RnM Name
364 = getLocalRdrEnv `thenM` \ local_env ->
365 case lookupLocalRdrEnv local_env rdr_name of
366 Just name -> return name
367 Nothing -> lookupGlobalOccRn rdr_name
369 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
370 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
372 lookupGlobalOccRn :: RdrName -> RnM Name
373 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
374 -- environment. Adds an error message if the RdrName is not in scope.
375 -- Also has a special case for GHCi.
377 lookupGlobalOccRn rdr_name
378 = do { -- First look up the name in the normal environment.
379 mb_name <- lookupGlobalOccRn_maybe rdr_name
384 { -- We allow qualified names on the command line to refer to
385 -- *any* name exported by any module in scope, just as if there
386 -- was an "import qualified M" declaration for every module.
387 allow_qual <- doptM Opt_ImplicitImportQualified
389 -- This test is not expensive,
390 -- and only happens for failed lookups
391 ; if isQual rdr_name && allow_qual && mod == iNTERACTIVE
392 then lookupQualifiedName rdr_name
393 else unboundName rdr_name } } }
395 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
396 -- No filter function; does not report an error on failure
398 lookupGlobalOccRn_maybe rdr_name
399 | Just n <- isExact_maybe rdr_name -- This happens in derived code
402 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
403 = do { n <- lookupOrig rdr_mod rdr_occ; return (Just n) }
406 = do { mb_gre <- lookupGreRn_maybe rdr_name
408 Nothing -> return Nothing
409 Just gre -> return (Just (gre_name gre)) }
412 unboundName :: RdrName -> RnM Name
414 = do { addErr (unknownNameErr rdr_name)
415 ; env <- getGlobalRdrEnv;
416 ; traceRn (vcat [unknownNameErr rdr_name,
417 ptext (sLit "Global envt is:"),
418 nest 3 (pprGlobalRdrEnv env)])
419 ; return (mkUnboundName rdr_name) }
421 --------------------------------------------------
422 -- Lookup in the Global RdrEnv of the module
423 --------------------------------------------------
425 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
426 -- Just look up the RdrName in the GlobalRdrEnv
427 lookupGreRn_maybe rdr_name
428 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
430 lookupGreRn :: RdrName -> RnM GlobalRdrElt
431 -- If not found, add error message, and return a fake GRE
433 = do { mb_gre <- lookupGreRn_maybe rdr_name
435 Just gre -> return gre ;
437 { traceRn $ text "lookupGreRn"
438 ; name <- unboundName rdr_name
439 ; return (GRE { gre_name = name, gre_par = NoParent,
440 gre_prov = LocalDef }) }}}
442 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
443 -- Similar, but restricted to locally-defined things
444 lookupGreLocalRn rdr_name
445 = lookupGreRn_help rdr_name lookup_fn
447 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
449 lookupGreRn_help :: RdrName -- Only used in error message
450 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
451 -> RnM (Maybe GlobalRdrElt)
452 -- Checks for exactly one match; reports deprecations
453 -- Returns Nothing, without error, if too few
454 lookupGreRn_help rdr_name lookup
455 = do { env <- getGlobalRdrEnv
458 [gre] -> do { addUsedRdrName gre rdr_name
459 ; return (Just gre) }
460 gres -> do { addNameClashErrRn rdr_name gres
461 ; return (Just (head gres)) } }
463 addUsedRdrName :: GlobalRdrElt -> RdrName -> RnM ()
464 -- Record usage of imported RdrNames
465 addUsedRdrName gre rdr
466 | isLocalGRE gre = return ()
467 | otherwise = do { env <- getGblEnv
468 ; updMutVar (tcg_used_rdrnames env)
469 (\s -> Set.insert rdr s) }
471 addUsedRdrNames :: [RdrName] -> RnM ()
472 -- Record used sub-binders
473 -- We don't check for imported-ness here, because it's inconvenient
474 -- and not stritly necessary.
476 = do { env <- getGblEnv
477 ; updMutVar (tcg_used_rdrnames env)
478 (\s -> foldr Set.insert s rdrs) }
480 ------------------------------
482 ------------------------------
484 -- A qualified name on the command line can refer to any module at all: we
485 -- try to load the interface if we don't already have it.
486 lookupQualifiedName :: RdrName -> RnM Name
487 lookupQualifiedName rdr_name
488 | Just (mod,occ) <- isQual_maybe rdr_name
489 -- Note: we want to behave as we would for a source file import here,
490 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
491 = loadSrcInterface doc mod False Nothing `thenM` \ iface ->
494 (mod,avails) <- mi_exports iface,
496 name <- availNames avail,
498 ((mod,occ):ns) -> ASSERT (null ns)
500 _ -> unboundName rdr_name
503 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
505 doc = ptext (sLit "Need to find") <+> ppr rdr_name
508 lookupSigOccRn is used for type signatures and pragmas
514 It's clear that the 'f' in the signature must refer to A.f
515 The Haskell98 report does not stipulate this, but it will!
516 So we must treat the 'f' in the signature in the same way
517 as the binding occurrence of 'f', using lookupBndrRn
519 However, consider this case:
523 We don't want to say 'f' is out of scope; instead, we want to
524 return the imported 'f', so that later on the reanamer will
525 correctly report "misplaced type sig".
528 lookupSigOccRn :: Maybe NameSet -- Just ns => source file; these are the binders
530 -- Nothing => hs-boot file; signatures without
531 -- binders are expected
533 -> Located RdrName -> RnM (Located Name)
534 lookupSigOccRn mb_bound_names sig
535 = wrapLocM $ \ rdr_name ->
536 do { mb_name <- lookupBindGroupOcc mb_bound_names (hsSigDoc sig) rdr_name
538 Left err -> do { addErr err; return (mkUnboundName rdr_name) }
539 Right name -> return name }
541 lookupBindGroupOcc :: Maybe NameSet -- Just ns => source file; these are the binders
543 -- Nothing => hs-boot file; signatures without
544 -- binders are expected
546 -> RdrName -> RnM (Either Message Name)
547 -- Looks up the RdrName, expecting it to resolve to one of the
548 -- bound names passed in. If not, return an appropriate error message
549 lookupBindGroupOcc mb_bound_names what rdr_name
550 = do { local_env <- getLocalRdrEnv
551 ; case lookupLocalRdrEnv local_env rdr_name of
552 Just n -> check_local_name n
553 Nothing -> do -- Not defined in a nested scope
555 { env <- getGlobalRdrEnv
556 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
557 ; case (filter isLocalGRE gres) of
558 (gre:_) -> check_local_name (gre_name gre)
559 -- If there is more than one local GRE for the
560 -- same OccName, that will be reported separately
561 [] | null gres -> bale_out_with empty
562 | otherwise -> bale_out_with import_msg
565 check_local_name name -- The name is in scope, and not imported
566 = case mb_bound_names of
567 Just bound_names | not (name `elemNameSet` bound_names)
568 -> bale_out_with local_msg
569 _other -> return (Right name)
572 = return (Left (sep [ ptext (sLit "The") <+> what
573 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
574 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
577 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
578 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
580 import_msg = parens $ ptext (sLit "You cannot give a") <+> what
581 <+> ptext (sLit "for an imported value")
584 lookupLocalDataTcNames :: NameSet -> SDoc -> RdrName -> RnM [Name]
585 -- GHC extension: look up both the tycon and data con
586 -- for con-like things
587 -- Complain if neither is in scope
588 lookupLocalDataTcNames bound_names what rdr_name
589 | Just n <- isExact_maybe rdr_name
590 -- Special case for (:), which doesn't get into the GlobalRdrEnv
591 = return [n] -- For this we don't need to try the tycon too
593 = do { mb_gres <- mapM (lookupBindGroupOcc (Just bound_names) what)
594 (dataTcOccs rdr_name)
595 ; let (errs, names) = splitEithers mb_gres
596 ; when (null names) (addErr (head errs)) -- Bleat about one only
599 dataTcOccs :: RdrName -> [RdrName]
600 -- If the input is a data constructor, return both it and a type
601 -- constructor. This is useful when we aren't sure which we are
604 | Just n <- isExact_maybe rdr_name -- Ghastly special case
605 , n `hasKey` consDataConKey = [rdr_name] -- see note below
606 | isDataOcc occ = [rdr_name, rdr_name_tc]
607 | otherwise = [rdr_name]
609 occ = rdrNameOcc rdr_name
610 rdr_name_tc = setRdrNameSpace rdr_name tcName
612 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
613 -- and setRdrNameSpace generates an Orig, which is fine
614 -- But it's not fine for (:), because there *is* no corresponding type
615 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
616 -- appear to be in scope (because Orig's simply allocate a new name-cache
617 -- entry) and then we get an error when we use dataTcOccs in
618 -- TcRnDriver.tcRnGetInfo. Large sigh.
622 %*********************************************************
626 %*********************************************************
629 --------------------------------
630 type FastStringEnv a = UniqFM a -- Keyed by FastString
633 emptyFsEnv :: FastStringEnv a
634 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
635 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
637 emptyFsEnv = emptyUFM
638 lookupFsEnv = lookupUFM
639 extendFsEnv = addToUFM
641 --------------------------------
642 type MiniFixityEnv = FastStringEnv (Located Fixity)
643 -- Mini fixity env for the names we're about
644 -- to bind, in a single binding group
646 -- It is keyed by the *FastString*, not the *OccName*, because
647 -- the single fixity decl infix 3 T
648 -- affects both the data constructor T and the type constrctor T
650 -- We keep the location so that if we find
651 -- a duplicate, we can report it sensibly
653 --------------------------------
654 -- Used for nested fixity decls to bind names along with their fixities.
655 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
657 addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
658 addLocalFixities mini_fix_env names thing_inside
659 = extendFixityEnv (mapCatMaybes find_fixity names) thing_inside
662 = case lookupFsEnv mini_fix_env (occNameFS occ) of
663 Just (L _ fix) -> Just (name, FixItem occ fix)
666 occ = nameOccName name
669 --------------------------------
670 lookupFixity is a bit strange.
672 * Nested local fixity decls are put in the local fixity env, which we
673 find with getFixtyEnv
675 * Imported fixities are found in the HIT or PIT
677 * Top-level fixity decls in this module may be for Names that are
678 either Global (constructors, class operations)
679 or Local/Exported (everything else)
680 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
681 We put them all in the local fixity environment
684 lookupFixityRn :: Name -> RnM Fixity
686 = getModule `thenM` \ this_mod ->
687 if nameIsLocalOrFrom this_mod name
688 then do -- It's defined in this module
689 local_fix_env <- getFixityEnv
690 traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
691 vcat [ppr name, ppr local_fix_env])
692 return $ lookupFixity local_fix_env name
693 else -- It's imported
694 -- For imported names, we have to get their fixities by doing a
695 -- loadInterfaceForName, and consulting the Ifaces that comes back
696 -- from that, because the interface file for the Name might not
697 -- have been loaded yet. Why not? Suppose you import module A,
698 -- which exports a function 'f', thus;
699 -- module CurrentModule where
701 -- module A( f ) where
703 -- Then B isn't loaded right away (after all, it's possible that
704 -- nothing from B will be used). When we come across a use of
705 -- 'f', we need to know its fixity, and it's then, and only
706 -- then, that we load B.hi. That is what's happening here.
708 -- loadInterfaceForName will find B.hi even if B is a hidden module,
709 -- and that's what we want.
710 loadInterfaceForName doc name `thenM` \ iface -> do {
711 traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
712 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
713 return (mi_fix_fn iface (nameOccName name))
716 doc = ptext (sLit "Checking fixity for") <+> ppr name
719 lookupTyFixityRn :: Located Name -> RnM Fixity
720 lookupTyFixityRn (L _ n) = lookupFixityRn n
724 %************************************************************************
727 Dealing with rebindable syntax is driven by the
728 Opt_NoImplicitPrelude dynamic flag.
730 In "deriving" code we don't want to use rebindable syntax
731 so we switch off the flag locally
734 %************************************************************************
736 Haskell 98 says that when you say "3" you get the "fromInteger" from the
737 Standard Prelude, regardless of what is in scope. However, to experiment
738 with having a language that is less coupled to the standard prelude, we're
739 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
740 happens to be in scope. Then you can
742 import MyPrelude as Prelude
743 to get the desired effect.
745 At the moment this just happens for
746 * fromInteger, fromRational on literals (in expressions and patterns)
747 * negate (in expressions)
748 * minus (arising from n+k patterns)
751 We store the relevant Name in the HsSyn tree, in
752 * HsIntegral/HsFractional/HsIsString
756 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
757 fromRationalName etc), but the renamer changes this to the appropriate user
758 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
760 We treat the orignal (standard) names as free-vars too, because the type checker
761 checks the type of the user thing against the type of the standard thing.
764 lookupSyntaxName :: Name -- The standard name
765 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
766 lookupSyntaxName std_name
767 = xoptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
768 if implicit_prelude then normal_case
770 -- Get the similarly named thing from the local environment
771 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
772 return (HsVar usr_name, unitFV usr_name)
774 normal_case = return (HsVar std_name, emptyFVs)
776 lookupSyntaxTable :: [Name] -- Standard names
777 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
778 lookupSyntaxTable std_names
779 = xoptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
780 if implicit_prelude then normal_case
782 -- Get the similarly named thing from the local environment
783 mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
785 return (std_names `zip` map HsVar usr_names, mkFVs usr_names)
787 normal_case = return (std_names `zip` map HsVar std_names, emptyFVs)
791 %*********************************************************
795 %*********************************************************
798 newLocalBndrRn :: Located RdrName -> RnM Name
799 -- Used for non-top-level binders. These should
800 -- never be qualified.
801 newLocalBndrRn (L loc rdr_name)
802 | Just name <- isExact_maybe rdr_name
803 = return name -- This happens in code generated by Template Haskell
804 -- although I'm not sure why. Perhpas it's the call
805 -- in RnPat.newName LetMk?
807 = do { unless (isUnqual rdr_name)
808 (addErrAt loc (badQualBndrErr rdr_name))
810 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
812 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
813 newLocalBndrsRn = mapM newLocalBndrRn
815 ---------------------
816 bindLocatedLocalsRn :: [Located RdrName]
819 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
820 = do { checkDupAndShadowedRdrNames rdr_names_w_loc
822 -- Make fresh Names and extend the environment
823 ; names <- newLocalBndrsRn rdr_names_w_loc
824 ; bindLocalNames names (enclosed_scope names) }
826 bindLocalNames :: [Name] -> RnM a -> RnM a
827 bindLocalNames names enclosed_scope
828 = do { name_env <- getLocalRdrEnv
829 ; setLocalRdrEnv (extendLocalRdrEnvList name_env names)
832 bindLocalName :: Name -> RnM a -> RnM a
833 bindLocalName name enclosed_scope
834 = do { name_env <- getLocalRdrEnv
835 ; setLocalRdrEnv (extendLocalRdrEnv name_env name)
838 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
839 bindLocalNamesFV names enclosed_scope
840 = do { (result, fvs) <- bindLocalNames names enclosed_scope
841 ; return (result, delFVs names fvs) }
844 -------------------------------------
845 -- binLocalsFVRn is the same as bindLocalsRn
846 -- except that it deals with free vars
847 bindLocatedLocalsFV :: [Located RdrName]
848 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
849 bindLocatedLocalsFV rdr_names enclosed_scope
850 = bindLocatedLocalsRn rdr_names $ \ names ->
851 enclosed_scope names `thenM` \ (thing, fvs) ->
852 return (thing, delFVs names fvs)
854 -------------------------------------
855 bindTyVarsFV :: [LHsTyVarBndr RdrName]
856 -> ([LHsTyVarBndr Name] -> RnM (a, FreeVars))
858 bindTyVarsFV tyvars thing_inside
859 = bindTyVarsRn tyvars $ \ tyvars' ->
860 do { (res, fvs) <- thing_inside tyvars'
861 ; return (res, delFVs (map hsLTyVarName tyvars') fvs) }
863 bindTyVarsRn :: [LHsTyVarBndr RdrName]
864 -> ([LHsTyVarBndr Name] -> RnM a)
866 -- Haskell-98 binding of type variables; e.g. within a data type decl
867 bindTyVarsRn tyvar_names enclosed_scope
868 = bindLocatedLocalsRn located_tyvars $ \ names ->
869 do { kind_sigs_ok <- xoptM Opt_KindSignatures
870 ; unless (null kinded_tyvars || kind_sigs_ok)
871 (mapM_ (addErr . kindSigErr) kinded_tyvars)
872 ; enclosed_scope (zipWith replace tyvar_names names) }
874 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
875 located_tyvars = hsLTyVarLocNames tyvar_names
876 kinded_tyvars = [n | L _ (KindedTyVar n _) <- tyvar_names]
878 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
879 -- Find the type variables in the pattern type
880 -- signatures that must be brought into scope
881 bindPatSigTyVars tys thing_inside
882 = do { scoped_tyvars <- xoptM Opt_ScopedTypeVariables
883 ; if not scoped_tyvars then
886 do { name_env <- getLocalRdrEnv
887 ; let locd_tvs = [ tv | ty <- tys
888 , tv <- extractHsTyRdrTyVars ty
889 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
890 nubbed_tvs = nubBy eqLocated locd_tvs
891 -- The 'nub' is important. For example:
892 -- f (x :: t) (y :: t) = ....
893 -- We don't want to complain about binding t twice!
895 ; bindLocatedLocalsRn nubbed_tvs thing_inside }}
897 bindPatSigTyVarsFV :: [LHsType RdrName]
900 bindPatSigTyVarsFV tys thing_inside
901 = bindPatSigTyVars tys $ \ tvs ->
902 thing_inside `thenM` \ (result,fvs) ->
903 return (result, fvs `delListFromNameSet` tvs)
905 bindSigTyVarsFV :: [Name]
908 bindSigTyVarsFV tvs thing_inside
909 = do { scoped_tyvars <- xoptM Opt_ScopedTypeVariables
910 ; if not scoped_tyvars then
913 bindLocalNamesFV tvs thing_inside }
915 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
916 -- This function is used only in rnSourceDecl on InstDecl
917 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
919 -------------------------------------
920 checkDupRdrNames :: [Located RdrName] -> RnM ()
921 checkDupRdrNames rdr_names_w_loc
922 = -- Check for duplicated names in a binding group
923 mapM_ (dupNamesErr getLoc) dups
925 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
927 checkDupNames :: [Name] -> RnM ()
929 = -- Check for duplicated names in a binding group
930 mapM_ (dupNamesErr nameSrcSpan) dups
932 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
934 ---------------------
935 checkDupAndShadowedRdrNames :: [Located RdrName] -> RnM ()
936 checkDupAndShadowedRdrNames loc_rdr_names
937 = do { checkDupRdrNames loc_rdr_names
939 ; checkShadowedOccs envs loc_occs }
941 loc_occs = [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names]
943 checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
944 checkDupAndShadowedNames envs names
945 = do { checkDupNames names
946 ; checkShadowedOccs envs loc_occs }
948 loc_occs = [(nameSrcSpan name, nameOccName name) | name <- names]
950 -------------------------------------
951 checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
952 checkShadowedOccs (global_env,local_env) loc_occs
953 = ifDOptM Opt_WarnNameShadowing $
954 do { traceRn (text "shadow" <+> ppr loc_occs)
955 ; mapM_ check_shadow loc_occs }
957 check_shadow (loc, occ)
958 | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
960 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
961 | otherwise = do { gres' <- filterM is_shadowed_gre gres
962 ; complain (map pprNameProvenance gres') }
964 complain [] = return ()
965 complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
966 mb_local = lookupLocalRdrOcc local_env occ
967 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
968 -- Make an Unqualified RdrName and look that up, so that
969 -- we don't find any GREs that are in scope qualified-only
971 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
972 -- Returns False for record selectors that are shadowed, when
973 -- punning or wild-cards are on (cf Trac #2723)
974 is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
975 = do { dflags <- getDOpts
976 ; if (xopt Opt_RecordPuns dflags || xopt Opt_RecordWildCards dflags)
977 then do { is_fld <- is_rec_fld gre; return (not is_fld) }
979 is_shadowed_gre _other = return True
981 is_rec_fld gre -- Return True for record selector ids
982 | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
983 ; return (gre_name gre `elemNameSet` fld_set) }
984 | otherwise = do { sel_id <- tcLookupField (gre_name gre)
985 ; return (isRecordSelector sel_id) }
989 %************************************************************************
991 \subsection{Free variable manipulation}
993 %************************************************************************
997 addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
998 addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
999 ; return (res, fvs1 `plusFV` fvs2) }
1001 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
1002 mapFvRn f xs = do stuff <- mapM f xs
1004 (ys, fvs_s) -> return (ys, plusFVs fvs_s)
1006 mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
1007 mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
1008 mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
1010 -- because some of the rename functions are CPSed:
1011 -- maps the function across the list from left to right;
1012 -- collects all the free vars into one set
1013 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
1014 -> [a] -> ([b] -> RnM c) -> RnM c
1016 mapFvRnCPS _ [] cont = cont []
1017 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
1018 mapFvRnCPS f xs $ \ xs' ->
1023 %************************************************************************
1025 \subsection{Envt utility functions}
1027 %************************************************************************
1030 warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1031 warnUnusedTopBinds gres
1032 = ifDOptM Opt_WarnUnusedBinds
1033 $ do isBoot <- tcIsHsBoot
1034 let noParent gre = case gre_par gre of
1037 -- Don't warn about unused bindings with parents in
1038 -- .hs-boot files, as you are sometimes required to give
1039 -- unused bindings (trac #3449).
1040 gres' = if isBoot then filter noParent gres
1042 warnUnusedGREs gres'
1044 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1045 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
1046 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
1048 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
1049 check_unused flag bound_names used_names
1050 = ifDOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1052 -------------------------
1054 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1056 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1058 warnUnusedLocals :: [Name] -> RnM ()
1059 warnUnusedLocals names
1060 = warnUnusedBinds [(n,LocalDef) | n<-names]
1062 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
1063 warnUnusedBinds names = mapM_ warnUnusedName (filter reportable names)
1064 where reportable (name,_)
1065 | isWiredInName name = False -- Don't report unused wired-in names
1066 -- Otherwise we get a zillion warnings
1068 | otherwise = not (startsWithUnderscore (nameOccName name))
1070 -------------------------
1072 warnUnusedName :: (Name, Provenance) -> RnM ()
1073 warnUnusedName (name, LocalDef)
1074 = addUnusedWarning name (nameSrcSpan name)
1075 (ptext (sLit "Defined but not used"))
1077 warnUnusedName (name, Imported is)
1080 warn spec = addUnusedWarning name span msg
1082 span = importSpecLoc spec
1083 pp_mod = quotes (ppr (importSpecModule spec))
1084 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1086 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1087 addUnusedWarning name span msg
1090 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1091 <+> quotes (ppr name)]
1095 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1096 addNameClashErrRn rdr_name names
1097 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1098 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1101 msg1 = ptext (sLit "either") <+> mk_ref np1
1102 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
1103 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1105 shadowedNameWarn :: OccName -> [SDoc] -> SDoc
1106 shadowedNameWarn occ shadowed_locs
1107 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1108 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1109 nest 2 (vcat shadowed_locs)]
1111 unknownNameErr :: RdrName -> SDoc
1112 unknownNameErr rdr_name
1113 = vcat [ hang (ptext (sLit "Not in scope:"))
1114 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1115 <+> quotes (ppr rdr_name))
1118 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1121 perhapsForallMsg :: SDoc
1123 = vcat [ ptext (sLit "Perhaps you intended to use -XExplicitForAll or similar flag")
1124 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1126 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1127 unknownSubordinateErr doc op -- Doc is "method of class" or
1128 -- "field of constructor"
1129 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1131 badOrigBinding :: RdrName -> SDoc
1133 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1134 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1136 dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
1137 dupNamesErr get_loc names
1138 = addErrAt big_loc $
1139 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1142 locs = map get_loc names
1143 big_loc = foldr1 combineSrcSpans locs
1144 locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sortLe (<=) locs))
1146 kindSigErr :: Outputable a => a -> SDoc
1148 = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
1149 2 (ptext (sLit "Perhaps you intended to use -XKindSignatures"))
1152 badQualBndrErr :: RdrName -> SDoc
1153 badQualBndrErr rdr_name
1154 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
1156 opDeclErr :: RdrName -> SDoc
1158 = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
1159 2 (ptext (sLit "Use -XTypeOperators to declare operators in type and declarations"))