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,
56 isLocallyDefinedName, nameOccName,
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, seqMaybe )
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 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
122 rn_dflags :: DynFlags,
124 rn_hit :: HomeIfaceTable,
125 rn_done :: Name -> Bool, -- Tells what things (both in the
126 -- home package and other packages)
127 -- were already available (i.e. in
128 -- the relevant SymbolTable) before
129 -- compiling this module
131 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
133 -- The second and third components are a flattened-out OrigNameEnv
134 rn_ns :: IORef (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv),
135 rn_ifaces :: IORef Ifaces
138 -- For renaming source code
142 rn_genv :: GlobalRdrEnv, -- Global envt
144 rn_lenv :: LocalRdrEnv, -- Local name envt
145 -- Does *not* include global name envt; may shadow it
146 -- Includes both ordinary variables and type variables;
147 -- they are kept distinct because tyvar have a different
148 -- occurrence contructor (Name.TvOcc)
149 -- We still need the unsullied global name env so that
150 -- we can look up record field names
152 rn_fixenv :: LocalFixityEnv -- Local fixities
153 -- The global fixities are held in the
154 -- rn_ifaces field. Why? See the comments
155 -- with RnIfaces.lookupLocalFixity
158 data RnMode = SourceMode -- Renaming source code
159 | InterfaceMode -- Renaming interface declarations.
162 %===================================================
163 \subsubsection{ ENVIRONMENTS}
164 %===================================================
167 --------------------------------
168 type LocalRdrEnv = RdrNameEnv Name
169 type LocalFixityEnv = NameEnv RenamedFixitySig
170 -- We keep the whole fixity sig so that we
171 -- can report line-number info when there is a duplicate
172 -- fixity declaration
174 lookupLocalFixity :: LocalFixityEnv -> Name -> Fixity
175 lookupLocalFixity env name
176 = case lookupNameEnv env name of
177 Just (FixitySig _ fix _) -> fix
178 Nothing -> defaultFixity
182 type ExportAvails = (FiniteMap ModuleName Avails,
183 -- Used to figure out "module M" export specifiers
184 -- Includes avails only from *unqualified* imports
185 -- (see 1.4 Report Section 5.1.1)
187 AvailEnv) -- Used to figure out all other export specifiers.
190 %===================================================
191 \subsubsection{ INTERFACE FILE STUFF}
192 %===================================================
195 type ExportItem = (ModuleName, [RdrAvailInfo])
196 type IfaceDeprecs = Maybe (Either DeprecTxt [(RdrName,DeprecTxt)])
197 -- Nothing => NoDeprecs
198 -- Just (Left t) => DeprecAll
199 -- Just (Right p) => DeprecSome
203 pi_mod :: Module, -- Complete with package info
204 pi_vers :: Version, -- Module version number
205 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
206 pi_usages :: [ImportVersion OccName], -- Usages
207 pi_exports :: (Version, [ExportItem]), -- Exports
208 pi_decls :: [(Version, RdrNameTyClDecl)], -- Local definitions
209 pi_fixity :: [RdrNameFixitySig], -- Local fixity declarations,
210 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
211 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
212 pi_deprecs :: IfaceDeprecs -- Deprecations
216 %************************************************************************
218 \subsection{The renamer state}
220 %************************************************************************
223 data Ifaces = Ifaces {
225 iPIT :: PackageIfaceTable,
226 -- The ModuleIFaces for modules in other packages
227 -- whose interfaces we have opened
228 -- The declarations in these interface files are held in
229 -- iDecls, iInsts, iRules (below), not in the mi_decls fields
230 -- of the iPIT. What _is_ in the iPIT is:
236 -- The iPIT field is initialised from the compiler's persistent
237 -- package symbol table, and the renamer incrementally adds
241 -- A single, global map of Names to unslurped decls
243 iInsts :: IfaceInsts,
244 -- The as-yet un-slurped instance decls; this bag is depleted when we
245 -- slurp an instance decl so that we don't slurp the same one twice.
246 -- Each is 'gated' by the names that must be available before
247 -- this instance decl is needed.
249 iRules :: IfaceRules,
250 -- Similar to instance decls, only for rules
253 -- These fields persist during the compilation of a single module only
254 iImpModInfo :: ImportedModuleInfo,
255 -- Modules this one depends on: that is, the union
256 -- of the modules its *direct* imports depend on.
257 -- NB: The direct imports have .hi files that enumerate *all* the
258 -- dependencies (direct or not) of the imported module.
261 -- All the names (whether "big" or "small", whether wired-in or not,
262 -- whether locally defined or not) that have been slurped in so far.
264 iVSlurp :: (ModuleSet, NameSet)
265 -- The Names are all the (a) non-wired-in
267 -- (c) non-locally-defined
269 -- names that have been slurped in so far, with their versions.
270 -- This is used to generate the "usage" information for this module.
271 -- Subset of the previous field.
272 -- The module set is the non-home-package modules from which we have
273 -- slurped at least one name.
274 -- It's worth keeping separately, because there's no very easy
275 -- way to distinguish the "big" names from the "non-big" ones.
276 -- But this is a decision we might want to revisit.
279 type ImportedModuleInfo = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface)
280 -- Contains info ONLY about modules that have not yet
281 --- been loaded into the iPIT
285 %************************************************************************
287 \subsection{Main monad code}
289 %************************************************************************
293 -> HomeIfaceTable -> HomeSymbolTable
294 -> PersistentCompilerState
297 -> IO (PersistentCompilerState, Bool, t)
298 -- True <=> found errors
300 initRn dflags hit hst pcs mod do_rn
302 let prs = pcs_PRS pcs
303 let pte = pcs_PTE pcs
304 let ifaces = Ifaces { iPIT = pcs_PIT pcs,
305 iDecls = prsDecls prs,
306 iInsts = prsInsts prs,
307 iRules = prsRules prs,
309 iImpModInfo = emptyFM,
310 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
311 -- Pretend that the dummy unbound name has already been
312 -- slurped. This is what's returned for an out-of-scope name,
313 -- and we don't want thereby to try to suck it in!
314 iVSlurp = (emptyModuleSet, emptyNameSet)
316 let uniqs = prsNS prs
318 names_var <- newIORef (uniqs, origNames (prsOrig prs),
319 origIParam (prsOrig prs))
320 errs_var <- newIORef (emptyBag,emptyBag)
321 iface_var <- newIORef ifaces
322 let rn_down = RnDown { rn_mod = mod,
327 rn_done = is_done hst pte,
331 rn_ifaces = iface_var,
335 res <- do_rn rn_down ()
337 -- Grab state and record it
338 (warns, errs) <- readIORef errs_var
339 new_ifaces <- readIORef iface_var
340 (new_NS, new_origN, new_origIP) <- readIORef names_var
341 let new_orig = Orig { origNames = new_origN, origIParam = new_origIP }
342 let new_prs = prs { prsOrig = new_orig,
343 prsDecls = iDecls new_ifaces,
344 prsInsts = iInsts new_ifaces,
345 prsRules = iRules new_ifaces,
347 let new_pcs = pcs { pcs_PIT = iPIT new_ifaces,
350 -- Check for warnings
351 printErrorsAndWarnings (warns, errs) ;
353 return (new_pcs, not (isEmptyBag errs), res)
355 is_done :: HomeSymbolTable -> PackageTypeEnv -> Name -> Bool
356 -- Returns True iff the name is in either symbol table
357 is_done hst pte n = maybeToBool (lookupType hst pte n)
359 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
361 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
362 rn_fixenv = fixity_env, rn_mode = mode }
364 thing_inside rn_down s_down
366 initIfaceRnMS :: Module -> RnMS r -> RnM d r
367 initIfaceRnMS mod thing_inside
368 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
369 setModuleRn mod thing_inside
373 @renameSourceCode@ is used to rename stuff ``out-of-line'';
374 that is, not as part of the main renamer.
375 Sole examples: derived definitions,
376 which are only generated in the type checker.
378 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
379 once you must either split it, or install a fresh unique supply.
382 renameSourceCode :: DynFlags
384 -> PersistentRenamerState
388 renameSourceCode dflags mod prs m
390 -- It's not really unsafe! When renaming source code we
391 -- only do any I/O if we need to read in a fixity declaration;
392 -- and that doesn't happen in pragmas etc
394 mkSplitUniqSupply 'r' >>= \ new_us ->
395 newIORef (new_us, origNames (prsOrig prs),
396 origIParam (prsOrig prs)) >>= \ names_var ->
397 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
399 rn_down = RnDown { rn_dflags = dflags,
400 rn_loc = generatedSrcLoc, rn_ns = names_var,
403 rn_done = bogus "rn_done", rn_hit = bogus "rn_hit",
404 rn_ifaces = bogus "rn_ifaces"
406 s_down = SDown { rn_mode = InterfaceMode,
407 -- So that we can refer to PrelBase.True etc
408 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
409 rn_fixenv = emptyNameEnv }
411 m rn_down s_down >>= \ result ->
413 readIORef errs_var >>= \ (warns,errs) ->
415 (if not (isEmptyBag errs) then
416 pprTrace "Urk! renameSourceCode found errors" (display errs)
418 else if not (isEmptyBag warns) then
419 pprTrace "Note: renameSourceCode found warnings" (display warns)
427 display errs = pprBagOfErrors errs
429 bogus s = panic ("rnameSourceCode: " ++ s) -- Used for unused record fields
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 getHomeIfaceTableRn :: RnM d HomeIfaceTable
582 getHomeIfaceTableRn down l_down = return (rn_hit down)
584 checkAlreadyAvailable :: Name -> RnM d Bool
585 checkAlreadyAvailable name down l_down = return (rn_done down name)
589 \subsubsection{Name supply}
590 %=====================
593 getNameSupplyRn :: RnM d (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv)
594 getNameSupplyRn rn_down l_down
595 = readIORef (rn_ns rn_down)
597 setNameSupplyRn :: (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv) -> RnM d ()
598 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
599 = writeIORef names_var names'
601 getUniqRn :: RnM d Unique
602 getUniqRn (RnDown {rn_ns = names_var}) l_down
603 = readIORef names_var >>= \ (us, cache, ipcache) ->
605 (us1,us') = splitUniqSupply us
607 writeIORef names_var (us', cache, ipcache) >>
608 return (uniqFromSupply us1)
612 \subsubsection{ Module}
613 %=====================
616 getModuleRn :: RnM d Module
617 getModuleRn (RnDown {rn_mod = mod}) l_down
620 setModuleRn :: Module -> RnM d a -> RnM d a
621 setModuleRn new_mod enclosed_thing rn_down l_down
622 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
626 %************************************************************************
628 \subsection{Plumbing for rename-source part}
630 %************************************************************************
633 \subsubsection{ RnEnv}
634 %=====================
637 getLocalNameEnv :: RnMS LocalRdrEnv
638 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
641 getGlobalNameEnv :: RnMS GlobalRdrEnv
642 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
645 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
646 setLocalNameEnv local_env' m rn_down l_down
647 = m rn_down (l_down {rn_lenv = local_env'})
649 getFixityEnv :: RnMS LocalFixityEnv
650 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
653 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
654 extendFixityEnv fixes enclosed_scope
655 rn_down l_down@(SDown {rn_fixenv = fixity_env})
657 new_fixity_env = extendNameEnvList fixity_env fixes
659 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
663 \subsubsection{ Mode}
664 %=====================
667 getModeRn :: RnMS RnMode
668 getModeRn rn_down (SDown {rn_mode = mode})
671 setModeRn :: RnMode -> RnMS a -> RnMS a
672 setModeRn new_mode thing_inside rn_down l_down
673 = thing_inside rn_down (l_down {rn_mode = new_mode})
677 %************************************************************************
679 \subsection{Plumbing for rename-globals part}
681 %************************************************************************
684 getIfacesRn :: RnM d Ifaces
685 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
686 = readIORef iface_var
688 setIfacesRn :: Ifaces -> RnM d ()
689 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
690 = writeIORef iface_var ifaces