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 )
37 import RnHsSyn ( RenamedFixitySig )
38 import HscTypes ( AvailEnv, lookupType,
39 OrigNameEnv(..), OrigNameNameEnv, OrigNameIParamEnv,
40 WhetherHasOrphans, ImportVersion,
41 PersistentRenamerState(..), IsBootInterface, Avails,
42 DeclsMap, IfaceInsts, IfaceRules,
43 HomeSymbolTable, PackageTypeEnv,
44 PersistentCompilerState(..), GlobalRdrEnv,
45 HomeIfaceTable, PackageIfaceTable,
47 import BasicTypes ( Version, defaultFixity )
48 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
49 pprBagOfErrors, ErrMsg, WarnMsg, Message
51 import RdrName ( RdrName, dummyRdrVarName, rdrNameModule, rdrNameOcc,
52 RdrNameEnv, emptyRdrEnv, extendRdrEnv,
53 addListToRdrEnv, rdrEnvToList, rdrEnvElts
55 import Name ( Name, OccName, NamedThing(..), getSrcLoc,
57 decode, mkLocalName, mkKnownKeyGlobal,
58 NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv,
61 import Module ( Module, ModuleName, ModuleSet, emptyModuleSet )
63 import CmdLineOpts ( DynFlags, DynFlag(..), dopt )
64 import SrcLoc ( SrcLoc, generatedSrcLoc, noSrcLoc )
65 import Unique ( Unique )
66 import FiniteMap ( FiniteMap, emptyFM )
67 import Bag ( Bag, emptyBag, isEmptyBag, snocBag )
70 import PrelNames ( mkUnboundName )
71 import Maybes ( maybeToBool )
72 import ErrUtils ( printErrorsAndWarnings )
74 infixr 9 `thenRn`, `thenRn_`
78 %************************************************************************
80 \subsection{Somewhat magical interface to other monads}
82 %************************************************************************
85 ioToRnM :: IO r -> RnM d (Either IOError r)
86 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
88 (\ err -> return (Left err))
90 ioToRnM_no_fail :: IO r -> RnM d r
91 ioToRnM_no_fail io rn_down g_down
92 = (io >>= \ ok -> return ok)
94 (\ err -> panic "ioToRnM_no_fail: the I/O operation failed!")
96 traceRn :: SDoc -> RnM d ()
98 = doptRn Opt_D_dump_rn_trace `thenRn` \b ->
99 if b then putDocRn msg else returnRn ()
101 putDocRn :: SDoc -> RnM d ()
102 putDocRn msg = ioToRnM (printErrs msg) `thenRn_`
107 %************************************************************************
109 \subsection{Data types}
111 %************************************************************************
113 %===================================================
114 \subsubsection{ MONAD TYPES}
115 %===================================================
118 type RnM d r = RnDown -> d -> IO r
119 type RnMS r = RnM SDown r -- Renaming source
120 type RnMG r = RnM () r -- Getting global names etc
125 rn_mod :: Module, -- This module
126 rn_loc :: SrcLoc, -- Current locn
128 rn_dflags :: DynFlags,
130 rn_hit :: HomeIfaceTable,
131 rn_done :: Name -> Bool, -- Tells what things (both in the
132 -- home package and other packages)
133 -- were already available (i.e. in
134 -- the relevant SymbolTable) before
135 -- compiling this module
137 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
139 -- The second and third components are a flattened-out OrigNameEnv
140 rn_ns :: IORef (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv),
141 rn_ifaces :: IORef Ifaces
144 -- For renaming source code
148 rn_genv :: GlobalRdrEnv, -- Top level environment
150 rn_lenv :: LocalRdrEnv, -- Local name envt
151 -- Does *not* include global name envt; may shadow it
152 -- Includes both ordinary variables and type variables;
153 -- they are kept distinct because tyvar have a different
154 -- occurrence contructor (Name.TvOcc)
155 -- We still need the unsullied global name env so that
156 -- we can look up record field names
158 rn_fixenv :: LocalFixityEnv -- Local fixities (for non-top-level
160 -- The global fixities are held in the
161 -- HIT or PIT. Why? See the comments
162 -- with RnIfaces.lookupLocalFixity
165 data RnMode = SourceMode -- Renaming source code
166 | InterfaceMode -- Renaming interface declarations.
169 %===================================================
170 \subsubsection{ ENVIRONMENTS}
171 %===================================================
174 --------------------------------
175 type LocalRdrEnv = RdrNameEnv Name
176 type LocalFixityEnv = NameEnv RenamedFixitySig
177 -- We keep the whole fixity sig so that we
178 -- can report line-number info when there is a duplicate
179 -- fixity declaration
181 lookupLocalFixity :: LocalFixityEnv -> Name -> Fixity
182 lookupLocalFixity env name
183 = case lookupNameEnv env name of
184 Just (FixitySig _ fix _) -> fix
185 Nothing -> defaultFixity
189 type ExportAvails = (FiniteMap ModuleName Avails,
190 -- Used to figure out "module M" export specifiers
191 -- Includes avails only from *unqualified* imports
192 -- (see 1.4 Report Section 5.1.1)
194 AvailEnv) -- Used to figure out all other export specifiers.
197 %===================================================
198 \subsubsection{ INTERFACE FILE STUFF}
199 %===================================================
202 type ExportItem = (ModuleName, [RdrAvailInfo])
203 type IfaceDeprecs = Maybe (Either DeprecTxt [(RdrName,DeprecTxt)])
204 -- Nothing => NoDeprecs
205 -- Just (Left t) => DeprecAll
206 -- Just (Right p) => DeprecSome
210 pi_mod :: Module, -- Complete with package info
211 pi_vers :: Version, -- Module version number
212 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
213 pi_usages :: [ImportVersion OccName], -- Usages
214 pi_exports :: (Version, [ExportItem]), -- Exports
215 pi_decls :: [(Version, RdrNameTyClDecl)], -- Local definitions
216 pi_fixity :: [RdrNameFixitySig], -- Local fixity declarations,
217 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
218 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
219 pi_deprecs :: IfaceDeprecs -- Deprecations
223 %************************************************************************
225 \subsection{The renamer state}
227 %************************************************************************
230 data Ifaces = Ifaces {
232 iPIT :: PackageIfaceTable,
233 -- The ModuleIFaces for modules in other packages
234 -- whose interfaces we have opened
235 -- The declarations in these interface files are held in
236 -- iDecls, iInsts, iRules (below), not in the mi_decls fields
237 -- of the iPIT. What _is_ in the iPIT is:
243 -- The iPIT field is initialised from the compiler's persistent
244 -- package symbol table, and the renamer incrementally adds
248 -- A single, global map of Names to unslurped decls
250 iInsts :: IfaceInsts,
251 -- The as-yet un-slurped instance decls; this bag is depleted when we
252 -- slurp an instance decl so that we don't slurp the same one twice.
253 -- Each is 'gated' by the names that must be available before
254 -- this instance decl is needed.
256 iRules :: IfaceRules,
257 -- Similar to instance decls, only for rules
260 -- These fields persist during the compilation of a single module only
261 iImpModInfo :: ImportedModuleInfo,
262 -- Modules this one depends on: that is, the union
263 -- of the modules its *direct* imports depend on.
264 -- NB: The direct imports have .hi files that enumerate *all* the
265 -- dependencies (direct or not) of the imported module.
268 -- All the names (whether "big" or "small", whether wired-in or not,
269 -- whether locally defined or not) that have been slurped in so far.
271 iVSlurp :: (ModuleSet, NameSet)
272 -- The Names are all the (a) non-wired-in
274 -- (c) non-locally-defined
276 -- names that have been slurped in so far, with their versions.
277 -- This is used to generate the "usage" information for this module.
278 -- Subset of the previous field.
279 -- The module set is the non-home-package modules from which we have
280 -- slurped at least one name.
281 -- It's worth keeping separately, because there's no very easy
282 -- way to distinguish the "big" names from the "non-big" ones.
283 -- But this is a decision we might want to revisit.
286 type ImportedModuleInfo = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface)
287 -- Contains info ONLY about modules that have not yet
288 --- been loaded into the iPIT
292 %************************************************************************
294 \subsection{Main monad code}
296 %************************************************************************
300 -> HomeIfaceTable -> HomeSymbolTable
301 -> PersistentCompilerState
304 -> IO (PersistentCompilerState, Bool, t)
305 -- True <=> found errors
307 initRn dflags hit hst pcs mod do_rn
309 let prs = pcs_PRS pcs
310 let pte = pcs_PTE pcs
311 let ifaces = Ifaces { iPIT = pcs_PIT pcs,
312 iDecls = prsDecls prs,
313 iInsts = prsInsts prs,
314 iRules = prsRules prs,
316 iImpModInfo = emptyFM,
317 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
318 -- Pretend that the dummy unbound name has already been
319 -- slurped. This is what's returned for an out-of-scope name,
320 -- and we don't want thereby to try to suck it in!
321 iVSlurp = (emptyModuleSet, emptyNameSet)
323 let uniqs = prsNS prs
325 names_var <- newIORef (uniqs, origNames (prsOrig prs),
326 origIParam (prsOrig prs))
327 errs_var <- newIORef (emptyBag,emptyBag)
328 iface_var <- newIORef ifaces
329 let rn_down = RnDown { rn_mod = mod,
334 rn_done = is_done hst pte,
338 rn_ifaces = iface_var,
342 res <- do_rn rn_down ()
344 -- Grab state and record it
345 (warns, errs) <- readIORef errs_var
346 new_ifaces <- readIORef iface_var
347 (new_NS, new_origN, new_origIP) <- readIORef names_var
348 let new_orig = Orig { origNames = new_origN, origIParam = new_origIP }
349 let new_prs = prs { prsOrig = new_orig,
350 prsDecls = iDecls new_ifaces,
351 prsInsts = iInsts new_ifaces,
352 prsRules = iRules new_ifaces,
354 let new_pcs = pcs { pcs_PIT = iPIT new_ifaces,
357 -- Check for warnings
358 printErrorsAndWarnings (warns, errs) ;
360 return (new_pcs, not (isEmptyBag errs), res)
362 is_done :: HomeSymbolTable -> PackageTypeEnv -> Name -> Bool
363 -- Returns True iff the name is in either symbol table
364 -- The name is a Global, so it has a Module
365 is_done hst pte n = maybeToBool (lookupType hst pte n)
367 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
368 -- The fixity_env appears in both the rn_fixenv field
369 -- and in the HIT. See comments with RnHiFiles.lookupFixityRn
371 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
372 rn_fixenv = fixity_env, rn_mode = mode }
374 thing_inside rn_down s_down
376 initIfaceRnMS :: Module -> RnMS r -> RnM d r
377 initIfaceRnMS mod thing_inside
378 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
379 setModuleRn mod thing_inside
382 @renameSourceCode@ is used to rename stuff ``out-of-line'';
383 that is, not as part of the main renamer.
384 Sole examples: derived definitions,
385 which are only generated in the type checker.
387 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
388 once you must either split it, or install a fresh unique supply.
391 renameSourceCode :: DynFlags
393 -> PersistentRenamerState
397 renameSourceCode dflags mod prs m
399 -- It's not really unsafe! When renaming source code we
400 -- only do any I/O if we need to read in a fixity declaration;
401 -- and that doesn't happen in pragmas etc
403 mkSplitUniqSupply 'r' >>= \ new_us ->
404 newIORef (new_us, origNames (prsOrig prs),
405 origIParam (prsOrig prs)) >>= \ names_var ->
406 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
408 rn_down = RnDown { rn_dflags = dflags,
409 rn_loc = generatedSrcLoc, rn_ns = names_var,
412 rn_done = bogus "rn_done", rn_hit = bogus "rn_hit",
413 rn_ifaces = bogus "rn_ifaces"
415 s_down = SDown { rn_mode = InterfaceMode,
416 -- So that we can refer to PrelBase.True etc
417 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
418 rn_fixenv = emptyNameEnv }
420 m rn_down s_down >>= \ result ->
422 readIORef errs_var >>= \ (warns,errs) ->
424 (if not (isEmptyBag errs) then
425 pprTrace "Urk! renameSourceCode found errors" (display errs)
427 else if not (isEmptyBag warns) then
428 pprTrace "Note: renameSourceCode found warnings" (display warns)
436 display errs = pprBagOfErrors errs
438 bogus s = panic ("rnameSourceCode: " ++ s) -- Used for unused record fields
440 {-# INLINE thenRn #-}
441 {-# INLINE thenRn_ #-}
442 {-# INLINE returnRn #-}
445 returnRn :: a -> RnM d a
446 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
447 thenRn_ :: RnM d a -> RnM d b -> RnM d b
448 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
449 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
450 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
451 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
452 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
453 sequenceRn :: [RnM d a] -> RnM d [a]
454 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
455 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
456 fixRn :: (a -> RnM d a) -> RnM d a
458 returnRn v gdown ldown = return v
459 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
460 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
461 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
462 andRn combiner m1 m2 gdown ldown
463 = m1 gdown ldown >>= \ res1 ->
464 m2 gdown ldown >>= \ res2 ->
465 return (combiner res1 res2)
467 sequenceRn [] = returnRn []
468 sequenceRn (m:ms) = m `thenRn` \ r ->
469 sequenceRn ms `thenRn` \ rs ->
472 mapRn f [] = returnRn []
474 = f x `thenRn` \ r ->
475 mapRn f xs `thenRn` \ rs ->
478 mapRn_ f [] = returnRn ()
483 foldlRn k z [] = returnRn z
484 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
487 mapAndUnzipRn f [] = returnRn ([],[])
488 mapAndUnzipRn f (x:xs)
489 = f x `thenRn` \ (r1, r2) ->
490 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
491 returnRn (r1:rs1, r2:rs2)
493 mapAndUnzip3Rn f [] = returnRn ([],[],[])
494 mapAndUnzip3Rn f (x:xs)
495 = f x `thenRn` \ (r1, r2, r3) ->
496 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
497 returnRn (r1:rs1, r2:rs2, r3:rs3)
499 mapMaybeRn f [] = returnRn []
500 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
501 mapMaybeRn f xs `thenRn` \ rs ->
503 Nothing -> returnRn rs
504 Just r -> returnRn (r:rs)
506 flatMapRn f [] = returnRn []
507 flatMapRn f (x:xs) = f x `thenRn` \ r ->
508 flatMapRn f xs `thenRn` \ rs ->
514 %************************************************************************
516 \subsection{Boring plumbing for common part}
518 %************************************************************************
522 \subsubsection{ Errors and warnings}
523 %=====================
526 failWithRn :: a -> Message -> RnM d a
527 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
528 = readIORef errs_var >>= \ (warns,errs) ->
529 writeIORef errs_var (warns, errs `snocBag` err) >>
532 err = addShortErrLocLine loc msg
534 warnWithRn :: a -> Message -> RnM d a
535 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
536 = readIORef errs_var >>= \ (warns,errs) ->
537 writeIORef errs_var (warns `snocBag` warn, errs) >>
540 warn = addShortWarnLocLine loc msg
542 addErrRn :: Message -> RnM d ()
543 addErrRn err = failWithRn () err
545 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
546 checkRn False err = addErrRn err
547 checkRn True err = returnRn ()
549 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
550 warnCheckRn False err = addWarnRn err
551 warnCheckRn True err = returnRn ()
553 addWarnRn :: Message -> RnM d ()
554 addWarnRn warn = warnWithRn () warn
556 checkErrsRn :: RnM d Bool -- True <=> no errors so far
557 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
558 = readIORef errs_var >>= \ (warns,errs) ->
559 return (isEmptyBag errs)
561 doptRn :: DynFlag -> RnM d Bool
562 doptRn dflag (RnDown { rn_dflags = dflags}) l_down
563 = return (dopt dflag dflags)
565 getDOptsRn :: RnM d DynFlags
566 getDOptsRn (RnDown { rn_dflags = dflags}) l_down
572 \subsubsection{Source location}
573 %=====================
576 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
577 pushSrcLocRn loc' m down l_down
578 = m (down {rn_loc = loc'}) l_down
580 getSrcLocRn :: RnM d SrcLoc
581 getSrcLocRn down l_down
582 = return (rn_loc down)
586 \subsubsection{The finder and home symbol table}
587 %=====================
590 getHomeIfaceTableRn :: RnM d HomeIfaceTable
591 getHomeIfaceTableRn down l_down = return (rn_hit down)
593 checkAlreadyAvailable :: Name -> RnM d Bool
594 -- Name is a Global name
595 checkAlreadyAvailable name down l_down = return (rn_done down name)
599 \subsubsection{Name supply}
600 %=====================
603 getNameSupplyRn :: RnM d (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv)
604 getNameSupplyRn rn_down l_down
605 = readIORef (rn_ns rn_down)
607 setNameSupplyRn :: (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv) -> RnM d ()
608 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
609 = writeIORef names_var names'
611 getUniqRn :: RnM d Unique
612 getUniqRn (RnDown {rn_ns = names_var}) l_down
613 = readIORef names_var >>= \ (us, cache, ipcache) ->
615 (us1,us') = splitUniqSupply us
617 writeIORef names_var (us', cache, ipcache) >>
618 return (uniqFromSupply us1)
622 \subsubsection{ Module}
623 %=====================
626 getModuleRn :: RnM d Module
627 getModuleRn (RnDown {rn_mod = mod}) l_down
630 setModuleRn :: Module -> RnM d a -> RnM d a
631 setModuleRn new_mod enclosed_thing rn_down l_down
632 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
636 %************************************************************************
638 \subsection{Plumbing for rename-source part}
640 %************************************************************************
643 \subsubsection{ RnEnv}
644 %=====================
647 getLocalNameEnv :: RnMS LocalRdrEnv
648 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
651 getGlobalNameEnv :: RnMS GlobalRdrEnv
652 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
655 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
656 setLocalNameEnv local_env' m rn_down l_down
657 = m rn_down (l_down {rn_lenv = local_env'})
659 getFixityEnv :: RnMS LocalFixityEnv
660 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
663 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
664 extendFixityEnv fixes enclosed_scope
665 rn_down l_down@(SDown {rn_fixenv = fixity_env})
667 new_fixity_env = extendNameEnvList fixity_env fixes
669 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
673 \subsubsection{ Mode}
674 %=====================
677 getModeRn :: RnMS RnMode
678 getModeRn rn_down (SDown {rn_mode = mode})
681 setModeRn :: RnMode -> RnMS a -> RnMS a
682 setModeRn new_mode thing_inside rn_down l_down
683 = thing_inside rn_down (l_down {rn_mode = new_mode})
687 %************************************************************************
689 \subsection{Plumbing for rename-globals part}
691 %************************************************************************
694 getIfacesRn :: RnM d Ifaces
695 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
696 = readIORef iface_var
698 setIfacesRn :: Ifaces -> RnM d ()
699 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
700 = writeIORef iface_var ifaces