2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnMonad]{The monad used by the renamer}
10 module RdrName, -- Re-exports
11 module Name, -- from these two
24 #include "HsVersions.h"
28 import RnHsSyn ( RenamedFixitySig )
29 import HscTypes ( AvailEnv, emptyAvailEnv, lookupType,
31 ImportedModuleInfo, WhetherHasOrphans, ImportVersion,
32 PersistentRenamerState(..), RdrExportItem,
33 DeclsMap, IfaceInsts, IfaceRules,
34 HomeSymbolTable, TyThing,
35 PersistentCompilerState(..), GlobalRdrEnv,
37 HomeIfaceTable, PackageIfaceTable )
38 import BasicTypes ( Version, defaultFixity,
39 Fixity(..), FixityDirection(..) )
40 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
41 Message, Messages, errorsFound, warningsFound,
42 printErrorsAndWarnings
44 import RdrName ( RdrName, dummyRdrVarName, rdrNameModule, rdrNameOcc,
45 RdrNameEnv, emptyRdrEnv, extendRdrEnv,
46 addListToRdrEnv, rdrEnvToList, rdrEnvElts
50 import Name ( Name, OccName, NamedThing(..),
51 nameOccName, nameRdrName,
52 decode, mkInternalName
54 import NameEnv ( NameEnv, lookupNameEnv, emptyNameEnv,
56 import Module ( Module, ModuleName, ModuleSet, emptyModuleSet,
57 PackageName, preludePackage )
58 import PrelInfo ( ghcPrimExports,
59 cCallableClassDecl, cReturnableClassDecl, assertDecl )
60 import PrelNames ( mkUnboundName, gHC_PRIM_Name )
62 import CmdLineOpts ( DynFlags, DynFlag(..), dopt )
63 import SrcLoc ( SrcLoc, generatedSrcLoc, noSrcLoc )
64 import Unique ( Unique )
65 import FiniteMap ( FiniteMap )
66 import Maybes ( seqMaybe )
67 import Bag ( Bag, emptyBag, isEmptyBag, snocBag )
71 import IOExts ( IORef, newIORef, readIORef, writeIORef,
72 fixIO, unsafePerformIO )
73 import IO ( hPutStr, stderr )
75 infixr 9 `thenRn`, `thenRn_`
79 %************************************************************************
81 \subsection{Somewhat magical interface to other monads}
83 %************************************************************************
86 ioToRnM :: IO r -> RnM d (Either IOError r)
87 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
89 (\ err -> return (Left err))
91 ioToRnM_no_fail :: IO r -> RnM d r
92 ioToRnM_no_fail io rn_down g_down
93 = (io >>= \ ok -> return ok)
95 (\ err -> panic "ioToRnM_no_fail: the I/O operation failed!")
97 traceRn :: SDoc -> RnM d ()
98 traceRn msg = ifOptRn Opt_D_dump_rn_trace (putDocRn msg)
100 traceHiDiffsRn :: SDoc -> RnM d ()
101 traceHiDiffsRn msg = ifOptRn Opt_D_dump_hi_diffs (putDocRn msg)
103 putDocRn :: SDoc -> RnM d ()
104 putDocRn msg = ioToRnM (printErrs alwaysQualify msg) `thenRn_`
109 %************************************************************************
111 \subsection{Data types}
113 %************************************************************************
115 %===================================================
116 \subsubsection{ MONAD TYPES}
117 %===================================================
120 type RnM d r = RnDown -> d -> IO r
121 type RnMS r = RnM SDown r -- Renaming source
122 type RnMG r = RnM () r -- Getting global names etc
127 rn_mod :: Module, -- This module
128 rn_loc :: SrcLoc, -- Current locn
130 rn_dflags :: DynFlags,
132 rn_hit :: HomeIfaceTable,
133 rn_done :: Name -> Maybe TyThing, -- Tells what things (both in the
134 -- home package and other packages)
135 -- were already available (i.e. in
136 -- the relevant SymbolTable) before
137 -- compiling this module
138 -- The Name passed to rn_done is guaranteed to be a Global,
139 -- so it has a Module, so it can be looked up
141 rn_errs :: IORef Messages,
142 rn_ns :: IORef NameSupply,
143 rn_ifaces :: IORef Ifaces
146 -- For renaming source code
150 rn_genv :: GlobalRdrEnv, -- Top level environment
152 rn_avails :: AvailEnv,
153 -- Top level AvailEnv; contains all the things that
154 -- are nameable in the top-level scope, regardless of
155 -- *how* they can be named (qualified, unqualified...)
156 -- It is used only to map a Class to its class ops, and
157 -- hence to resolve the binders in an instance decl
159 rn_lenv :: LocalRdrEnv, -- Local name envt
160 -- Does *not* include global name envt; may shadow it
161 -- Includes both ordinary variables and type variables;
162 -- they are kept distinct because tyvar have a different
163 -- occurrence contructor (Name.TvOcc)
164 -- We still need the unsullied global name env so that
165 -- we can look up record field names
167 rn_fixenv :: LocalFixityEnv -- Local fixities (for non-top-level
169 -- The global fixities are held in the
170 -- HIT or PIT. Why? See the comments
171 -- with RnIfaces.lookupLocalFixity
174 data RnMode = SourceMode -- Renaming source code
175 | InterfaceMode -- Renaming interface declarations.
176 | CmdLineMode -- Renaming a command-line expression
178 isInterfaceMode InterfaceMode = True
179 isInterfaceMode _ = False
181 isCmdLineMode CmdLineMode = True
182 isCmdLineMode _ = False
186 type LocalFixityEnv = NameEnv RenamedFixitySig
187 -- We keep the whole fixity sig so that we
188 -- can report line-number info when there is a duplicate
189 -- fixity declaration
191 emptyLocalFixityEnv :: LocalFixityEnv
192 emptyLocalFixityEnv = emptyNameEnv
196 %************************************************************************
198 \subsection{Interface file stuff}
200 %************************************************************************
203 type IfaceDeprecs = Maybe (Either DeprecTxt [(RdrName,DeprecTxt)])
204 -- Nothing => NoDeprecs
205 -- Just (Left t) => DeprecAll
206 -- Just (Right p) => DeprecSome
210 pi_mod :: ModuleName,
211 pi_pkg :: PackageName,
212 pi_vers :: Version, -- Module version number
213 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
214 pi_usages :: [ImportVersion OccName], -- Usages
215 pi_exports :: (Version, [RdrExportItem]), -- Exports
216 pi_decls :: [(Version, RdrNameTyClDecl)], -- Local definitions
217 pi_fixity :: [(RdrName,Fixity)], -- Local fixity declarations,
218 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
219 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
220 pi_deprecs :: IfaceDeprecs -- Deprecations
224 %************************************************************************
226 \subsection{Wired-in interfaces}
228 %************************************************************************
231 ghcPrimIface :: ParsedIface
232 ghcPrimIface = ParsedIface {
233 pi_mod = gHC_PRIM_Name,
234 pi_pkg = preludePackage,
238 pi_exports = (1, [(gHC_PRIM_Name, ghcPrimExports)]),
239 pi_decls = [(1,cCallableClassDecl),
240 (1,cReturnableClassDecl),
242 pi_fixity = [(nameRdrName (idName seqId), Fixity 0 InfixR)],
250 %************************************************************************
252 \subsection{The renamer state}
254 %************************************************************************
257 data Ifaces = Ifaces {
259 iPIT :: PackageIfaceTable,
260 -- The ModuleIFaces for modules in other packages
261 -- whose interfaces we have opened
262 -- The declarations in these interface files are held in
263 -- iDecls, iInsts, iRules (below), not in the mi_decls fields
264 -- of the iPIT. What _is_ in the iPIT is:
270 -- The iPIT field is initialised from the compiler's persistent
271 -- package symbol table, and the renamer incrementally adds
274 iImpModInfo :: ImportedModuleInfo,
275 -- Modules that we know something about, because they are mentioned
276 -- in interface files, BUT which we have not loaded yet.
277 -- No module is both in here and in the PIT
280 -- A single, global map of Names to unslurped decls
282 iInsts :: IfaceInsts,
283 -- The as-yet un-slurped instance decls; this bag is depleted when we
284 -- slurp an instance decl so that we don't slurp the same one twice.
285 -- Each is 'gated' by the names that must be available before
286 -- this instance decl is needed.
288 iRules :: IfaceRules,
289 -- Similar to instance decls, only for rules
292 -- These fields persist during the compilation of a single module only
294 -- All the names (whether "big" or "small", whether wired-in or not,
295 -- whether locally defined or not) that have been slurped in so far.
297 -- It's used for two things:
298 -- a) To record what we've already slurped, so
299 -- we can no-op if we try to slurp it again
300 -- b) As the 'gates' for importing rules. We import a rule
301 -- if all its LHS free vars have been slurped
303 iVSlurp :: (ModuleSet, NameSet)
304 -- The Names are all the (a) non-wired-in
306 -- (c) non-locally-defined
308 -- names that have been slurped in so far, with their versions.
309 -- This is used to generate the "usage" information for this module.
310 -- Subset of the previous field.
312 -- The module set is the non-home-package modules from which we have
313 -- slurped at least one name.
314 -- It's worth keeping separately, because there's no very easy
315 -- way to distinguish the "big" names from the "non-big" ones.
316 -- But this is a decision we might want to revisit.
321 %************************************************************************
323 \subsection{Main monad code}
325 %************************************************************************
328 runRn dflags hit hst pcs mod do_rn
329 = do { (pcs, msgs, r) <- initRn dflags hit hst pcs mod do_rn ;
330 printErrorsAndWarnings alwaysQualify msgs ;
331 return (pcs, errorsFound msgs, r)
335 -> HomeIfaceTable -> HomeSymbolTable
336 -> PersistentCompilerState
339 -> IO (PersistentCompilerState, Messages, t)
341 initRn dflags hit hst pcs mod do_rn
343 let prs = pcs_PRS pcs
344 let pte = pcs_PTE pcs
345 let ifaces = Ifaces { iPIT = pcs_PIT pcs,
346 iDecls = prsDecls prs,
347 iInsts = prsInsts prs,
348 iRules = prsRules prs,
350 iImpModInfo = prsImpMods prs,
351 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
352 -- Pretend that the dummy unbound name has already been
353 -- slurped. This is what's returned for an out-of-scope name,
354 -- and we don't want thereby to try to suck it in!
355 iVSlurp = (emptyModuleSet, emptyNameSet)
357 names_var <- newIORef (prsOrig prs)
358 errs_var <- newIORef (emptyBag,emptyBag)
359 iface_var <- newIORef ifaces
360 let rn_down = RnDown { rn_mod = mod,
365 rn_done = lookupType hst pte,
369 rn_ifaces = iface_var,
373 res <- do_rn rn_down ()
375 -- Grab state and record it
376 (warns, errs) <- readIORef errs_var
377 new_ifaces <- readIORef iface_var
378 new_orig <- readIORef names_var
379 let new_prs = prs { prsOrig = new_orig,
380 prsImpMods = iImpModInfo new_ifaces,
381 prsDecls = iDecls new_ifaces,
382 prsInsts = iInsts new_ifaces,
383 prsRules = iRules new_ifaces }
384 let new_pcs = pcs { pcs_PIT = iPIT new_ifaces,
387 return (new_pcs, (warns, errs), res)
389 initRnMS :: GlobalRdrEnv -> AvailEnv -> LocalRdrEnv -> LocalFixityEnv -> RnMode
392 initRnMS rn_env avails local_env fixity_env mode thing_inside rn_down g_down
393 -- The fixity_env appears in both the rn_fixenv field
394 -- and in the HIT. See comments with RnHiFiles.lookupFixityRn
396 s_down = SDown { rn_genv = rn_env, rn_avails = avails,
397 rn_lenv = local_env, rn_fixenv = fixity_env,
400 thing_inside rn_down s_down
402 initIfaceRnMS :: Module -> RnMS r -> RnM d r
403 initIfaceRnMS mod thing_inside
404 = initRnMS emptyRdrEnv emptyAvailEnv emptyRdrEnv
405 emptyLocalFixityEnv InterfaceMode
406 (setModuleRn mod thing_inside)
409 @renameDerivedCode@ is used to rename stuff ``out-of-line'';
410 that is, not as part of the main renamer.
411 Sole examples: derived definitions,
412 which are only generated in the type checker.
414 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
415 once you must either split it, or install a fresh unique supply.
418 renameDerivedCode :: DynFlags
420 -> PersistentRenamerState
424 renameDerivedCode dflags mod prs thing_inside
426 -- It's not really unsafe! When renaming source code we
427 -- only do any I/O if we need to read in a fixity declaration;
428 -- and that doesn't happen in pragmas etc
430 do { us <- mkSplitUniqSupply 'r'
431 ; names_var <- newIORef ((prsOrig prs) { nsUniqs = us })
432 ; errs_var <- newIORef (emptyBag,emptyBag)
434 ; let rn_down = RnDown { rn_dflags = dflags,
435 rn_loc = generatedSrcLoc, rn_ns = names_var,
438 rn_done = bogus "rn_done",
439 rn_hit = bogus "rn_hit",
440 rn_ifaces = bogus "rn_ifaces"
442 ; let s_down = SDown { rn_mode = InterfaceMode,
443 -- So that we can refer to PrelBase.True etc
444 rn_avails = emptyAvailEnv,
445 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
446 rn_fixenv = emptyLocalFixityEnv }
448 ; result <- thing_inside rn_down s_down
449 ; messages <- readIORef errs_var
451 ; if bad messages then
452 do { hPutStr stderr "Urk! renameDerivedCode found errors or warnings"
453 ; printErrorsAndWarnings alwaysQualify messages
462 bad messages = errorsFound messages || warningsFound messages
464 bad messages = errorsFound messages
467 bogus s = panic ("rnameSourceCode: " ++ s) -- Used for unused record fields
469 {-# INLINE thenRn #-}
470 {-# INLINE thenRn_ #-}
471 {-# INLINE returnRn #-}
474 returnRn :: a -> RnM d a
475 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
476 thenRn_ :: RnM d a -> RnM d b -> RnM d b
477 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
478 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
479 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
480 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
481 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
482 sequenceRn :: [RnM d a] -> RnM d [a]
483 sequenceRn_ :: [RnM d a] -> RnM d ()
484 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
485 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
486 fixRn :: (a -> RnM d a) -> RnM d a
488 returnRn v gdown ldown = return v
489 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
490 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
491 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
492 andRn combiner m1 m2 gdown ldown
493 = m1 gdown ldown >>= \ res1 ->
494 m2 gdown ldown >>= \ res2 ->
495 return (combiner res1 res2)
497 sequenceRn [] = returnRn []
498 sequenceRn (m:ms) = m `thenRn` \ r ->
499 sequenceRn ms `thenRn` \ rs ->
502 sequenceRn_ [] = returnRn ()
503 sequenceRn_ (m:ms) = m `thenRn_` sequenceRn_ ms
505 mapRn f [] = returnRn []
507 = f x `thenRn` \ r ->
508 mapRn f xs `thenRn` \ rs ->
511 mapRn_ f [] = returnRn ()
516 foldlRn k z [] = returnRn z
517 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
520 mapAndUnzipRn f [] = returnRn ([],[])
521 mapAndUnzipRn f (x:xs)
522 = f x `thenRn` \ (r1, r2) ->
523 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
524 returnRn (r1:rs1, r2:rs2)
526 mapAndUnzip3Rn f [] = returnRn ([],[],[])
527 mapAndUnzip3Rn f (x:xs)
528 = f x `thenRn` \ (r1, r2, r3) ->
529 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
530 returnRn (r1:rs1, r2:rs2, r3:rs3)
532 mapMaybeRn f [] = returnRn []
533 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
534 mapMaybeRn f xs `thenRn` \ rs ->
536 Nothing -> returnRn rs
537 Just r -> returnRn (r:rs)
539 flatMapRn f [] = returnRn []
540 flatMapRn f (x:xs) = f x `thenRn` \ r ->
541 flatMapRn f xs `thenRn` \ rs ->
547 %************************************************************************
549 \subsection{Boring plumbing for common part}
551 %************************************************************************
555 \subsubsection{ Errors and warnings}
556 %=====================
559 failWithRn :: a -> Message -> RnM d a
560 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
561 = readIORef errs_var >>= \ (warns,errs) ->
562 writeIORef errs_var (warns, errs `snocBag` err) >>
565 err = addShortErrLocLine loc msg
567 warnWithRn :: a -> Message -> RnM d a
568 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
569 = readIORef errs_var >>= \ (warns,errs) ->
570 writeIORef errs_var (warns `snocBag` warn, errs) >>
573 warn = addShortWarnLocLine loc msg
575 tryRn :: RnM d a -> RnM d (Either Messages a)
576 tryRn try_this down@(RnDown {rn_errs = errs_var}) l_down
577 = do current_msgs <- readIORef errs_var
578 writeIORef errs_var (emptyBag,emptyBag)
579 a <- try_this down l_down
580 (warns, errs) <- readIORef errs_var
581 writeIORef errs_var current_msgs
583 then return (Right a)
584 else return (Left (warns,errs))
586 setErrsRn :: Messages -> RnM d ()
587 setErrsRn msgs down@(RnDown {rn_errs = errs_var}) l_down
588 = do writeIORef errs_var msgs; return ()
590 addErrRn :: Message -> RnM d ()
591 addErrRn err = failWithRn () err
593 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
594 checkRn False err = addErrRn err
595 checkRn True err = returnRn ()
597 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
598 warnCheckRn False err = addWarnRn err
599 warnCheckRn True err = returnRn ()
601 addWarnRn :: Message -> RnM d ()
602 addWarnRn warn = warnWithRn () warn
604 checkErrsRn :: RnM d Bool -- True <=> no errors so far
605 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
606 = readIORef errs_var >>= \ (warns,errs) ->
607 return (isEmptyBag errs)
609 doptRn :: DynFlag -> RnM d Bool
610 doptRn dflag (RnDown { rn_dflags = dflags}) l_down
611 = return (dopt dflag dflags)
613 ifOptRn :: DynFlag -> RnM d a -> RnM d ()
614 ifOptRn dflag thing_inside down@(RnDown { rn_dflags = dflags}) l_down
615 | dopt dflag dflags = thing_inside down l_down >> return ()
616 | otherwise = return ()
618 getDOptsRn :: RnM d DynFlags
619 getDOptsRn (RnDown { rn_dflags = dflags}) l_down
625 \subsubsection{Source location}
626 %=====================
629 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
630 pushSrcLocRn loc' m down l_down
631 = m (down {rn_loc = loc'}) l_down
633 getSrcLocRn :: RnM d SrcLoc
634 getSrcLocRn down l_down
635 = return (rn_loc down)
639 \subsubsection{The finder and home symbol table}
640 %=====================
643 getHomeIfaceTableRn :: RnM d HomeIfaceTable
644 getHomeIfaceTableRn down l_down = return (rn_hit down)
646 getTypeEnvRn :: RnM d (Name -> Maybe TyThing)
647 getTypeEnvRn down l_down = return (rn_done down)
649 extendTypeEnvRn :: NameEnv TyThing -> RnM d a -> RnM d a
650 extendTypeEnvRn env inside down l_down
651 = inside down{rn_done=new_rn_done} l_down
652 where new_rn_done = \nm -> lookupNameEnv env nm `seqMaybe` rn_done down nm
656 \subsubsection{Name supply}
657 %=====================
660 getNameSupplyRn :: RnM d NameSupply
661 getNameSupplyRn rn_down l_down
662 = readIORef (rn_ns rn_down)
664 setNameSupplyRn :: NameSupply -> RnM d ()
665 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
666 = writeIORef names_var names'
668 getUniqRn :: RnM d Unique
669 getUniqRn (RnDown {rn_ns = names_var}) l_down
670 = readIORef names_var >>= \ ns ->
672 (us1,us') = splitUniqSupply (nsUniqs ns)
674 writeIORef names_var (ns {nsUniqs = us'}) >>
675 return (uniqFromSupply us1)
679 \subsubsection{ Module}
680 %=====================
683 getModuleRn :: RnM d Module
684 getModuleRn (RnDown {rn_mod = mod}) l_down
687 setModuleRn :: Module -> RnM d a -> RnM d a
688 setModuleRn new_mod enclosed_thing rn_down l_down
689 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
693 %************************************************************************
695 \subsection{Plumbing for rename-source part}
697 %************************************************************************
700 \subsubsection{ RnEnv}
701 %=====================
704 getLocalNameEnv :: RnMS LocalRdrEnv
705 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
708 getGlobalNameEnv :: RnMS GlobalRdrEnv
709 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
712 getGlobalAvails :: RnMS AvailEnv
713 getGlobalAvails rn_down (SDown {rn_avails = avails})
716 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
717 setLocalNameEnv local_env' m rn_down l_down
718 = m rn_down (l_down {rn_lenv = local_env'})
720 getFixityEnv :: RnMS LocalFixityEnv
721 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
724 setFixityEnv :: LocalFixityEnv -> RnMS a -> RnMS a
725 setFixityEnv fixes enclosed_scope rn_down l_down
726 = enclosed_scope rn_down (l_down {rn_fixenv = fixes})
730 \subsubsection{ Mode}
731 %=====================
734 getModeRn :: RnMS RnMode
735 getModeRn rn_down (SDown {rn_mode = mode})
738 setModeRn :: RnMode -> RnMS a -> RnMS a
739 setModeRn new_mode thing_inside rn_down l_down
740 = thing_inside rn_down (l_down {rn_mode = new_mode})
744 %************************************************************************
746 \subsection{Plumbing for rename-globals part}
748 %************************************************************************
751 getIfacesRn :: RnM d Ifaces
752 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
753 = readIORef iface_var
755 setIfacesRn :: Ifaces -> RnM d ()
756 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
757 = writeIORef iface_var ifaces