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,
64 consDataConKey, hasKey, forall_tv_RDR )
66 import BasicTypes ( IPName, mapIPName, Fixity )
67 import SrcLoc ( SrcSpan, srcSpanStart, Located(..), eqLocated, unLoc,
68 srcLocSpan, getLoc, combineSrcSpans, isOneLineSpan )
72 import ListSetOps ( removeDups )
81 thenM :: Monad a => a b -> (b -> a c) -> a c
84 thenM_ :: Monad a => a b -> a c -> a c
87 returnM :: Monad m => a -> m a
90 mappM :: (Monad m) => (a -> m b) -> [a] -> m [b]
93 mappM_ :: (Monad m) => (a -> m b) -> [a] -> m ()
96 checkM :: Monad m => Bool -> m () -> m ()
100 %*********************************************************
104 %*********************************************************
107 newTopSrcBinder :: Module -> Located RdrName -> RnM Name
108 newTopSrcBinder this_mod (L loc rdr_name)
109 | Just name <- isExact_maybe rdr_name
110 = -- This is here to catch
111 -- (a) Exact-name binders created by Template Haskell
112 -- (b) The PrelBase defn of (say) [] and similar, for which
113 -- the parser reads the special syntax and returns an Exact RdrName
114 -- We are at a binding site for the name, so check first that it
115 -- the current module is the correct one; otherwise GHC can get
116 -- very confused indeed. This test rejects code like
117 -- data T = (,) Int Int
118 -- unless we are in GHC.Tup
119 ASSERT2( isExternalName name, ppr name )
120 do { checkM (this_mod == nameModule name)
121 (addErrAt loc (badOrigBinding rdr_name))
125 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
126 = do { checkM (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
127 (addErrAt loc (badOrigBinding rdr_name))
128 -- When reading External Core we get Orig names as binders,
129 -- but they should agree with the module gotten from the monad
131 -- We can get built-in syntax showing up here too, sadly. If you type
133 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
134 -- uses setRdrNameSpace to make it into a data constructors. At that point
135 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
136 -- Hence the badOrigBinding error message.
138 -- Except for the ":Main.main = ..." definition inserted into
139 -- the Main module; ugh!
141 -- Because of this latter case, we call newGlobalBinder with a module from
142 -- the RdrName, not from the environment. In principle, it'd be fine to
143 -- have an arbitrary mixture of external core definitions in a single module,
144 -- (apart from module-initialisation issues, perhaps).
145 ; newGlobalBinder rdr_mod rdr_occ loc }
146 --TODO, should pass the whole span
149 = do { checkM (not (isQual rdr_name))
150 (addErrAt loc (badQualBndrErr rdr_name))
151 -- Binders should not be qualified; if they are, and with a different
152 -- module name, we we get a confusing "M.T is not in scope" error later
153 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
156 %*********************************************************
158 Source code occurrences
160 %*********************************************************
162 Looking up a name in the RnEnv.
165 lookupLocatedBndrRn :: Located RdrName -> RnM (Located Name)
166 lookupLocatedBndrRn = wrapLocM lookupBndrRn
168 lookupBndrRn :: RdrName -> RnM Name
169 lookupBndrRn n = do nopt <- lookupBndrRn_maybe n
172 Nothing -> do traceRn $ text "lookupTopBndrRn"
175 lookupTopBndrRn :: RdrName -> RnM Name
176 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
179 Nothing -> do traceRn $ text "lookupTopBndrRn"
182 lookupBndrRn_maybe :: RdrName -> RnM (Maybe Name)
183 -- NOTE: assumes that the SrcSpan of the binder has already been setSrcSpan'd
184 lookupBndrRn_maybe rdr_name
185 = getLocalRdrEnv `thenM` \ local_env ->
186 case lookupLocalRdrEnv local_env rdr_name of
187 Just name -> returnM (Just name)
188 Nothing -> lookupTopBndrRn_maybe rdr_name
190 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
191 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
193 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
194 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
195 -- and there may be several imported 'f's too, which must not confuse us.
196 -- For example, this is OK:
198 -- infix 9 f -- The 'f' here does not need to be qualified
199 -- f x = x -- Nor here, of course
200 -- So we have to filter out the non-local ones.
202 -- A separate function (importsFromLocalDecls) reports duplicate top level
203 -- decls, so here it's safe just to choose an arbitrary one.
205 -- There should never be a qualified name in a binding position in Haskell,
206 -- but there can be if we have read in an external-Core file.
207 -- The Haskell parser checks for the illegal qualified name in Haskell
208 -- source files, so we don't need to do so here.
210 lookupTopBndrRn_maybe rdr_name
211 | Just name <- isExact_maybe rdr_name
212 = returnM (Just name)
214 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
215 -- This deals with the case of derived bindings, where
216 -- we don't bother to call newTopSrcBinder first
217 -- We assume there is no "parent" name
218 = do { loc <- getSrcSpanM
219 ; n <- newGlobalBinder rdr_mod rdr_occ loc
223 = do { mb_gre <- lookupGreLocalRn rdr_name
225 Nothing -> returnM Nothing
226 Just gre -> returnM (Just $ gre_name gre) }
228 -- lookupLocatedSigOccRn is used for type signatures and pragmas
234 -- It's clear that the 'f' in the signature must refer to A.f
235 -- The Haskell98 report does not stipulate this, but it will!
236 -- So we must treat the 'f' in the signature in the same way
237 -- as the binding occurrence of 'f', using lookupBndrRn
239 -- However, consider this case:
243 -- We don't want to say 'f' is out of scope; instead, we want to
244 -- return the imported 'f', so that later on the reanamer will
245 -- correctly report "misplaced type sig".
246 lookupLocatedSigOccRn :: Located RdrName -> RnM (Located Name)
247 lookupLocatedSigOccRn = wrapLocM $ \ rdr_name -> do
248 { local_env <- getLocalRdrEnv
249 ; case lookupLocalRdrEnv local_env rdr_name of {
252 { mb_gre <- lookupGreLocalRn rdr_name
254 Just gre -> return (gre_name gre)
255 Nothing -> lookupGlobalOccRn rdr_name
258 -----------------------------------------------
259 lookupInstDeclBndr :: Name -> Located RdrName -> RnM (Located Name)
260 -- This is called on the method name on the left-hand side of an
261 -- instance declaration binding. eg. instance Functor T where
263 -- ^^^^ called on this
264 -- Regardless of how many unqualified fmaps are in scope, we want
265 -- the one that comes from the Functor class.
267 -- Furthermore, note that we take no account of whether the
268 -- name is only in scope qualified. I.e. even if method op is
269 -- in scope as M.op, we still allow plain 'op' on the LHS of
271 lookupInstDeclBndr cls rdr = lookup_located_sub_bndr is_op doc rdr
273 doc = ptext SLIT("method of class") <+> quotes (ppr cls)
274 is_op gre@(GRE {gre_par = ParentIs n}) = n == cls
277 -----------------------------------------------
278 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
279 -- Used for record construction and pattern matching
280 -- When the -fdisambiguate-record-fields flag is on, take account of the
281 -- constructor name to disambiguate which field to use; it's just the
282 -- same as for instance decls
283 lookupRecordBndr Nothing rdr_name
284 = lookupLocatedGlobalOccRn rdr_name
285 lookupRecordBndr (Just (L _ data_con)) rdr_name
286 = do { flag_on <- doptM Opt_DisambiguateRecordFields
288 then lookupLocatedGlobalOccRn rdr_name
290 fields <- lookupConstructorFields data_con
291 ; let is_field gre = gre_name gre `elem` fields
292 ; lookup_located_sub_bndr is_field doc rdr_name
295 doc = ptext SLIT("field of constructor") <+> quotes (ppr data_con)
298 lookupConstructorFields :: Name -> RnM [Name]
299 -- Look up the fields of a given constructor
300 -- * For constructors from this module, use the record field env,
301 -- which is itself gathered from the (as yet un-typechecked)
304 -- * For constructors from imported modules, use the *type* environment
305 -- since imported modles are already compiled, the info is conveniently
308 lookupConstructorFields con_name
309 = do { this_mod <- getModule
310 ; if nameIsLocalOrFrom this_mod con_name then
311 do { field_env <- getRecFieldEnv
312 ; return (lookupNameEnv field_env con_name `orElse` []) }
314 do { con <- tcLookupDataCon con_name
315 ; return (dataConFieldLabels con) } }
317 -----------------------------------------------
318 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
319 -> SDoc -> Located RdrName
320 -> RnM (Located Name)
321 lookup_located_sub_bndr is_good doc rdr_name
322 = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
324 lookup_sub_bndr is_good doc rdr_name
325 | isUnqual rdr_name -- Find all the things the rdr-name maps to
326 = do { -- and pick the one with the right parent name
327 ; env <- getGlobalRdrEnv
328 ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) of
329 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
330 -- The latter does pickGREs, but we want to allow 'x'
331 -- even if only 'M.x' is in scope
332 [gre] -> return (gre_name gre)
333 [] -> do { addErr (unknownSubordinateErr doc rdr_name)
334 ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
335 ; return (mkUnboundName rdr_name) }
336 gres -> do { addNameClashErrRn rdr_name gres
337 ; return (gre_name (head gres)) }
340 | otherwise -- Occurs in derived instances, where we just
341 -- refer directly to the right method
342 = ASSERT2( not (isQual rdr_name), ppr rdr_name )
343 -- NB: qualified names are rejected by the parser
344 lookupImportedName rdr_name
346 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
347 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
349 -- Looking up family names in type instances is a subtle affair. The family
350 -- may be imported, in which case we need to lookup the occurence of a global
351 -- name. Alternatively, the family may be in the same binding group (and in
352 -- fact in a declaration processed later), and we need to create a new top
355 -- So, also this is strictly speaking an occurence, we cannot raise an error
356 -- message yet for instances without a family declaration. This will happen
357 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
359 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
360 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
361 = do { mb_gre <- lookupGreRn_maybe rdr_name
363 Just gre -> returnM (gre_name gre) ;
364 Nothing -> newTopSrcBinder mod lrdr_name }
366 --------------------------------------------------
368 --------------------------------------------------
370 getLookupOccRn :: RnM (Name -> Maybe Name)
372 = getLocalRdrEnv `thenM` \ local_env ->
373 return (lookupLocalRdrOcc local_env . nameOccName)
375 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
376 lookupLocatedOccRn = wrapLocM lookupOccRn
378 -- lookupOccRn looks up an occurrence of a RdrName
379 lookupOccRn :: RdrName -> RnM Name
381 = getLocalRdrEnv `thenM` \ local_env ->
382 case lookupLocalRdrEnv local_env rdr_name of
383 Just name -> returnM name
384 Nothing -> lookupGlobalOccRn rdr_name
386 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
387 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
389 lookupGlobalOccRn :: RdrName -> RnM Name
390 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
391 -- environment. It's used only for
392 -- record field names
393 -- class op names in class and instance decls
395 lookupGlobalOccRn rdr_name
396 | not (isSrcRdrName rdr_name)
397 = lookupImportedName rdr_name
400 = -- First look up the name in the normal environment.
401 lookupGreRn_maybe rdr_name `thenM` \ mb_gre ->
403 Just gre -> returnM (gre_name gre) ;
406 -- We allow qualified names on the command line to refer to
407 -- *any* name exported by any module in scope, just as if
408 -- there was an "import qualified M" declaration for every
410 getModule `thenM` \ mod ->
411 if isQual rdr_name && mod == iNTERACTIVE then
412 -- This test is not expensive,
413 lookupQualifiedName rdr_name -- and only happens for failed lookups
415 traceRn $ text "lookupGlobalOccRn"
416 unboundName rdr_name }
418 lookupImportedName :: RdrName -> TcRnIf m n Name
419 -- Lookup the occurrence of an imported name
420 -- The RdrName is *always* qualified or Exact
421 -- Treat it as an original name, and conjure up the Name
422 -- Usually it's Exact or Orig, but it can be Qual if it
423 -- comes from an hi-boot file. (This minor infelicity is
424 -- just to reduce duplication in the parser.)
425 lookupImportedName rdr_name
426 | Just n <- isExact_maybe rdr_name
427 -- This happens in derived code
430 -- Always Orig, even when reading a .hi-boot file
431 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
432 = lookupOrig rdr_mod rdr_occ
435 = pprPanic "RnEnv.lookupImportedName" (ppr rdr_name)
437 unboundName :: RdrName -> RnM Name
439 = do { addErr (unknownNameErr rdr_name)
440 ; env <- getGlobalRdrEnv;
441 ; traceRn (vcat [unknownNameErr rdr_name,
442 ptext SLIT("Global envt is:"),
443 nest 3 (pprGlobalRdrEnv env)])
444 ; returnM (mkUnboundName rdr_name) }
446 --------------------------------------------------
447 -- Lookup in the Global RdrEnv of the module
448 --------------------------------------------------
450 lookupSrcOcc_maybe :: RdrName -> RnM (Maybe Name)
451 -- No filter function; does not report an error on failure
452 lookupSrcOcc_maybe rdr_name
453 = do { mb_gre <- lookupGreRn_maybe rdr_name
455 Nothing -> returnM Nothing
456 Just gre -> returnM (Just (gre_name gre)) }
458 -------------------------
459 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
460 -- Just look up the RdrName in the GlobalRdrEnv
461 lookupGreRn_maybe rdr_name
462 = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
464 lookupGreRn :: RdrName -> RnM GlobalRdrElt
465 -- If not found, add error message, and return a fake GRE
467 = do { mb_gre <- lookupGreRn_maybe rdr_name
469 Just gre -> return gre ;
471 { traceRn $ text "lookupGreRn"
472 ; name <- unboundName rdr_name
473 ; return (GRE { gre_name = name, gre_par = NoParent,
474 gre_prov = LocalDef }) }}}
476 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
477 -- Similar, but restricted to locally-defined things
478 lookupGreLocalRn rdr_name
479 = lookupGreRn_help rdr_name lookup_fn
481 lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
483 lookupGreRn_help :: RdrName -- Only used in error message
484 -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
485 -> RnM (Maybe GlobalRdrElt)
486 -- Checks for exactly one match; reports deprecations
487 -- Returns Nothing, without error, if too few
488 lookupGreRn_help rdr_name lookup
489 = do { env <- getGlobalRdrEnv
491 [] -> returnM Nothing
492 [gre] -> returnM (Just gre)
493 gres -> do { addNameClashErrRn rdr_name gres
494 ; returnM (Just (head gres)) } }
496 ------------------------------
498 ------------------------------
500 -- A qualified name on the command line can refer to any module at all: we
501 -- try to load the interface if we don't already have it.
502 lookupQualifiedName :: RdrName -> RnM Name
503 lookupQualifiedName rdr_name
504 | Just (mod,occ) <- isQual_maybe rdr_name
505 -- Note: we want to behave as we would for a source file import here,
506 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
507 = loadSrcInterface doc mod False `thenM` \ iface ->
510 (mod,avails) <- mi_exports iface,
512 name <- availNames avail,
514 ((mod,occ):ns) -> ASSERT (null ns)
516 _ -> unboundName rdr_name
519 = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
521 doc = ptext SLIT("Need to find") <+> ppr rdr_name
524 %*********************************************************
528 %*********************************************************
531 lookupLocalDataTcNames :: RdrName -> RnM [Name]
532 -- GHC extension: look up both the tycon and data con
533 -- for con-like things
534 -- Complain if neither is in scope
535 lookupLocalDataTcNames rdr_name
536 | Just n <- isExact_maybe rdr_name
537 -- Special case for (:), which doesn't get into the GlobalRdrEnv
538 = return [n] -- For this we don't need to try the tycon too
540 = do { mb_gres <- mapM lookupGreLocalRn (dataTcOccs rdr_name)
541 ; case [gre_name gre | Just gre <- mb_gres] of
543 -- run for error reporting
544 ; unboundName rdr_name
546 names -> return names
549 --------------------------------
550 bindLocalFixities :: [FixitySig RdrName] -> (UniqFM (Located Fixity) -> RnM a) -> RnM a
551 -- Used for nested fixity decls:
552 -- bind the names that are in scope already;
553 -- pass the rest to the continuation for later
554 -- as a FastString->(Located Fixity) map
556 -- No need to worry about type constructors here,
557 -- Should check for duplicates?
558 bindLocalFixities fixes thing_inside
559 | null fixes = thing_inside emptyUFM
560 | otherwise = do ls <- mappM rn_sig fixes
561 let (now, later) = nowAndLater ls
562 extendFixityEnv now $ thing_inside later
564 rn_sig (FixitySig lv@(L loc v) fix) = do
565 vopt <- lookupBndrRn_maybe v
567 Just new_v -> returnM (Left (new_v, (FixItem (rdrNameOcc v) fix)))
568 Nothing -> returnM (Right (occNameFS $ rdrNameOcc v, (L loc fix)))
570 nowAndLater :: [Either (Name, FixItem) (FastString, Located Fixity)]
571 -> ([(Name,FixItem)], UniqFM (Located Fixity))
573 foldr (\ cur -> \ (now, later) ->
575 Left (n, f) -> ((n, f) : now, later)
576 Right (fs, f) -> (now, addToUFM later fs f))
579 -- Used for nested fixity decls to bind names along with their fixities.
580 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
581 -- Also check for unused binders
582 bindLocalNamesFV_WithFixities :: [Name]
583 -> UniqFM (Located Fixity)
584 -> RnM (a, FreeVars) -> RnM (a, FreeVars)
585 bindLocalNamesFV_WithFixities names fixities thing_inside
586 = bindLocalNamesFV names $
587 extendFixityEnv boundFixities $
590 -- find the names that have fixity decls
591 boundFixities = foldr
593 -- check whether this name has a fixity decl
594 case lookupUFM fixities (occNameFS (nameOccName name)) of
595 Just (L _ fix) -> (name, FixItem (nameOccName name) fix) : acc
596 Nothing -> acc) [] names
597 -- bind the names; extend the fixity env; do the thing inside
600 --------------------------------
601 lookupFixity is a bit strange.
603 * Nested local fixity decls are put in the local fixity env, which we
604 find with getFixtyEnv
606 * Imported fixities are found in the HIT or PIT
608 * Top-level fixity decls in this module may be for Names that are
609 either Global (constructors, class operations)
610 or Local/Exported (everything else)
611 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
612 We put them all in the local fixity environment
615 lookupFixityRn :: Name -> RnM Fixity
617 = getModule `thenM` \ this_mod ->
618 if nameIsLocalOrFrom this_mod name
619 then do -- It's defined in this module
620 local_fix_env <- getFixityEnv
621 traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
622 vcat [ppr name, ppr local_fix_env])
623 return $ lookupFixity local_fix_env name
624 else -- It's imported
625 -- For imported names, we have to get their fixities by doing a
626 -- loadInterfaceForName, and consulting the Ifaces that comes back
627 -- from that, because the interface file for the Name might not
628 -- have been loaded yet. Why not? Suppose you import module A,
629 -- which exports a function 'f', thus;
630 -- module CurrentModule where
632 -- module A( f ) where
634 -- Then B isn't loaded right away (after all, it's possible that
635 -- nothing from B will be used). When we come across a use of
636 -- 'f', we need to know its fixity, and it's then, and only
637 -- then, that we load B.hi. That is what's happening here.
639 -- loadInterfaceForName will find B.hi even if B is a hidden module,
640 -- and that's what we want.
641 loadInterfaceForName doc name `thenM` \ iface -> do {
642 traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
643 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
644 returnM (mi_fix_fn iface (nameOccName name))
647 doc = ptext SLIT("Checking fixity for") <+> ppr name
650 lookupTyFixityRn :: Located Name -> RnM Fixity
651 lookupTyFixityRn (L loc n) = lookupFixityRn n
654 dataTcOccs :: RdrName -> [RdrName]
655 -- If the input is a data constructor, return both it and a type
656 -- constructor. This is useful when we aren't sure which we are
659 | Just n <- isExact_maybe rdr_name -- Ghastly special case
660 , n `hasKey` consDataConKey = [rdr_name] -- see note below
661 | isDataOcc occ = [rdr_name_tc, rdr_name]
662 | otherwise = [rdr_name]
664 occ = rdrNameOcc rdr_name
665 rdr_name_tc = setRdrNameSpace rdr_name tcName
667 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
668 -- and setRdrNameSpace generates an Orig, which is fine
669 -- But it's not fine for (:), because there *is* no corresponding type
670 -- constructor. If we generate an Orig tycon for GHC.Base.(:), it'll
671 -- appear to be in scope (because Orig's simply allocate a new name-cache
672 -- entry) and then we get an error when we use dataTcOccs in
673 -- TcRnDriver.tcRnGetInfo. Large sigh.
676 %************************************************************************
679 Dealing with rebindable syntax is driven by the
680 Opt_NoImplicitPrelude dynamic flag.
682 In "deriving" code we don't want to use rebindable syntax
683 so we switch off the flag locally
686 %************************************************************************
688 Haskell 98 says that when you say "3" you get the "fromInteger" from the
689 Standard Prelude, regardless of what is in scope. However, to experiment
690 with having a language that is less coupled to the standard prelude, we're
691 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
692 happens to be in scope. Then you can
694 import MyPrelude as Prelude
695 to get the desired effect.
697 At the moment this just happens for
698 * fromInteger, fromRational on literals (in expressions and patterns)
699 * negate (in expressions)
700 * minus (arising from n+k patterns)
703 We store the relevant Name in the HsSyn tree, in
704 * HsIntegral/HsFractional/HsIsString
708 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
709 fromRationalName etc), but the renamer changes this to the appropriate user
710 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
712 We treat the orignal (standard) names as free-vars too, because the type checker
713 checks the type of the user thing against the type of the standard thing.
716 lookupSyntaxName :: Name -- The standard name
717 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
718 lookupSyntaxName std_name
719 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
720 if implicit_prelude then normal_case
722 -- Get the similarly named thing from the local environment
723 lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
724 returnM (HsVar usr_name, unitFV usr_name)
726 normal_case = returnM (HsVar std_name, emptyFVs)
728 lookupSyntaxTable :: [Name] -- Standard names
729 -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
730 lookupSyntaxTable std_names
731 = doptM Opt_ImplicitPrelude `thenM` \ implicit_prelude ->
732 if implicit_prelude then normal_case
734 -- Get the similarly named thing from the local environment
735 mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
737 returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
739 normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
743 %*********************************************************
747 %*********************************************************
750 newLocalsRn :: [Located RdrName] -> RnM [Name]
751 newLocalsRn rdr_names_w_loc
752 = newUniqueSupply `thenM` \ us ->
753 returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
755 mk (L loc rdr_name) uniq
756 | Just name <- isExact_maybe rdr_name = name
757 -- This happens in code generated by Template Haskell
758 | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
759 -- We only bind unqualified names here
760 -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
761 mkInternalName uniq (rdrNameOcc rdr_name) loc
763 ---------------------
764 checkDupAndShadowedRdrNames :: SDoc -> [Located RdrName] -> RnM ()
765 checkDupAndShadowedRdrNames doc loc_rdr_names
766 = do { checkDupRdrNames doc loc_rdr_names
768 ; checkShadowedNames doc envs
769 [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names] }
771 ---------------------
772 bindLocatedLocalsRn :: SDoc -- Documentation string for error message
776 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
777 = checkDupAndShadowedRdrNames doc_str rdr_names_w_loc `thenM_`
779 -- Make fresh Names and extend the environment
780 newLocalsRn rdr_names_w_loc `thenM` \names ->
781 bindLocalNames names (enclosed_scope names)
783 bindLocalNames :: [Name] -> RnM a -> RnM a
784 bindLocalNames names enclosed_scope
785 = getLocalRdrEnv `thenM` \ name_env ->
786 setLocalRdrEnv (extendLocalRdrEnv name_env names)
789 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
790 bindLocalNamesFV names enclosed_scope
791 = do { (result, fvs) <- bindLocalNames names enclosed_scope
792 ; returnM (result, delListFromNameSet fvs names) }
795 -------------------------------------
796 -- binLocalsFVRn is the same as bindLocalsRn
797 -- except that it deals with free vars
798 bindLocatedLocalsFV :: SDoc -> [Located RdrName]
799 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
800 bindLocatedLocalsFV doc rdr_names enclosed_scope
801 = bindLocatedLocalsRn doc rdr_names $ \ names ->
802 enclosed_scope names `thenM` \ (thing, fvs) ->
803 returnM (thing, delListFromNameSet fvs names)
805 -------------------------------------
806 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
807 -> ([LHsTyVarBndr Name] -> RnM a)
809 -- Haskell-98 binding of type variables; e.g. within a data type decl
810 bindTyVarsRn doc_str tyvar_names enclosed_scope
812 located_tyvars = hsLTyVarLocNames tyvar_names
814 bindLocatedLocalsRn doc_str located_tyvars $ \ names ->
815 enclosed_scope (zipWith replace tyvar_names names)
817 replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
819 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
820 -- Find the type variables in the pattern type
821 -- signatures that must be brought into scope
822 bindPatSigTyVars tys thing_inside
823 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
824 ; if not scoped_tyvars then
827 do { name_env <- getLocalRdrEnv
828 ; let locd_tvs = [ tv | ty <- tys
829 , tv <- extractHsTyRdrTyVars ty
830 , not (unLoc tv `elemLocalRdrEnv` name_env) ]
831 nubbed_tvs = nubBy eqLocated locd_tvs
832 -- The 'nub' is important. For example:
833 -- f (x :: t) (y :: t) = ....
834 -- We don't want to complain about binding t twice!
836 ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
838 doc_sig = text "In a pattern type-signature"
840 bindPatSigTyVarsFV :: [LHsType RdrName]
843 bindPatSigTyVarsFV tys thing_inside
844 = bindPatSigTyVars tys $ \ tvs ->
845 thing_inside `thenM` \ (result,fvs) ->
846 returnM (result, fvs `delListFromNameSet` tvs)
848 bindSigTyVarsFV :: [Name]
851 bindSigTyVarsFV tvs thing_inside
852 = do { scoped_tyvars <- doptM Opt_ScopedTypeVariables
853 ; if not scoped_tyvars then
856 bindLocalNamesFV tvs thing_inside }
858 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
859 -- This function is used only in rnSourceDecl on InstDecl
860 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
862 -------------------------------------
863 checkDupRdrNames :: SDoc
866 checkDupRdrNames doc_str rdr_names_w_loc
867 = -- Check for duplicated names in a binding group
868 mappM_ (dupNamesErr getLoc doc_str) dups
870 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
872 checkDupNames :: SDoc
875 checkDupNames doc_str names
876 = -- Check for duplicated names in a binding group
877 mappM_ (dupNamesErr nameSrcSpan doc_str) dups
879 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
881 -------------------------------------
882 checkShadowedNames :: SDoc -> (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
883 checkShadowedNames doc_str (global_env,local_env) loc_rdr_names
884 = ifOptM Opt_WarnNameShadowing $
885 do { traceRn (text "shadow" <+> ppr loc_rdr_names)
886 ; mappM_ check_shadow loc_rdr_names }
888 check_shadow (loc, occ)
889 | Just n <- mb_local = complain [ptext SLIT("bound at") <+> ppr loc]
890 | not (null gres) = complain (map pprNameProvenance gres)
891 | otherwise = return ()
893 complain pp_locs = addWarnAt loc (shadowedNameWarn doc_str occ pp_locs)
894 mb_local = lookupLocalRdrOcc local_env occ
895 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
896 -- Make an Unqualified RdrName and look that up, so that
897 -- we don't find any GREs that are in scope qualified-only
901 %************************************************************************
903 \subsection{Free variable manipulation}
905 %************************************************************************
909 mapFvRn f xs = mappM f xs `thenM` \ stuff ->
911 (ys, fvs_s) = unzip stuff
913 returnM (ys, plusFVs fvs_s)
915 -- because some of the rename functions are CPSed:
916 -- maps the function across the list from left to right;
917 -- collects all the free vars into one set
918 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
919 -> [a] -> ([b] -> RnM c) -> RnM c
921 mapFvRnCPS _ [] cont = cont []
922 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
923 mapFvRnCPS f xs $ \ xs' ->
928 %************************************************************************
930 \subsection{Envt utility functions}
932 %************************************************************************
935 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
936 warnUnusedModules mods
937 = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
939 bleat (mod,loc) = addWarnAt loc (mk_warn mod)
940 mk_warn m = vcat [ptext SLIT("Module") <+> quotes (ppr m)
941 <+> text "is imported, but nothing from it is used,",
942 nest 2 (ptext SLIT("except perhaps instances visible in")
944 ptext SLIT("To suppress this warning, use:")
945 <+> ptext SLIT("import") <+> ppr m <> parens empty ]
948 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
949 warnUnusedImports gres = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
950 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds (warnUnusedGREs gres)
952 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
953 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
954 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
956 check_unused :: DynFlag -> [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
957 check_unused flag names thing_inside
958 = do { (res, res_fvs) <- thing_inside
960 -- Warn about unused names
961 ; ifOptM flag (warnUnusedLocals (filterOut (`elemNameSet` res_fvs) names))
964 ; return (res, res_fvs) }
966 -------------------------
969 = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
971 warnUnusedLocals names
972 = warnUnusedBinds [(n,LocalDef) | n<-names]
974 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
975 warnUnusedBinds names = mappM_ warnUnusedName (filter reportable names)
976 where reportable (name,_)
977 | isWiredInName name = False -- Don't report unused wired-in names
978 -- Otherwise we get a zillion warnings
980 | otherwise = reportIfUnused (nameOccName name)
982 -------------------------
984 warnUnusedName :: (Name, Provenance) -> RnM ()
985 warnUnusedName (name, LocalDef)
986 = addUnusedWarning name (srcLocSpan (nameSrcLoc name))
987 (ptext SLIT("Defined but not used"))
989 warnUnusedName (name, Imported is)
992 warn spec = addUnusedWarning name span msg
994 span = importSpecLoc spec
995 pp_mod = quotes (ppr (importSpecModule spec))
996 msg = ptext SLIT("Imported from") <+> pp_mod <+> ptext SLIT("but not used")
998 addUnusedWarning name span msg
1001 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1002 <+> quotes (ppr name)]
1006 addNameClashErrRn rdr_name names
1007 = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1008 ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1011 msg1 = ptext SLIT("either") <+> mk_ref np1
1012 msgs = [ptext SLIT(" or") <+> mk_ref np | np <- nps]
1013 mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1015 shadowedNameWarn doc occ shadowed_locs
1016 = sep [ptext SLIT("This binding for") <+> quotes (ppr occ)
1017 <+> ptext SLIT("shadows the existing binding") <> plural shadowed_locs,
1018 nest 2 (vcat shadowed_locs)]
1021 unknownNameErr rdr_name
1022 = vcat [ hang (ptext SLIT("Not in scope:"))
1023 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1024 <+> quotes (ppr rdr_name))
1027 extra | rdr_name == forall_tv_RDR
1028 = ptext SLIT("Perhaps you intended to use -XRankNTypes or similar flag")
1031 unknownSubordinateErr doc op -- Doc is "method of class" or
1032 -- "field of constructor"
1033 = quotes (ppr op) <+> ptext SLIT("is not a (visible)") <+> doc
1036 = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1037 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1039 dupNamesErr :: Outputable n => (n -> SrcSpan) -> SDoc -> [n] -> RnM ()
1040 dupNamesErr get_loc descriptor names
1041 = addErrAt big_loc $
1042 vcat [ptext SLIT("Conflicting definitions for") <+> quotes (ppr (head names)),
1043 locations, descriptor]
1045 locs = map get_loc names
1046 big_loc = foldr1 combineSrcSpans locs
1047 one_line = isOneLineSpan big_loc
1048 locations | one_line = empty
1049 | otherwise = ptext SLIT("Bound at:") <+>
1050 vcat (map ppr (sortLe (<=) locs))
1052 badQualBndrErr rdr_name
1053 = ptext SLIT("Qualified name in binding position:") <+> ppr rdr_name