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, lookupBndrRn_maybe,
17 lookupLocatedTopBndrRn, lookupTopBndrRn, lookupBndrRn_maybe,
18 lookupLocatedOccRn, lookupOccRn,
19 lookupLocatedGlobalOccRn, lookupGlobalOccRn,
20 lookupLocalDataTcNames, lookupSrcOcc_maybe,
21 lookupFixityRn, lookupTyFixityRn, lookupLocatedSigOccRn,
22 lookupInstDeclBndr, lookupRecordBndr, lookupConstructorFields,
23 lookupSyntaxName, lookupSyntaxTable, lookupImportedName,
24 lookupGreRn, lookupGreLocalRn, lookupGreRn_maybe,
27 newLocalsRn, newIPNameRn,
28 bindLocalNames, bindLocalNamesFV, bindLocalNamesFV_WithFixities,
29 bindLocatedLocalsFV, bindLocatedLocalsRn,
30 bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
31 bindTyVarsRn, extendTyVarEnvFVRn,
34 checkDupRdrNames, checkDupNames, checkShadowedNames,
35 checkDupAndShadowedRdrNames,
37 warnUnusedMatches, warnUnusedModules, warnUnusedImports,
38 warnUnusedTopBinds, warnUnusedLocalBinds,
39 dataTcOccs, unknownNameErr,
42 #include "HsVersions.h"
44 import LoadIface ( loadInterfaceForName, loadSrcInterface )
45 import IfaceEnv ( lookupOrig, newGlobalBinder, newIPName )
46 import HsSyn ( FixitySig(..), HsExpr(..), SyntaxExpr, SyntaxTable,
47 LHsTyVarBndr, LHsType,
48 Fixity, hsLTyVarLocNames, replaceTyVarName )
49 import RdrHsSyn ( extractHsTyRdrTyVars )
51 import HscTypes ( availNames, ModIface(..), FixItem(..), lookupFixity)
52 import TcEnv ( tcLookupDataCon )
54 import Name ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
55 nameSrcLoc, nameSrcSpan, nameOccName, nameModule, isExternalName )
59 import DataCon ( dataConFieldLabels )
60 import OccName ( OccName, tcName, isDataOcc, pprNonVarNameSpace, occNameSpace,
61 reportIfUnused, occNameFS )
62 import Module ( Module, ModuleName )
63 import PrelNames ( mkUnboundName, rOOT_MAIN, iNTERACTIVE, consDataConKey, hasKey )
65 import BasicTypes ( IPName, mapIPName, Fixity )
66 import SrcLoc ( SrcSpan, srcSpanStart, Located(..), eqLocated, unLoc,
67 srcLocSpan, getLoc, combineSrcSpans, isOneLineSpan )
71 import ListSetOps ( removeDups )
80 thenM :: Monad a => a b -> (b -> a c) -> a c
83 thenM_ :: Monad a => a b -> a c -> a c
86 returnM :: Monad m => a -> m a
89 mappM :: (Monad m) => (a -> m b) -> [a] -> m [b]
92 mappM_ :: (Monad m) => (a -> m b) -> [a] -> m ()
95 checkM :: Monad m => Bool -> m () -> m ()
99 %*********************************************************
103 %*********************************************************
106 newTopSrcBinder :: Module -> Located RdrName -> RnM Name
107 newTopSrcBinder this_mod (L loc rdr_name)
108 | Just name <- isExact_maybe rdr_name
109 = -- This is here to catch
110 -- (a) Exact-name binders created by Template Haskell
111 -- (b) The PrelBase defn of (say) [] and similar, for which
112 -- the parser reads the special syntax and returns an Exact RdrName
113 -- We are at a binding site for the name, so check first that it
114 -- the current module is the correct one; otherwise GHC can get
115 -- very confused indeed. This test rejects code like
116 -- data T = (,) Int Int
117 -- unless we are in GHC.Tup
118 ASSERT2( isExternalName name, ppr name )
119 do { checkM (this_mod == nameModule name)
120 (addErrAt loc (badOrigBinding rdr_name))
124 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
125 = do { checkM (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
126 (addErrAt loc (badOrigBinding rdr_name))
127 -- When reading External Core we get Orig names as binders,
128 -- but they should agree with the module gotten from the monad
130 -- We can get built-in syntax showing up here too, sadly. If you type
132 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
133 -- uses setRdrNameSpace to make it into a data constructors. At that point
134 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
135 -- Hence the badOrigBinding error message.
137 -- Except for the ":Main.main = ..." definition inserted into
138 -- the Main module; ugh!
140 -- Because of this latter case, we call newGlobalBinder with a module from
141 -- the RdrName, not from the environment. In principle, it'd be fine to
142 -- have an arbitrary mixture of external core definitions in a single module,
143 -- (apart from module-initialisation issues, perhaps).
144 ; newGlobalBinder rdr_mod rdr_occ loc }
145 --TODO, should pass the whole span
148 = do { checkM (not (isQual rdr_name))
149 (addErrAt loc (badQualBndrErr rdr_name))
150 -- Binders should not be qualified; if they are, and with a different
151 -- module name, we we get a confusing "M.T is not in scope" error later
152 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
155 %*********************************************************
157 Source code occurrences
159 %*********************************************************
161 Looking up a name in the RnEnv.
164 lookupLocatedBndrRn :: Located RdrName -> RnM (Located Name)
165 lookupLocatedBndrRn = wrapLocM lookupBndrRn
167 lookupBndrRn :: RdrName -> RnM Name
168 lookupBndrRn n = do nopt <- lookupBndrRn_maybe n
171 Nothing -> do traceRn $ text "lookupTopBndrRn"
174 lookupTopBndrRn :: RdrName -> RnM Name
175 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
178 Nothing -> do traceRn $ text "lookupTopBndrRn"
181 lookupBndrRn_maybe :: RdrName -> RnM (Maybe Name)
182 -- NOTE: assumes that the SrcSpan of the binder has already been setSrcSpan'd
183 lookupBndrRn_maybe rdr_name
184 = getLocalRdrEnv `thenM` \ local_env ->
185 case lookupLocalRdrEnv local_env rdr_name of
186 Just name -> returnM (Just name)
187 Nothing -> lookupTopBndrRn_maybe rdr_name
189 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
190 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
192 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
193 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
194 -- and there may be several imported 'f's too, which must not confuse us.
195 -- For example, this is OK:
197 -- infix 9 f -- The 'f' here does not need to be qualified
198 -- f x = x -- Nor here, of course
199 -- So we have to filter out the non-local ones.
201 -- A separate function (importsFromLocalDecls) reports duplicate top level
202 -- decls, so here it's safe just to choose an arbitrary one.
204 -- There should never be a qualified name in a binding position in Haskell,
205 -- but there can be if we have read in an external-Core file.
206 -- The Haskell parser checks for the illegal qualified name in Haskell
207 -- source files, so we don't need to do so here.
209 lookupTopBndrRn_maybe rdr_name
210 | Just name <- isExact_maybe rdr_name
211 = returnM (Just name)
213 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
214 -- This deals with the case of derived bindings, where
215 -- we don't bother to call newTopSrcBinder first
216 -- We assume there is no "parent" name
217 = do { loc <- getSrcSpanM
218 ; n <- newGlobalBinder rdr_mod rdr_occ loc
222 = do { mb_gre <- lookupGreLocalRn rdr_name
224 Nothing -> returnM Nothing
225 Just gre -> returnM (Just $ gre_name gre) }
227 -- lookupLocatedSigOccRn is used for type signatures and pragmas
233 -- It's clear that the 'f' in the signature must refer to A.f
234 -- The Haskell98 report does not stipulate this, but it will!
235 -- So we must treat the 'f' in the signature in the same way
236 -- as the binding occurrence of 'f', using lookupBndrRn
238 -- However, consider this case:
242 -- We don't want to say 'f' is out of scope; instead, we want to
243 -- return the imported 'f', so that later on the reanamer will
244 -- correctly report "misplaced type sig".
245 lookupLocatedSigOccRn :: Located RdrName -> RnM (Located Name)
246 lookupLocatedSigOccRn = wrapLocM $ \ rdr_name -> do
247 { local_env <- getLocalRdrEnv
248 ; case lookupLocalRdrEnv local_env rdr_name of {
251 { mb_gre <- lookupGreLocalRn rdr_name
253 Just gre -> return (gre_name gre)
254 Nothing -> lookupGlobalOccRn rdr_name
257 -----------------------------------------------
258 lookupInstDeclBndr :: Name -> Located RdrName -> RnM (Located Name)
259 -- This is called on the method name on the left-hand side of an
260 -- instance declaration binding. eg. instance Functor T where
262 -- ^^^^ called on this
263 -- Regardless of how many unqualified fmaps are in scope, we want
264 -- the one that comes from the Functor class.
266 -- Furthermore, note that we take no account of whether the
267 -- name is only in scope qualified. I.e. even if method op is
268 -- in scope as M.op, we still allow plain 'op' on the LHS of
270 lookupInstDeclBndr cls rdr = lookup_located_sub_bndr is_op doc rdr
272 doc = ptext SLIT("method of class") <+> quotes (ppr cls)
273 is_op gre@(GRE {gre_par = ParentIs n}) = n == cls
276 -----------------------------------------------
277 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
278 -- Used for record construction and pattern matching
279 -- When the -fdisambiguate-record-fields flag is on, take account of the
280 -- constructor name to disambiguate which field to use; it's just the
281 -- same as for instance decls
282 lookupRecordBndr Nothing rdr_name
283 = lookupLocatedGlobalOccRn rdr_name
284 lookupRecordBndr (Just (L _ data_con)) rdr_name
285 = do { flag_on <- doptM Opt_DisambiguateRecordFields
287 then lookupLocatedGlobalOccRn rdr_name
289 fields <- lookupConstructorFields data_con
290 ; let is_field gre = gre_name gre `elem` fields
291 ; lookup_located_sub_bndr is_field doc rdr_name
294 doc = ptext SLIT("field of constructor") <+> quotes (ppr data_con)
297 lookupConstructorFields :: Name -> RnM [Name]
298 -- Look up the fields of a given constructor
299 -- * For constructors from this module, use the record field env,
300 -- which is itself gathered from the (as yet un-typechecked)
303 -- * For constructors from imported modules, use the *type* environment
304 -- since imported modles are already compiled, the info is conveniently
307 lookupConstructorFields con_name
308 = do { this_mod <- getModule
309 ; if nameIsLocalOrFrom this_mod con_name then
310 do { field_env <- getRecFieldEnv
311 ; return (lookupNameEnv field_env con_name `orElse` []) }
313 do { con <- tcLookupDataCon con_name
314 ; return (dataConFieldLabels con) } }
316 -----------------------------------------------
317 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
318 -> SDoc -> Located RdrName
319 -> RnM (Located Name)
320 lookup_located_sub_bndr is_good doc rdr_name
321 = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
323 lookup_sub_bndr is_good doc rdr_name
324 | isUnqual rdr_name -- Find all the things the rdr-name maps to
325 = do { -- and pick the one with the right parent name
326 ; env <- getGlobalRdrEnv
327 ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) of
328 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
329 -- The latter does pickGREs, but we want to allow 'x'
330 -- even if only 'M.x' is in scope
331 [gre] -> return (gre_name gre)
332 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
333 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
334 ; return (mkUnboundName rdr_name) }
335 gres -> do { addNameClashErrRn rdr_name gres
336 ; return (gre_name (head gres)) }
339 | otherwise -- Occurs in derived instances, where we just
340 -- refer directly to the right method
341 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
342 -- NB: qualified names are rejected by the parser
343 lookupImportedName rdr_name
345 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
346 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
348 -- Looking up family names in type instances is a subtle affair. The family
349 -- may be imported, in which case we need to lookup the occurence of a global
350 -- name. Alternatively, the family may be in the same binding group (and in
351 -- fact in a declaration processed later), and we need to create a new top
354 -- So, also this is strictly speaking an occurence, we cannot raise an error
355 -- message yet for instances without a family declaration. This will happen
356 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
358 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
359 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
360 = do { mb_gre <- lookupGreRn_maybe rdr_name
362 Just gre -> returnM (gre_name gre) ;
363 Nothing -> newTopSrcBinder mod lrdr_name }
365 --------------------------------------------------
367 --------------------------------------------------
369 getLookupOccRn :: RnM (Name -> Maybe Name)
371 = getLocalRdrEnv `thenM` \ local_env ->
372 return (lookupLocalRdrOcc local_env . nameOccName)
374 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
375 lookupLocatedOccRn = wrapLocM lookupOccRn
377 -- lookupOccRn looks up an occurrence of a RdrName
378 lookupOccRn :: RdrName -> RnM Name
380 = getLocalRdrEnv `thenM` \ local_env ->
381 case lookupLocalRdrEnv local_env rdr_name of
382 Just name -> returnM name
383 Nothing -> lookupGlobalOccRn rdr_name
385 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
386 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
388 lookupGlobalOccRn :: RdrName -> RnM Name
389 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
390 -- environment. It's used only for
391 -- record field names
392 -- class op names in class and instance decls
394 lookupGlobalOccRn rdr_name
395 | not (isSrcRdrName rdr_name)
396 = lookupImportedName rdr_name
399 = -- First look up the name in the normal environment.
400 lookupGreRn_maybe rdr_name `thenM` \ mb_gre ->
402 Just gre -> returnM (gre_name gre) ;
405 -- We allow qualified names on the command line to refer to
406 -- *any* name exported by any module in scope, just as if
407 -- there was an "import qualified M" declaration for every
409 getModule `thenM` \ mod ->
410 if isQual rdr_name && mod == iNTERACTIVE then
411 -- This test is not expensive,
412 lookupQualifiedName rdr_name -- and only happens for failed lookups
414 traceRn $ text "lookupGlobalOccRn"
415 unboundName rdr_name }
417 lookupImportedName :: RdrName -> TcRnIf m n Name
418 -- Lookup the occurrence of an imported name
419 -- The RdrName is *always* qualified or Exact
420 -- Treat it as an original name, and conjure up the Name
421 -- Usually it's Exact or Orig, but it can be Qual if it
422 -- comes from an hi-boot file. (This minor infelicity is
423 -- just to reduce duplication in the parser.)
424 lookupImportedName rdr_name
425 | Just n <- isExact_maybe rdr_name
426 -- This happens in derived code
429 -- Always Orig, even when reading a .hi-boot file
430 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
431 = lookupOrig rdr_mod rdr_occ
434 = pprPanic "RnEnv.lookupImportedName" (ppr rdr_name)
436 unboundName :: RdrName -> RnM Name
438 = do { addErr (unknownNameErr rdr_name)
439 ; env <- getGlobalRdrEnv;
440 ; traceRn (vcat [unknownNameErr rdr_name,
441 ptext SLIT("Global envt is:"),
442 nest 3 (pprGlobalRdrEnv env)])
443 ; returnM (mkUnboundName rdr_name) }
445 --------------------------------------------------
446 -- Lookup in the Global RdrEnv of the module
447 --------------------------------------------------
449 lookupSrcOcc_maybe :: RdrName -> RnM (Maybe Name)
450 -- No filter function; does not report an error on failure
451 lookupSrcOcc_maybe rdr_name
452 = do { mb_gre <- lookupGreRn_maybe rdr_name
454 Nothing -> returnM Nothing
455 Just gre -> returnM (Just (gre_name gre)) }
457 -------------------------
458 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
459 -- Just look up the RdrName in the GlobalRdrEnv
460 lookupGreRn_maybe rdr_name
461 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
463 lookupGreRn :: RdrName -> RnM GlobalRdrElt
464 -- If not found, add error message, and return a fake GRE
466 = do { mb_gre <- lookupGreRn_maybe rdr_name
468 Just gre -> return gre ;
470 { traceRn $ text "lookupGreRn"
471 ; name <- unboundName rdr_name
472 ; return (GRE { gre_name = name, gre_par = NoParent,
473 gre_prov = LocalDef }) }}}
475 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
476 -- Similar, but restricted to locally-defined things
477 lookupGreLocalRn rdr_name
478 = lookupGreRn_help rdr_name lookup_fn
480 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
482 lookupGreRn_help :: RdrName -- Only used in error message
483 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
484 -> RnM (Maybe GlobalRdrElt)
485 -- Checks for exactly one match; reports deprecations
486 -- Returns Nothing, without error, if too few
487 lookupGreRn_help rdr_name lookup
488 = do { env <- getGlobalRdrEnv
490 [] -> returnM Nothing
491 [gre] -> returnM (Just gre)
492 gres -> do { addNameClashErrRn rdr_name gres
493 ; returnM (Just (head gres)) } }
495 ------------------------------
497 ------------------------------
499 -- A qualified name on the command line can refer to any module at all: we
500 -- try to load the interface if we don't already have it.
501 lookupQualifiedName :: RdrName -> RnM Name
502 lookupQualifiedName rdr_name
503 | Just (mod,occ) <- isQual_maybe rdr_name
504 -- Note: we want to behave as we would for a source file import here,
505 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
506 = loadSrcInterface doc mod False `thenM` \ iface ->
509 (mod,avails) <- mi_exports iface,
511 name <- availNames avail,
513 ((mod,occ):ns) -> ASSERT (null ns)
515 _ -> unboundName rdr_name
518 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
520 doc = ptext SLIT("Need to find") <+> ppr rdr_name
523 %*********************************************************
527 %*********************************************************
530 lookupLocalDataTcNames :: RdrName -> RnM [Name]
531 -- GHC extension: look up both the tycon and data con
532 -- for con-like things
533 -- Complain if neither is in scope
534 lookupLocalDataTcNames rdr_name
535 | Just n <- isExact_maybe rdr_name
536 -- Special case for (:), which doesn't get into the GlobalRdrEnv
537 = return [n] -- For this we don't need to try the tycon too
539 = do { mb_gres <- mapM lookupGreLocalRn (dataTcOccs rdr_name)
540 ; case [gre_name gre | Just gre <- mb_gres] of
542 -- run for error reporting
543 ; unboundName rdr_name
545 names -> return names
548 --------------------------------
549 bindLocalFixities :: [FixitySig RdrName] -> (UniqFM (Located Fixity) -> RnM a) -> RnM a
550 -- Used for nested fixity decls:
551 -- bind the names that are in scope already;
552 -- pass the rest to the continuation for later
553 -- as a FastString->(Located Fixity) map
555 -- No need to worry about type constructors here,
556 -- Should check for duplicates?
557 bindLocalFixities fixes thing_inside
558 | null fixes = thing_inside emptyUFM
559 | otherwise = do ls <- mappM rn_sig fixes
560 let (now, later) = nowAndLater ls
561 extendFixityEnv now $ thing_inside later
563 rn_sig (FixitySig lv@(L loc v) fix) = do
564 vopt <- lookupBndrRn_maybe v
566 Just new_v -> returnM (Left (new_v, (FixItem (rdrNameOcc v) fix)))
567 Nothing -> returnM (Right (occNameFS $ rdrNameOcc v, (L loc fix)))
569 nowAndLater :: [Either (Name, FixItem) (FastString, Located Fixity)]
570 -> ([(Name,FixItem)], UniqFM (Located Fixity))
572 foldr (\ cur -> \ (now, later) ->
574 Left (n, f) -> ((n, f) : now, later)
575 Right (fs, f) -> (now, addToUFM later fs f))
578 -- Used for nested fixity decls to bind names along with their fixities.
579 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
580 -- Also check for unused binders
581 bindLocalNamesFV_WithFixities :: [Name]
582 -> UniqFM (Located Fixity)
583 -> RnM (a, FreeVars) -> RnM (a, FreeVars)
584 bindLocalNamesFV_WithFixities names fixities thing_inside
585 = bindLocalNamesFV names $
586 extendFixityEnv boundFixities $
589 -- find the names that have fixity decls
590 boundFixities = foldr
592 -- check whether this name has a fixity decl
593 case lookupUFM fixities (occNameFS (nameOccName name)) of
594 Just (L _ fix) -> (name, FixItem (nameOccName name) fix) : acc
595 Nothing -> acc) [] names
596 -- bind the names; extend the fixity env; do the thing inside
599 --------------------------------
600 lookupFixity is a bit strange.
602 * Nested local fixity decls are put in the local fixity env, which we
603 find with getFixtyEnv
605 * Imported fixities are found in the HIT or PIT
607 * Top-level fixity decls in this module may be for Names that are
608 either Global (constructors, class operations)
609 or Local/Exported (everything else)
610 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
611 We put them all in the local fixity environment
614 lookupFixityRn :: Name -> RnM Fixity
616 = getModule `thenM` \ this_mod ->
617 if nameIsLocalOrFrom this_mod name
618 then do -- It's defined in this module
619 local_fix_env <- getFixityEnv
620 traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
621 vcat [ppr name, ppr local_fix_env])
622 return $ lookupFixity local_fix_env name
623 else -- It's imported
624 -- For imported names, we have to get their fixities by doing a
625 -- loadInterfaceForName, and consulting the Ifaces that comes back
626 -- from that, because the interface file for the Name might not
627 -- have been loaded yet. Why not? Suppose you import module A,
628 -- which exports a function 'f', thus;
629 -- module CurrentModule where
631 -- module A( f ) where
633 -- Then B isn't loaded right away (after all, it's possible that
634 -- nothing from B will be used). When we come across a use of
635 -- 'f', we need to know its fixity, and it's then, and only
636 -- then, that we load B.hi. That is what's happening here.
638 -- loadInterfaceForName will find B.hi even if B is a hidden module,
639 -- and that's what we want.
640 loadInterfaceForName doc name `thenM` \ iface -> do {
641 traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
642 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
643 returnM (mi_fix_fn iface (nameOccName name))
646 doc = ptext SLIT("Checking fixity for") <+> ppr name
649 lookupTyFixityRn :: Located Name -> RnM Fixity
650 lookupTyFixityRn (L loc n) = lookupFixityRn n
653 dataTcOccs :: RdrName -> [RdrName]
654 -- If the input is a data constructor, return both it and a type
655 -- constructor. This is useful when we aren't sure which we are
658 | Just n <- isExact_maybe rdr_name -- Ghastly special case
659 , n `hasKey` consDataConKey = [rdr_name] -- see note below
660 | isDataOcc occ = [rdr_name_tc, rdr_name]
661 | otherwise = [rdr_name]
663 occ = rdrNameOcc rdr_name
664 rdr_name_tc = setRdrNameSpace rdr_name tcName
666 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
667 -- and setRdrNameSpace generates an Orig, which is fine
668 -- But it's not fine for (:), because there *is* no corresponding type
669 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
670 -- appear to be in scope (because Orig's simply allocate a new name-cache
671 -- entry) and then we get an error when we use dataTcOccs in
672 -- TcRnDriver.tcRnGetInfo. Large sigh.
675 %************************************************************************
678 Dealing with rebindable syntax is driven by the
679 Opt_NoImplicitPrelude dynamic flag.
681 In "deriving" code we don't want to use rebindable syntax
682 so we switch off the flag locally
685 %************************************************************************
687 Haskell 98 says that when you say "3" you get the "fromInteger" from the
688 Standard Prelude, regardless of what is in scope. However, to experiment
689 with having a language that is less coupled to the standard prelude, we're
690 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
691 happens to be in scope. Then you can
693 import MyPrelude as Prelude
694 to get the desired effect.
696 At the moment this just happens for
697 * fromInteger, fromRational on literals (in expressions and patterns)
698 * negate (in expressions)
699 * minus (arising from n+k patterns)
702 We store the relevant Name in the HsSyn tree, in
703 * HsIntegral/HsFractional/HsIsString
707 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
708 fromRationalName etc), but the renamer changes this to the appropriate user
709 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
711 We treat the orignal (standard) names as free-vars too, because the type checker
712 checks the type of the user thing against the type of the standard thing.
715 lookupSyntaxName :: Name -- The standard name
716 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
717 lookupSyntaxName std_name
718 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
719 if implicit_prelude then normal_case
721 -- Get the similarly named thing from the local environment
722 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
723 returnM (HsVar usr_name, unitFV usr_name)
725 normal_case = returnM (HsVar std_name, emptyFVs)
727 lookupSyntaxTable :: [Name] -- Standard names
728 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
729 lookupSyntaxTable std_names
730 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
731 if implicit_prelude then normal_case
733 -- Get the similarly named thing from the local environment
734 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
736 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
738 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
742 %*********************************************************
746 %*********************************************************
749 newLocalsRn :: [Located RdrName] -> RnM [Name]
750 newLocalsRn rdr_names_w_loc
751 = newUniqueSupply `thenM` \ us ->
752 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
754 mk (L loc rdr_name) uniq
755 | Just name <- isExact_maybe rdr_name = name
756 -- This happens in code generated by Template Haskell
757 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
758 -- We only bind unqualified names here
759 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
760 mkInternalName uniq (rdrNameOcc rdr_name) loc
762 ---------------------
763 checkDupAndShadowedRdrNames :: SDoc -> [Located RdrName] -> RnM ()
764 checkDupAndShadowedRdrNames doc loc_rdr_names
765 = do { checkDupRdrNames doc loc_rdr_names
767 ; checkShadowedNames doc envs
768 [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names] }
770 ---------------------
771 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
775 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
776 = checkDupAndShadowedRdrNames doc_str rdr_names_w_loc `thenM_`
778 -- Make fresh Names and extend the environment
779 newLocalsRn rdr_names_w_loc `thenM` \names ->
780 bindLocalNames names (enclosed_scope names)
782 bindLocalNames :: [Name] -> RnM a -> RnM a
783 bindLocalNames names enclosed_scope
784 = getLocalRdrEnv `thenM` \ name_env ->
785 setLocalRdrEnv (extendLocalRdrEnv name_env names)
788 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
789 bindLocalNamesFV names enclosed_scope
790 = do { (result, fvs) <- bindLocalNames names enclosed_scope
791 ; returnM (result, delListFromNameSet fvs names) }
794 -------------------------------------
795 -- binLocalsFVRn is the same as bindLocalsRn
796 -- except that it deals with free vars
797 bindLocatedLocalsFV :: SDoc -> [Located RdrName]
798 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
799 bindLocatedLocalsFV doc rdr_names enclosed_scope
800 = bindLocatedLocalsRn doc rdr_names $ \ names ->
801 enclosed_scope names `thenM` \ (thing, fvs) ->
802 returnM (thing, delListFromNameSet fvs names)
804 -------------------------------------
805 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
806 -> ([LHsTyVarBndr Name] -> RnM a)
808 -- Haskell-98 binding of type variables; e.g. within a data type decl
809 bindTyVarsRn doc_str tyvar_names enclosed_scope
811 located_tyvars = hsLTyVarLocNames tyvar_names
813 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
814 enclosed_scope (zipWith replace tyvar_names names)
816 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
818 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
819 -- Find the type variables in the pattern type
820 -- signatures that must be brought into scope
821 bindPatSigTyVars tys thing_inside
822 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
823 ; if not scoped_tyvars then
826 do { name_env <- getLocalRdrEnv
827 ; let locd_tvs = [ tv | ty <- tys
828 , tv <- extractHsTyRdrTyVars ty
829 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
830 nubbed_tvs = nubBy eqLocated locd_tvs
831 -- The 'nub' is important. For example:
832 -- f (x :: t) (y :: t) = ....
833 -- We don't want to complain about binding t twice!
835 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
837 doc_sig = text "In a pattern type-signature"
839 bindPatSigTyVarsFV :: [LHsType RdrName]
842 bindPatSigTyVarsFV tys thing_inside
843 = bindPatSigTyVars tys $ \ tvs ->
844 thing_inside `thenM` \ (result,fvs) ->
845 returnM (result, fvs `delListFromNameSet` tvs)
847 bindSigTyVarsFV :: [Name]
850 bindSigTyVarsFV tvs thing_inside
851 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
852 ; if not scoped_tyvars then
855 bindLocalNamesFV tvs thing_inside }
857 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
858 -- This function is used only in rnSourceDecl on InstDecl
859 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
861 -------------------------------------
862 checkDupRdrNames :: SDoc
865 checkDupRdrNames doc_str rdr_names_w_loc
866 = -- Check for duplicated names in a binding group
867 mappM_ (dupNamesErr getLoc doc_str) dups
869 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
871 checkDupNames :: SDoc
874 checkDupNames doc_str names
875 = -- Check for duplicated names in a binding group
876 mappM_ (dupNamesErr nameSrcSpan doc_str) dups
878 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
880 -------------------------------------
881 checkShadowedNames :: SDoc -> (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
882 checkShadowedNames doc_str (global_env,local_env) loc_rdr_names
883 = ifOptM Opt_WarnNameShadowing $
884 do { traceRn (text "shadow" <+> ppr loc_rdr_names)
885 ; mappM_ check_shadow loc_rdr_names }
887 check_shadow (loc, occ)
888 | Just n <- mb_local = complain [ptext SLIT("bound at") <+> ppr loc]
889 | not (null gres) = complain (map pprNameProvenance gres)
890 | otherwise = return ()
892 complain pp_locs = addWarnAt loc (shadowedNameWarn doc_str occ pp_locs)
893 mb_local = lookupLocalRdrOcc local_env occ
894 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
895 -- Make an Unqualified RdrName and look that up, so that
896 -- we don't find any GREs that are in scope qualified-only
900 %************************************************************************
902 \subsection{Free variable manipulation}
904 %************************************************************************
908 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
910 (ys, fvs_s) = unzip stuff
912 returnM (ys, plusFVs fvs_s)
914 -- because some of the rename functions are CPSed:
915 -- maps the function across the list from left to right;
916 -- collects all the free vars into one set
917 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
918 -> [a] -> ([b] -> RnM c) -> RnM c
920 mapFvRnCPS _ [] cont = cont []
921 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
922 mapFvRnCPS f xs $ \ xs' ->
927 %************************************************************************
929 \subsection{Envt utility functions}
931 %************************************************************************
934 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
935 warnUnusedModules mods
936 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
938 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
939 mk_warn m = vcat [ptext SLIT("Module") <+> quotes (ppr m)
940 <+> text "is imported, but nothing from it is used,",
941 nest 2 (ptext SLIT("except perhaps instances visible in")
943 ptext SLIT("To suppress this warning, use:")
944 <+> ptext SLIT("import") <+> ppr m <> parens empty ]
947 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
948 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
949 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
951 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
952 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
953 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
955 check_unused :: DynFlag -> [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
956 check_unused flag names thing_inside
957 = do { (res, res_fvs) <- thing_inside
959 -- Warn about unused names
960 ; ifOptM flag (warnUnusedLocals (filterOut (`elemNameSet` res_fvs) names))
963 ; return (res, res_fvs) }
965 -------------------------
968 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
970 warnUnusedLocals names
971 = warnUnusedBinds [(n,LocalDef) | n<-names]
973 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
974 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
975 where reportable (name,_)
976 | isWiredInName name = False -- Don't report unused wired-in names
977 -- Otherwise we get a zillion warnings
979 | otherwise = reportIfUnused (nameOccName name)
981 -------------------------
983 warnUnusedName :: (Name, Provenance) -> RnM ()
984 warnUnusedName (name, LocalDef)
985 = addUnusedWarning name (srcLocSpan (nameSrcLoc name))
986 (ptext SLIT("Defined but not used"))
988 warnUnusedName (name, Imported is)
991 warn spec = addUnusedWarning name span msg
993 span = importSpecLoc spec
994 pp_mod = quotes (ppr (importSpecModule spec))
995 msg = ptext SLIT("Imported from") <+> pp_mod <+> ptext SLIT("but not used")
997 addUnusedWarning name span msg
1000 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1001 <+> quotes (ppr name)]
1005 addNameClashErrRn rdr_name names
1006 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1007 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1010 msg1 = ptext SLIT("either") <+> mk_ref np1
1011 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
1012 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1014 shadowedNameWarn doc occ shadowed_locs
1015 = sep [ptext SLIT("This binding for") <+> quotes (ppr occ)
1016 <+> ptext SLIT("shadows the existing binding") <> plural shadowed_locs,
1017 nest 2 (vcat shadowed_locs)]
1020 unknownNameErr rdr_name
1021 = sep [ptext SLIT("Not in scope:"),
1022 nest 2 $ pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1023 <+> quotes (ppr rdr_name)]
1025 unknownSubordinateErr doc op -- Doc is "method of class" or
1026 -- "field of constructor"
1027 = quotes (ppr op) <+> ptext SLIT("is not a (visible)") <+> doc
1030 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1031 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1033 dupNamesErr :: Outputable n => (n -> SrcSpan) -> SDoc -> [n] -> RnM ()
1034 dupNamesErr get_loc descriptor names
1035 = addErrAt big_loc $
1036 vcat [ptext SLIT("Conflicting definitions for") <+> quotes (ppr (head names)),
1037 locations, descriptor]
1039 locs = map get_loc names
1040 big_loc = foldr1 combineSrcSpans locs
1041 one_line = isOneLineSpan big_loc
1042 locations | one_line = empty
1043 | otherwise = ptext SLIT("Bound at:") <+>
1044 vcat (map ppr (sortLe (<=) locs))
1046 badQualBndrErr rdr_name
1047 = ptext SLIT("Qualified name in binding position:") <+> ppr rdr_name