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"
26 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 405
27 import IOExts ( fixIO )
28 #elif defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 302
29 import PrelIOBase ( fixIO ) -- Should be in GlaExts
31 import IOBase ( fixIO )
33 import IOExts ( IORef, newIORef, readIORef, writeIORef, unsafePerformIO )
34 import IO ( hPutStr, stderr )
38 import RnHsSyn ( RenamedFixitySig )
39 import HscTypes ( AvailEnv, lookupType,
41 WhetherHasOrphans, ImportVersion,
42 PersistentRenamerState(..), IsBootInterface, Avails,
43 DeclsMap, IfaceInsts, IfaceRules,
44 HomeSymbolTable, TyThing,
45 PersistentCompilerState(..), GlobalRdrEnv,
46 HomeIfaceTable, PackageIfaceTable,
48 import BasicTypes ( Version, defaultFixity )
49 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
50 Message, Messages, errorsFound, warningsFound,
51 printErrorsAndWarnings
53 import RdrName ( RdrName, dummyRdrVarName, rdrNameModule, rdrNameOcc,
54 RdrNameEnv, emptyRdrEnv, extendRdrEnv,
55 addListToRdrEnv, rdrEnvToList, rdrEnvElts
57 import Name ( Name, OccName, NamedThing(..),
59 decode, mkLocalName, mkKnownKeyGlobal
61 import Name ( NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv, extendNameEnvList )
62 import Module ( Module, ModuleName, ModuleSet, emptyModuleSet )
64 import CmdLineOpts ( DynFlags, DynFlag(..), dopt )
65 import SrcLoc ( SrcLoc, generatedSrcLoc, noSrcLoc )
66 import Unique ( Unique )
67 import FiniteMap ( FiniteMap, emptyFM )
68 import Bag ( Bag, emptyBag, isEmptyBag, snocBag )
71 import PrelNames ( mkUnboundName )
73 infixr 9 `thenRn`, `thenRn_`
77 %************************************************************************
79 \subsection{Somewhat magical interface to other monads}
81 %************************************************************************
84 ioToRnM :: IO r -> RnM d (Either IOError r)
85 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
87 (\ err -> return (Left err))
89 ioToRnM_no_fail :: IO r -> RnM d r
90 ioToRnM_no_fail io rn_down g_down
91 = (io >>= \ ok -> return ok)
93 (\ err -> panic "ioToRnM_no_fail: the I/O operation failed!")
95 traceRn :: SDoc -> RnM d ()
97 = doptRn Opt_D_dump_rn_trace `thenRn` \b ->
98 if b then putDocRn msg else returnRn ()
100 traceHiDiffsRn :: SDoc -> RnM d ()
102 = doptRn Opt_D_dump_hi_diffs `thenRn` \b ->
103 if b then putDocRn msg else returnRn ()
105 putDocRn :: SDoc -> RnM d ()
106 putDocRn msg = ioToRnM (printErrs alwaysQualify msg) `thenRn_`
111 %************************************************************************
113 \subsection{Data types}
115 %************************************************************************
117 %===================================================
118 \subsubsection{ MONAD TYPES}
119 %===================================================
122 type RnM d r = RnDown -> d -> IO r
123 type RnMS r = RnM SDown r -- Renaming source
124 type RnMG r = RnM () r -- Getting global names etc
129 rn_mod :: Module, -- This module
130 rn_loc :: SrcLoc, -- Current locn
132 rn_dflags :: DynFlags,
134 rn_hit :: HomeIfaceTable,
135 rn_done :: Name -> Maybe TyThing, -- Tells what things (both in the
136 -- home package and other packages)
137 -- were already available (i.e. in
138 -- the relevant SymbolTable) before
139 -- compiling this module
140 -- The Name passed to rn_done is guaranteed to be a Global,
141 -- so it has a Module, so it can be looked up
143 rn_errs :: IORef Messages,
144 rn_ns :: IORef NameSupply,
145 rn_ifaces :: IORef Ifaces
148 -- For renaming source code
152 rn_genv :: GlobalRdrEnv, -- Top level environment
154 rn_lenv :: LocalRdrEnv, -- Local name envt
155 -- Does *not* include global name envt; may shadow it
156 -- Includes both ordinary variables and type variables;
157 -- they are kept distinct because tyvar have a different
158 -- occurrence contructor (Name.TvOcc)
159 -- We still need the unsullied global name env so that
160 -- we can look up record field names
162 rn_fixenv :: LocalFixityEnv -- Local fixities (for non-top-level
164 -- The global fixities are held in the
165 -- HIT or PIT. Why? See the comments
166 -- with RnIfaces.lookupLocalFixity
169 data RnMode = SourceMode -- Renaming source code
170 | InterfaceMode -- Renaming interface declarations.
173 %===================================================
174 \subsubsection{ ENVIRONMENTS}
175 %===================================================
178 --------------------------------
179 type LocalRdrEnv = RdrNameEnv Name
180 type LocalFixityEnv = NameEnv RenamedFixitySig
181 -- We keep the whole fixity sig so that we
182 -- can report line-number info when there is a duplicate
183 -- fixity declaration
185 emptyLocalFixityEnv :: LocalFixityEnv
186 emptyLocalFixityEnv = emptyNameEnv
188 lookupLocalFixity :: LocalFixityEnv -> Name -> Fixity
189 lookupLocalFixity env name
190 = case lookupNameEnv env name of
191 Just (FixitySig _ fix _) -> fix
192 Nothing -> defaultFixity
196 type ExportAvails = (FiniteMap ModuleName Avails,
197 -- Used to figure out "module M" export specifiers
198 -- Includes avails only from *unqualified* imports
199 -- (see 1.4 Report Section 5.1.1)
201 AvailEnv) -- Used to figure out all other export specifiers.
204 %===================================================
205 \subsubsection{ INTERFACE FILE STUFF}
206 %===================================================
209 type ExportItem = (ModuleName, [RdrAvailInfo])
210 type IfaceDeprecs = Maybe (Either DeprecTxt [(RdrName,DeprecTxt)])
211 -- Nothing => NoDeprecs
212 -- Just (Left t) => DeprecAll
213 -- Just (Right p) => DeprecSome
217 pi_mod :: Module, -- Complete with package info
218 pi_vers :: Version, -- Module version number
219 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
220 pi_usages :: [ImportVersion OccName], -- Usages
221 pi_exports :: (Version, [ExportItem]), -- Exports
222 pi_decls :: [(Version, RdrNameTyClDecl)], -- Local definitions
223 pi_fixity :: [RdrNameFixitySig], -- Local fixity declarations,
224 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
225 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
226 pi_deprecs :: IfaceDeprecs -- Deprecations
230 %************************************************************************
232 \subsection{The renamer state}
234 %************************************************************************
237 data Ifaces = Ifaces {
239 iPIT :: PackageIfaceTable,
240 -- The ModuleIFaces for modules in other packages
241 -- whose interfaces we have opened
242 -- The declarations in these interface files are held in
243 -- iDecls, iInsts, iRules (below), not in the mi_decls fields
244 -- of the iPIT. What _is_ in the iPIT is:
250 -- The iPIT field is initialised from the compiler's persistent
251 -- package symbol table, and the renamer incrementally adds
255 -- A single, global map of Names to unslurped decls
257 iInsts :: IfaceInsts,
258 -- The as-yet un-slurped instance decls; this bag is depleted when we
259 -- slurp an instance decl so that we don't slurp the same one twice.
260 -- Each is 'gated' by the names that must be available before
261 -- this instance decl is needed.
263 iRules :: IfaceRules,
264 -- Similar to instance decls, only for rules
267 -- These fields persist during the compilation of a single module only
268 iImpModInfo :: ImportedModuleInfo,
269 -- Modules that we know something about, because they are mentioned
270 -- in interface files, BUT which we have not loaded yet.
271 -- No module is both in here and in the PIT
274 -- All the names (whether "big" or "small", whether wired-in or not,
275 -- whether locally defined or not) that have been slurped in so far.
277 iVSlurp :: (ModuleSet, NameSet)
278 -- The Names are all the (a) non-wired-in
280 -- (c) non-locally-defined
282 -- names that have been slurped in so far, with their versions.
283 -- This is used to generate the "usage" information for this module.
284 -- Subset of the previous field.
285 -- The module set is the non-home-package modules from which we have
286 -- slurped at least one name.
287 -- It's worth keeping separately, because there's no very easy
288 -- way to distinguish the "big" names from the "non-big" ones.
289 -- But this is a decision we might want to revisit.
292 type ImportedModuleInfo = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface)
293 -- Contains info ONLY about modules that have not yet
294 --- been loaded into the iPIT
298 %************************************************************************
300 \subsection{Main monad code}
302 %************************************************************************
305 runRn dflags hit hst pcs mod do_rn
306 = do { (pcs, msgs, r) <- initRn dflags hit hst pcs mod do_rn ;
307 printErrorsAndWarnings alwaysQualify msgs ;
308 return (pcs, errorsFound msgs, r)
312 -> HomeIfaceTable -> HomeSymbolTable
313 -> PersistentCompilerState
316 -> IO (PersistentCompilerState, Messages, t)
318 initRn dflags hit hst pcs mod do_rn
320 let prs = pcs_PRS pcs
321 let pte = pcs_PTE pcs
322 let ifaces = Ifaces { iPIT = pcs_PIT pcs,
323 iDecls = prsDecls prs,
324 iInsts = prsInsts prs,
325 iRules = prsRules prs,
327 iImpModInfo = emptyFM,
328 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
329 -- Pretend that the dummy unbound name has already been
330 -- slurped. This is what's returned for an out-of-scope name,
331 -- and we don't want thereby to try to suck it in!
332 iVSlurp = (emptyModuleSet, emptyNameSet)
334 names_var <- newIORef (prsOrig prs)
335 errs_var <- newIORef (emptyBag,emptyBag)
336 iface_var <- newIORef ifaces
337 let rn_down = RnDown { rn_mod = mod,
342 rn_done = lookupType hst pte,
346 rn_ifaces = iface_var,
350 res <- do_rn rn_down ()
352 -- Grab state and record it
353 (warns, errs) <- readIORef errs_var
354 new_ifaces <- readIORef iface_var
355 new_orig <- readIORef names_var
356 let new_prs = prs { prsOrig = new_orig,
357 prsDecls = iDecls new_ifaces,
358 prsInsts = iInsts new_ifaces,
359 prsRules = iRules new_ifaces }
360 let new_pcs = pcs { pcs_PIT = iPIT new_ifaces,
363 return (new_pcs, (warns, errs), res)
365 initRnMS :: GlobalRdrEnv -> LocalFixityEnv -> RnMode
368 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
369 -- The fixity_env appears in both the rn_fixenv field
370 -- and in the HIT. See comments with RnHiFiles.lookupFixityRn
372 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
373 rn_fixenv = fixity_env, rn_mode = mode }
375 thing_inside rn_down s_down
377 initIfaceRnMS :: Module -> RnMS r -> RnM d r
378 initIfaceRnMS mod thing_inside
379 = initRnMS emptyRdrEnv emptyLocalFixityEnv InterfaceMode $
380 setModuleRn mod thing_inside
383 @renameDerivedCode@ is used to rename stuff ``out-of-line'';
384 that is, not as part of the main renamer.
385 Sole examples: derived definitions,
386 which are only generated in the type checker.
388 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
389 once you must either split it, or install a fresh unique supply.
392 renameDerivedCode :: DynFlags
394 -> PersistentRenamerState
398 renameDerivedCode dflags mod prs thing_inside
400 -- It's not really unsafe! When renaming source code we
401 -- only do any I/O if we need to read in a fixity declaration;
402 -- and that doesn't happen in pragmas etc
404 do { us <- mkSplitUniqSupply 'r'
405 ; names_var <- newIORef ((prsOrig prs) { nsUniqs = us })
406 ; errs_var <- newIORef (emptyBag,emptyBag)
408 ; let rn_down = RnDown { rn_dflags = dflags,
409 rn_loc = generatedSrcLoc, rn_ns = names_var,
412 rn_done = bogus "rn_done",
413 rn_hit = bogus "rn_hit",
414 rn_ifaces = bogus "rn_ifaces"
416 ; let s_down = SDown { rn_mode = InterfaceMode,
417 -- So that we can refer to PrelBase.True etc
418 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
419 rn_fixenv = emptyLocalFixityEnv }
421 ; result <- thing_inside rn_down s_down
422 ; messages <- readIORef errs_var
424 ; if bad messages then
425 do { hPutStr stderr "Urk! renameDerivedCode found errors or warnings"
426 ; printErrorsAndWarnings alwaysQualify messages
435 bad messages = errorsFound messages || warningsFound messages
437 bad messages = errorsFound messages
440 bogus s = panic ("rnameSourceCode: " ++ s) -- Used for unused record fields
442 {-# INLINE thenRn #-}
443 {-# INLINE thenRn_ #-}
444 {-# INLINE returnRn #-}
447 returnRn :: a -> RnM d a
448 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
449 thenRn_ :: RnM d a -> RnM d b -> RnM d b
450 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
451 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
452 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
453 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
454 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
455 sequenceRn :: [RnM d a] -> RnM d [a]
456 sequenceRn_ :: [RnM d a] -> RnM d ()
457 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
458 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
459 fixRn :: (a -> RnM d a) -> RnM d a
461 returnRn v gdown ldown = return v
462 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
463 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
464 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
465 andRn combiner m1 m2 gdown ldown
466 = m1 gdown ldown >>= \ res1 ->
467 m2 gdown ldown >>= \ res2 ->
468 return (combiner res1 res2)
470 sequenceRn [] = returnRn []
471 sequenceRn (m:ms) = m `thenRn` \ r ->
472 sequenceRn ms `thenRn` \ rs ->
475 sequenceRn_ [] = returnRn ()
476 sequenceRn_ (m:ms) = m `thenRn_` sequenceRn_ ms
478 mapRn f [] = returnRn []
480 = f x `thenRn` \ r ->
481 mapRn f xs `thenRn` \ rs ->
484 mapRn_ f [] = returnRn ()
489 foldlRn k z [] = returnRn z
490 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
493 mapAndUnzipRn f [] = returnRn ([],[])
494 mapAndUnzipRn f (x:xs)
495 = f x `thenRn` \ (r1, r2) ->
496 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
497 returnRn (r1:rs1, r2:rs2)
499 mapAndUnzip3Rn f [] = returnRn ([],[],[])
500 mapAndUnzip3Rn f (x:xs)
501 = f x `thenRn` \ (r1, r2, r3) ->
502 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
503 returnRn (r1:rs1, r2:rs2, r3:rs3)
505 mapMaybeRn f [] = returnRn []
506 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
507 mapMaybeRn f xs `thenRn` \ rs ->
509 Nothing -> returnRn rs
510 Just r -> returnRn (r:rs)
512 flatMapRn f [] = returnRn []
513 flatMapRn f (x:xs) = f x `thenRn` \ r ->
514 flatMapRn f xs `thenRn` \ rs ->
520 %************************************************************************
522 \subsection{Boring plumbing for common part}
524 %************************************************************************
528 \subsubsection{ Errors and warnings}
529 %=====================
532 failWithRn :: a -> Message -> RnM d a
533 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
534 = readIORef errs_var >>= \ (warns,errs) ->
535 writeIORef errs_var (warns, errs `snocBag` err) >>
538 err = addShortErrLocLine loc msg
540 warnWithRn :: a -> Message -> RnM d a
541 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
542 = readIORef errs_var >>= \ (warns,errs) ->
543 writeIORef errs_var (warns `snocBag` warn, errs) >>
546 warn = addShortWarnLocLine loc msg
548 addErrRn :: Message -> RnM d ()
549 addErrRn err = failWithRn () err
551 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
552 checkRn False err = addErrRn err
553 checkRn True err = returnRn ()
555 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
556 warnCheckRn False err = addWarnRn err
557 warnCheckRn True err = returnRn ()
559 addWarnRn :: Message -> RnM d ()
560 addWarnRn warn = warnWithRn () warn
562 checkErrsRn :: RnM d Bool -- True <=> no errors so far
563 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
564 = readIORef errs_var >>= \ (warns,errs) ->
565 return (isEmptyBag errs)
567 doptRn :: DynFlag -> RnM d Bool
568 doptRn dflag (RnDown { rn_dflags = dflags}) l_down
569 = return (dopt dflag dflags)
571 getDOptsRn :: RnM d DynFlags
572 getDOptsRn (RnDown { rn_dflags = dflags}) l_down
578 \subsubsection{Source location}
579 %=====================
582 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
583 pushSrcLocRn loc' m down l_down
584 = m (down {rn_loc = loc'}) l_down
586 getSrcLocRn :: RnM d SrcLoc
587 getSrcLocRn down l_down
588 = return (rn_loc down)
592 \subsubsection{The finder and home symbol table}
593 %=====================
596 getHomeIfaceTableRn :: RnM d HomeIfaceTable
597 getHomeIfaceTableRn down l_down = return (rn_hit down)
599 getTypeEnvRn :: RnM d (Name -> Maybe TyThing)
600 getTypeEnvRn down l_down = return (rn_done down)
604 \subsubsection{Name supply}
605 %=====================
608 getNameSupplyRn :: RnM d NameSupply
609 getNameSupplyRn rn_down l_down
610 = readIORef (rn_ns rn_down)
612 setNameSupplyRn :: NameSupply -> RnM d ()
613 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
614 = writeIORef names_var names'
616 getUniqRn :: RnM d Unique
617 getUniqRn (RnDown {rn_ns = names_var}) l_down
618 = readIORef names_var >>= \ ns ->
620 (us1,us') = splitUniqSupply (nsUniqs ns)
622 writeIORef names_var (ns {nsUniqs = us'}) >>
623 return (uniqFromSupply us1)
627 \subsubsection{ Module}
628 %=====================
631 getModuleRn :: RnM d Module
632 getModuleRn (RnDown {rn_mod = mod}) l_down
635 setModuleRn :: Module -> RnM d a -> RnM d a
636 setModuleRn new_mod enclosed_thing rn_down l_down
637 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
641 %************************************************************************
643 \subsection{Plumbing for rename-source part}
645 %************************************************************************
648 \subsubsection{ RnEnv}
649 %=====================
652 getLocalNameEnv :: RnMS LocalRdrEnv
653 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
656 getGlobalNameEnv :: RnMS GlobalRdrEnv
657 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
660 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
661 setLocalNameEnv local_env' m rn_down l_down
662 = m rn_down (l_down {rn_lenv = local_env'})
664 getFixityEnv :: RnMS LocalFixityEnv
665 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
668 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
669 extendFixityEnv fixes enclosed_scope
670 rn_down l_down@(SDown {rn_fixenv = fixity_env})
672 new_fixity_env = extendNameEnvList fixity_env fixes
674 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
678 \subsubsection{ Mode}
679 %=====================
682 getModeRn :: RnMS RnMode
683 getModeRn rn_down (SDown {rn_mode = mode})
686 setModeRn :: RnMode -> RnMS a -> RnMS a
687 setModeRn new_mode thing_inside rn_down l_down
688 = thing_inside rn_down (l_down {rn_mode = new_mode})
692 %************************************************************************
694 \subsection{Plumbing for rename-globals part}
696 %************************************************************************
699 getIfacesRn :: RnM d Ifaces
700 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
701 = readIORef iface_var
703 setIfacesRn :: Ifaces -> RnM d ()
704 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
705 = writeIORef iface_var ifaces