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 ( Finder,
39 AvailEnv, lookupTypeEnv,
40 OrigNameEnv(..), OrigNameNameEnv, OrigNameIParamEnv,
41 WhetherHasOrphans, ImportVersion,
42 PersistentRenamerState(..), IsBootInterface, Avails,
43 DeclsMap, IfaceInsts, IfaceRules,
44 HomeSymbolTable, PackageSymbolTable,
45 PersistentCompilerState(..), GlobalRdrEnv,
46 HomeIfaceTable, PackageIfaceTable,
47 RdrAvailInfo, ModIface )
48 import BasicTypes ( Version, defaultFixity )
49 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
50 pprBagOfErrors, ErrMsg, WarnMsg, Message
52 import RdrName ( RdrName, dummyRdrVarName, rdrNameModule, rdrNameOcc,
53 RdrNameEnv, emptyRdrEnv, extendRdrEnv,
54 lookupRdrEnv, addListToRdrEnv, rdrEnvToList, rdrEnvElts
56 import Name ( Name, OccName, NamedThing(..), getSrcLoc,
57 isLocallyDefinedName, nameModule, nameOccName,
58 decode, mkLocalName, mkKnownKeyGlobal,
59 NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv,
62 import Module ( Module, ModuleName, lookupModuleEnvByName )
64 import CmdLineOpts ( DynFlags, DynFlag(..), dopt )
65 import SrcLoc ( SrcLoc, generatedSrcLoc )
66 import Unique ( Unique )
67 import FiniteMap ( FiniteMap, emptyFM )
68 import Bag ( Bag, emptyBag, isEmptyBag, snocBag )
71 import PrelNames ( mkUnboundName )
72 import Maybes ( maybeToBool, seqMaybe, orElse )
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 traceRn :: SDoc -> RnM d ()
92 = doptRn Opt_D_dump_rn_trace `thenRn` \b ->
93 if b then putDocRn msg else returnRn ()
95 putDocRn :: SDoc -> RnM d ()
96 putDocRn msg = ioToRnM (printErrs msg) `thenRn_`
101 %************************************************************************
103 \subsection{Data types}
105 %************************************************************************
107 %===================================================
108 \subsubsection{ MONAD TYPES}
109 %===================================================
112 type RnM d r = RnDown -> d -> IO r
113 type RnMS r = RnM SDown r -- Renaming source
114 type RnMG r = RnM () r -- Getting global names etc
119 rn_mod :: Module, -- This module
120 rn_loc :: SrcLoc, -- Current locn
123 rn_dflags :: DynFlags,
125 rn_hit :: HomeIfaceTable,
126 rn_done :: Name -> Bool, -- Tells what things (both in the
127 -- home package and other packages)
128 -- were already available (i.e. in
129 -- the relevant SymbolTable) before
130 -- compiling this module
132 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
134 -- The second and third components are a flattened-out OrigNameEnv
135 rn_ns :: IORef (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv),
136 rn_ifaces :: IORef Ifaces
139 -- For renaming source code
143 rn_genv :: GlobalRdrEnv, -- Global envt
145 rn_lenv :: LocalRdrEnv, -- Local name envt
146 -- Does *not* include global name envt; may shadow it
147 -- Includes both ordinary variables and type variables;
148 -- they are kept distinct because tyvar have a different
149 -- occurrence contructor (Name.TvOcc)
150 -- We still need the unsullied global name env so that
151 -- we can look up record field names
153 rn_fixenv :: LocalFixityEnv -- Local fixities
154 -- The global fixities are held in the
155 -- rn_ifaces field. Why? See the comments
156 -- with RnIfaces.lookupLocalFixity
159 data RnMode = SourceMode -- Renaming source code
160 | InterfaceMode -- Renaming interface declarations.
163 %===================================================
164 \subsubsection{ ENVIRONMENTS}
165 %===================================================
168 --------------------------------
169 type LocalRdrEnv = RdrNameEnv Name
170 type LocalFixityEnv = NameEnv RenamedFixitySig
171 -- We keep the whole fixity sig so that we
172 -- can report line-number info when there is a duplicate
173 -- fixity declaration
175 lookupLocalFixity :: LocalFixityEnv -> Name -> Fixity
176 lookupLocalFixity env name
177 = case lookupNameEnv env name of
178 Just (FixitySig _ fix _) -> fix
179 Nothing -> defaultFixity
183 type ExportAvails = (FiniteMap ModuleName Avails,
184 -- Used to figure out "module M" export specifiers
185 -- Includes avails only from *unqualified* imports
186 -- (see 1.4 Report Section 5.1.1)
188 AvailEnv) -- Used to figure out all other export specifiers.
191 %===================================================
192 \subsubsection{ INTERFACE FILE STUFF}
193 %===================================================
196 type ExportItem = (ModuleName, [RdrAvailInfo])
200 pi_mod :: Module, -- Complete with package info
201 pi_vers :: Version, -- Module version number
202 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
203 pi_usages :: [ImportVersion OccName], -- Usages
204 pi_exports :: [ExportItem], -- Exports
205 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
206 pi_decls :: [(Version, RdrNameHsDecl)], -- Local definitions
207 pi_fixity :: (Version, [RdrNameFixitySig]), -- Local fixity declarations,
208 -- with their version
209 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
210 pi_deprecs :: [RdrNameDeprecation] -- Deprecations
214 %************************************************************************
216 \subsection{The renamer state}
218 %************************************************************************
221 data Ifaces = Ifaces {
223 iPIT :: PackageIfaceTable,
224 -- The ModuleIFaces for modules in other packages
225 -- whose interfaces we have opened
226 -- The declarations in these interface files are held in
227 -- iDecls, iInsts, iRules (below), not in the mi_decls fields
228 -- of the iPIT. What _is_ in the iPIT is:
234 -- The iPIT field is initialised from the compiler's persistent
235 -- package symbol table, and the renamer incrementally adds
239 -- A single, global map of Names to unslurped decls
241 iInsts :: IfaceInsts,
242 -- The as-yet un-slurped instance decls; this bag is depleted when we
243 -- slurp an instance decl so that we don't slurp the same one twice.
244 -- Each is 'gated' by the names that must be available before
245 -- this instance decl is needed.
247 iRules :: IfaceRules,
248 -- Similar to instance decls, only for rules
251 -- These fields persist during the compilation of a single module only
252 iImpModInfo :: ImportedModuleInfo,
253 -- Modules this one depends on: that is, the union
254 -- of the modules its *direct* imports depend on.
255 -- NB: The direct imports have .hi files that enumerate *all* the
256 -- dependencies (direct or not) of the imported module.
259 -- All the names (whether "big" or "small", whether wired-in or not,
260 -- whether locally defined or not) that have been slurped in so far.
263 -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
264 -- names that have been slurped in so far, with their versions.
265 -- This is used to generate the "usage" information for this module.
266 -- Subset of the previous field.
267 -- It's worth keeping separately, because there's no very easy
268 -- way to distinguish the "big" names from the "non-big" ones.
269 -- But this is a decision we might want to revisit.
272 type ImportedModuleInfo = FiniteMap ModuleName
273 (WhetherHasOrphans, IsBootInterface, IsLoaded)
278 %************************************************************************
280 \subsection{Main monad code}
282 %************************************************************************
289 -> PersistentCompilerState
293 -> IO (t, PersistentCompilerState, (Bag WarnMsg, Bag ErrMsg))
295 initRn dflags finder hit hst pcs mod loc do_rn
297 let prs = pcs_PRS pcs
298 let pst = pcs_PST pcs
300 uniqs <- mkSplitUniqSupply 'r'
301 names_var <- newIORef (uniqs, origNames (prsOrig prs),
302 origIParam (prsOrig prs))
303 errs_var <- newIORef (emptyBag,emptyBag)
304 iface_var <- newIORef (initIfaces pcs)
305 let rn_down = RnDown { rn_mod = mod,
311 rn_done = is_done hst pst,
315 rn_ifaces = iface_var,
319 res <- do_rn rn_down ()
321 -- Grab state and record it
322 (warns, errs) <- readIORef errs_var
323 new_ifaces <- readIORef iface_var
324 (_, new_origN, new_origIP) <- readIORef names_var
325 let new_orig = Orig { origNames = new_origN, origIParam = new_origIP }
326 let new_prs = prs { prsOrig = new_orig,
327 prsDecls = iDecls new_ifaces,
328 prsInsts = iInsts new_ifaces,
329 prsRules = iRules new_ifaces }
330 let new_pcs = pcs { pcs_PIT = iPIT new_ifaces,
333 return (res, new_pcs, (warns, errs))
335 is_done :: HomeSymbolTable -> PackageSymbolTable -> Name -> Bool
336 -- Returns True iff the name is in either symbol table
337 is_done hst pst n = maybeToBool (lookupTypeEnv pst n `seqMaybe` lookupTypeEnv hst n)
339 lookupIface :: HomeIfaceTable -> PackageIfaceTable -> ModuleName -> ModIface
340 lookupIface hit pit mod = lookupModuleEnvByName hit mod `orElse`
341 lookupModuleEnvByName pit mod `orElse`
342 pprPanic "lookupIface" (ppr mod)
344 initIfaces :: PersistentCompilerState -> Ifaces
345 initIfaces (PCS { pcs_PIT = pit, pcs_PRS = prs })
346 = Ifaces { iPIT = pit,
347 iDecls = prsDecls prs,
348 iInsts = prsInsts prs,
349 iRules = prsRules prs,
351 iImpModInfo = emptyFM,
352 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
353 -- Pretend that the dummy unbound name has already been
354 -- slurped. This is what's returned for an out-of-scope name,
355 -- and we don't want thereby to try to suck it in!
360 initRnMS :: GlobalRdrEnv -> LocalFixityEnv -> RnMode -> RnMS r -> RnM d r
361 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
363 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
364 rn_fixenv = fixity_env, rn_mode = mode }
366 thing_inside rn_down s_down
368 initIfaceRnMS :: Module -> RnMS r -> RnM d r
369 initIfaceRnMS mod thing_inside
370 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
371 setModuleRn mod thing_inside
375 @renameSourceCode@ is used to rename stuff ``out-of-line'';
376 that is, not as part of the main renamer.
377 Sole examples: derived definitions,
378 which are only generated in the type checker.
380 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
381 once you must either split it, or install a fresh unique supply.
384 renameSourceCode :: DynFlags
386 -> PersistentRenamerState
390 renameSourceCode dflags mod prs m
392 -- It's not really unsafe! When renaming source code we
393 -- only do any I/O if we need to read in a fixity declaration;
394 -- and that doesn't happen in pragmas etc
396 mkSplitUniqSupply 'r' >>= \ new_us ->
397 newIORef (new_us, origNames (prsOrig prs),
398 origIParam (prsOrig prs)) >>= \ names_var ->
399 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
401 rn_down = RnDown { rn_dflags = dflags,
402 rn_loc = generatedSrcLoc, rn_ns = names_var,
405 rn_ifaces = panic "rnameSourceCode: rn_ifaces", -- Not required
406 rn_finder = panic "rnameSourceCode: rn_finder" -- Not required
408 s_down = SDown { rn_mode = InterfaceMode,
409 -- So that we can refer to PrelBase.True etc
410 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
411 rn_fixenv = emptyNameEnv }
413 m rn_down s_down >>= \ result ->
415 readIORef errs_var >>= \ (warns,errs) ->
417 (if not (isEmptyBag errs) then
418 pprTrace "Urk! renameSourceCode found errors" (display errs)
420 else if not (isEmptyBag warns) then
421 pprTrace "Note: renameSourceCode found warnings" (display warns)
429 display errs = pprBagOfErrors errs
431 {-# INLINE thenRn #-}
432 {-# INLINE thenRn_ #-}
433 {-# INLINE returnRn #-}
436 returnRn :: a -> RnM d a
437 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
438 thenRn_ :: RnM d a -> RnM d b -> RnM d b
439 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
440 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
441 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
442 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
443 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
444 sequenceRn :: [RnM d a] -> RnM d [a]
445 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
446 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
447 fixRn :: (a -> RnM d a) -> RnM d a
449 returnRn v gdown ldown = return v
450 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
451 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
452 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
453 andRn combiner m1 m2 gdown ldown
454 = m1 gdown ldown >>= \ res1 ->
455 m2 gdown ldown >>= \ res2 ->
456 return (combiner res1 res2)
458 sequenceRn [] = returnRn []
459 sequenceRn (m:ms) = m `thenRn` \ r ->
460 sequenceRn ms `thenRn` \ rs ->
463 mapRn f [] = returnRn []
465 = f x `thenRn` \ r ->
466 mapRn f xs `thenRn` \ rs ->
469 mapRn_ f [] = returnRn ()
474 foldlRn k z [] = returnRn z
475 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
478 mapAndUnzipRn f [] = returnRn ([],[])
479 mapAndUnzipRn f (x:xs)
480 = f x `thenRn` \ (r1, r2) ->
481 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
482 returnRn (r1:rs1, r2:rs2)
484 mapAndUnzip3Rn f [] = returnRn ([],[],[])
485 mapAndUnzip3Rn f (x:xs)
486 = f x `thenRn` \ (r1, r2, r3) ->
487 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
488 returnRn (r1:rs1, r2:rs2, r3:rs3)
490 mapMaybeRn f [] = returnRn []
491 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
492 mapMaybeRn f xs `thenRn` \ rs ->
494 Nothing -> returnRn rs
495 Just r -> returnRn (r:rs)
497 flatMapRn f [] = returnRn []
498 flatMapRn f (x:xs) = f x `thenRn` \ r ->
499 flatMapRn f xs `thenRn` \ rs ->
505 %************************************************************************
507 \subsection{Boring plumbing for common part}
509 %************************************************************************
513 \subsubsection{ Errors and warnings}
514 %=====================
517 failWithRn :: a -> Message -> RnM d a
518 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
519 = readIORef errs_var >>= \ (warns,errs) ->
520 writeIORef errs_var (warns, errs `snocBag` err) >>
523 err = addShortErrLocLine loc msg
525 warnWithRn :: a -> Message -> RnM d a
526 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
527 = readIORef errs_var >>= \ (warns,errs) ->
528 writeIORef errs_var (warns `snocBag` warn, errs) >>
531 warn = addShortWarnLocLine loc msg
533 addErrRn :: Message -> RnM d ()
534 addErrRn err = failWithRn () err
536 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
537 checkRn False err = addErrRn err
538 checkRn True err = returnRn ()
540 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
541 warnCheckRn False err = addWarnRn err
542 warnCheckRn True err = returnRn ()
544 addWarnRn :: Message -> RnM d ()
545 addWarnRn warn = warnWithRn () warn
547 checkErrsRn :: RnM d Bool -- True <=> no errors so far
548 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
549 = readIORef errs_var >>= \ (warns,errs) ->
550 return (isEmptyBag errs)
552 doptRn :: DynFlag -> RnM d Bool
553 doptRn dflag (RnDown { rn_dflags = dflags}) l_down
554 = return (dopt dflag dflags)
556 getDOptsRn :: RnM d DynFlags
557 getDOptsRn (RnDown { rn_dflags = dflags}) l_down
563 \subsubsection{Source location}
564 %=====================
567 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
568 pushSrcLocRn loc' m down l_down
569 = m (down {rn_loc = loc'}) l_down
571 getSrcLocRn :: RnM d SrcLoc
572 getSrcLocRn down l_down
573 = return (rn_loc down)
577 \subsubsection{The finder and home symbol table}
578 %=====================
581 getFinderRn :: RnM d Finder
582 getFinderRn down l_down = return (rn_finder down)
584 getHomeIfaceTableRn :: RnM d HomeIfaceTable
585 getHomeIfaceTableRn down l_down = return (rn_hit down)
587 checkAlreadyAvailable :: Name -> RnM d Bool
588 checkAlreadyAvailable name down l_down = return (rn_done down name)
592 \subsubsection{Name supply}
593 %=====================
596 getNameSupplyRn :: RnM d (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv)
597 getNameSupplyRn rn_down l_down
598 = readIORef (rn_ns rn_down)
600 setNameSupplyRn :: (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv) -> RnM d ()
601 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
602 = writeIORef names_var names'
604 getUniqRn :: RnM d Unique
605 getUniqRn (RnDown {rn_ns = names_var}) l_down
606 = readIORef names_var >>= \ (us, cache, ipcache) ->
608 (us1,us') = splitUniqSupply us
610 writeIORef names_var (us', cache, ipcache) >>
611 return (uniqFromSupply us1)
615 \subsubsection{ Module}
616 %=====================
619 getModuleRn :: RnM d Module
620 getModuleRn (RnDown {rn_mod = mod}) l_down
623 setModuleRn :: Module -> RnM d a -> RnM d a
624 setModuleRn new_mod enclosed_thing rn_down l_down
625 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
629 %************************************************************************
631 \subsection{Plumbing for rename-source part}
633 %************************************************************************
636 \subsubsection{ RnEnv}
637 %=====================
640 getLocalNameEnv :: RnMS LocalRdrEnv
641 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
644 getGlobalNameEnv :: RnMS GlobalRdrEnv
645 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
648 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
649 setLocalNameEnv local_env' m rn_down l_down
650 = m rn_down (l_down {rn_lenv = local_env'})
652 getFixityEnv :: RnMS LocalFixityEnv
653 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
656 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
657 extendFixityEnv fixes enclosed_scope
658 rn_down l_down@(SDown {rn_fixenv = fixity_env})
660 new_fixity_env = extendNameEnvList fixity_env fixes
662 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
666 \subsubsection{ Mode}
667 %=====================
670 getModeRn :: RnMS RnMode
671 getModeRn rn_down (SDown {rn_mode = mode})
674 setModeRn :: RnMode -> RnMS a -> RnMS a
675 setModeRn new_mode thing_inside rn_down l_down
676 = thing_inside rn_down (l_down {rn_mode = new_mode})
680 %************************************************************************
682 \subsection{Plumbing for rename-globals part}
684 %************************************************************************
687 getIfacesRn :: RnM d Ifaces
688 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
689 = readIORef iface_var
691 setIfacesRn :: Ifaces -> RnM d ()
692 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
693 = writeIORef iface_var ifaces