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,
40 OrigNameEnv(..), OrigNameNameEnv, OrigNameIParamEnv,
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,
145 -- The second and third components are a flattened-out OrigNameEnv
146 rn_ns :: IORef (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv),
147 rn_ifaces :: IORef Ifaces
150 -- For renaming source code
154 rn_genv :: GlobalRdrEnv, -- Top level environment
156 rn_lenv :: LocalRdrEnv, -- Local name envt
157 -- Does *not* include global name envt; may shadow it
158 -- Includes both ordinary variables and type variables;
159 -- they are kept distinct because tyvar have a different
160 -- occurrence contructor (Name.TvOcc)
161 -- We still need the unsullied global name env so that
162 -- we can look up record field names
164 rn_fixenv :: LocalFixityEnv -- Local fixities (for non-top-level
166 -- The global fixities are held in the
167 -- HIT or PIT. Why? See the comments
168 -- with RnIfaces.lookupLocalFixity
171 data RnMode = SourceMode -- Renaming source code
172 | InterfaceMode -- Renaming interface declarations.
175 %===================================================
176 \subsubsection{ ENVIRONMENTS}
177 %===================================================
180 --------------------------------
181 type LocalRdrEnv = RdrNameEnv Name
182 type LocalFixityEnv = NameEnv RenamedFixitySig
183 -- We keep the whole fixity sig so that we
184 -- can report line-number info when there is a duplicate
185 -- fixity declaration
187 emptyLocalFixityEnv :: LocalFixityEnv
188 emptyLocalFixityEnv = emptyNameEnv
190 lookupLocalFixity :: LocalFixityEnv -> Name -> Fixity
191 lookupLocalFixity env name
192 = case lookupNameEnv env name of
193 Just (FixitySig _ fix _) -> fix
194 Nothing -> defaultFixity
198 type ExportAvails = (FiniteMap ModuleName Avails,
199 -- Used to figure out "module M" export specifiers
200 -- Includes avails only from *unqualified* imports
201 -- (see 1.4 Report Section 5.1.1)
203 AvailEnv) -- Used to figure out all other export specifiers.
206 %===================================================
207 \subsubsection{ INTERFACE FILE STUFF}
208 %===================================================
211 type ExportItem = (ModuleName, [RdrAvailInfo])
212 type IfaceDeprecs = Maybe (Either DeprecTxt [(RdrName,DeprecTxt)])
213 -- Nothing => NoDeprecs
214 -- Just (Left t) => DeprecAll
215 -- Just (Right p) => DeprecSome
219 pi_mod :: Module, -- Complete with package info
220 pi_vers :: Version, -- Module version number
221 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
222 pi_usages :: [ImportVersion OccName], -- Usages
223 pi_exports :: (Version, [ExportItem]), -- Exports
224 pi_decls :: [(Version, RdrNameTyClDecl)], -- Local definitions
225 pi_fixity :: [RdrNameFixitySig], -- Local fixity declarations,
226 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
227 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
228 pi_deprecs :: IfaceDeprecs -- Deprecations
232 %************************************************************************
234 \subsection{The renamer state}
236 %************************************************************************
239 data Ifaces = Ifaces {
241 iPIT :: PackageIfaceTable,
242 -- The ModuleIFaces for modules in other packages
243 -- whose interfaces we have opened
244 -- The declarations in these interface files are held in
245 -- iDecls, iInsts, iRules (below), not in the mi_decls fields
246 -- of the iPIT. What _is_ in the iPIT is:
252 -- The iPIT field is initialised from the compiler's persistent
253 -- package symbol table, and the renamer incrementally adds
257 -- A single, global map of Names to unslurped decls
259 iInsts :: IfaceInsts,
260 -- The as-yet un-slurped instance decls; this bag is depleted when we
261 -- slurp an instance decl so that we don't slurp the same one twice.
262 -- Each is 'gated' by the names that must be available before
263 -- this instance decl is needed.
265 iRules :: IfaceRules,
266 -- Similar to instance decls, only for rules
269 -- These fields persist during the compilation of a single module only
270 iImpModInfo :: ImportedModuleInfo,
271 -- Modules that we know something about, because they are mentioned
272 -- in interface files, BUT which we have not loaded yet.
273 -- No module is both in here and in the PIT
276 -- All the names (whether "big" or "small", whether wired-in or not,
277 -- whether locally defined or not) that have been slurped in so far.
279 iVSlurp :: (ModuleSet, NameSet)
280 -- The Names are all the (a) non-wired-in
282 -- (c) non-locally-defined
284 -- names that have been slurped in so far, with their versions.
285 -- This is used to generate the "usage" information for this module.
286 -- Subset of the previous field.
287 -- The module set is the non-home-package modules from which we have
288 -- slurped at least one name.
289 -- It's worth keeping separately, because there's no very easy
290 -- way to distinguish the "big" names from the "non-big" ones.
291 -- But this is a decision we might want to revisit.
294 type ImportedModuleInfo = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface)
295 -- Contains info ONLY about modules that have not yet
296 --- been loaded into the iPIT
300 %************************************************************************
302 \subsection{Main monad code}
304 %************************************************************************
307 runRn dflags hit hst pcs mod do_rn
308 = do { (pcs, msgs, r) <- initRn dflags hit hst pcs mod do_rn ;
309 printErrorsAndWarnings alwaysQualify msgs ;
310 return (pcs, errorsFound msgs, r)
314 -> HomeIfaceTable -> HomeSymbolTable
315 -> PersistentCompilerState
318 -> IO (PersistentCompilerState, Messages, t)
320 initRn dflags hit hst pcs mod do_rn
322 let prs = pcs_PRS pcs
323 let pte = pcs_PTE pcs
324 let ifaces = Ifaces { iPIT = pcs_PIT pcs,
325 iDecls = prsDecls prs,
326 iInsts = prsInsts prs,
327 iRules = prsRules prs,
329 iImpModInfo = emptyFM,
330 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
331 -- Pretend that the dummy unbound name has already been
332 -- slurped. This is what's returned for an out-of-scope name,
333 -- and we don't want thereby to try to suck it in!
334 iVSlurp = (emptyModuleSet, emptyNameSet)
336 let uniqs = prsNS prs
338 names_var <- newIORef (uniqs, origNames (prsOrig prs),
339 origIParam (prsOrig prs))
340 errs_var <- newIORef (emptyBag,emptyBag)
341 iface_var <- newIORef ifaces
342 let rn_down = RnDown { rn_mod = mod,
347 rn_done = lookupType hst pte,
351 rn_ifaces = iface_var,
355 res <- do_rn rn_down ()
357 -- Grab state and record it
358 (warns, errs) <- readIORef errs_var
359 new_ifaces <- readIORef iface_var
360 (new_NS, new_origN, new_origIP) <- readIORef names_var
361 let new_orig = Orig { origNames = new_origN, origIParam = new_origIP }
362 let new_prs = prs { prsOrig = new_orig,
363 prsDecls = iDecls new_ifaces,
364 prsInsts = iInsts new_ifaces,
365 prsRules = iRules new_ifaces,
367 let new_pcs = pcs { pcs_PIT = iPIT new_ifaces,
370 return (new_pcs, (warns, errs), res)
372 initRnMS :: GlobalRdrEnv -> LocalFixityEnv -> RnMode
375 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
376 -- The fixity_env appears in both the rn_fixenv field
377 -- and in the HIT. See comments with RnHiFiles.lookupFixityRn
379 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
380 rn_fixenv = fixity_env, rn_mode = mode }
382 thing_inside rn_down s_down
384 initIfaceRnMS :: Module -> RnMS r -> RnM d r
385 initIfaceRnMS mod thing_inside
386 = initRnMS emptyRdrEnv emptyLocalFixityEnv InterfaceMode $
387 setModuleRn mod thing_inside
390 @renameDerivedCode@ is used to rename stuff ``out-of-line'';
391 that is, not as part of the main renamer.
392 Sole examples: derived definitions,
393 which are only generated in the type checker.
395 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
396 once you must either split it, or install a fresh unique supply.
399 renameDerivedCode :: DynFlags
401 -> PersistentRenamerState
405 renameDerivedCode dflags mod prs thing_inside
407 -- It's not really unsafe! When renaming source code we
408 -- only do any I/O if we need to read in a fixity declaration;
409 -- and that doesn't happen in pragmas etc
411 do { us <- mkSplitUniqSupply 'r'
412 ; names_var <- newIORef (us, origNames (prsOrig prs),
413 origIParam (prsOrig prs))
414 ; errs_var <- newIORef (emptyBag,emptyBag)
416 ; let rn_down = RnDown { rn_dflags = dflags,
417 rn_loc = generatedSrcLoc, rn_ns = names_var,
420 rn_done = bogus "rn_done",
421 rn_hit = bogus "rn_hit",
422 rn_ifaces = bogus "rn_ifaces"
424 ; let s_down = SDown { rn_mode = InterfaceMode,
425 -- So that we can refer to PrelBase.True etc
426 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
427 rn_fixenv = emptyLocalFixityEnv }
429 ; result <- thing_inside rn_down s_down
430 ; messages <- readIORef errs_var
432 ; if bad messages then
433 do { hPutStr stderr "Urk! renameDerivedCode found errors or warnings"
434 ; printErrorsAndWarnings alwaysQualify messages
443 bad messages = errorsFound messages || warningsFound messages
445 bad messages = errorsFound messages
448 bogus s = panic ("rnameSourceCode: " ++ s) -- Used for unused record fields
450 {-# INLINE thenRn #-}
451 {-# INLINE thenRn_ #-}
452 {-# INLINE returnRn #-}
455 returnRn :: a -> RnM d a
456 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
457 thenRn_ :: RnM d a -> RnM d b -> RnM d b
458 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
459 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
460 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
461 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
462 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
463 sequenceRn :: [RnM d a] -> RnM d [a]
464 sequenceRn_ :: [RnM d a] -> RnM d ()
465 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
466 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
467 fixRn :: (a -> RnM d a) -> RnM d a
469 returnRn v gdown ldown = return v
470 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
471 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
472 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
473 andRn combiner m1 m2 gdown ldown
474 = m1 gdown ldown >>= \ res1 ->
475 m2 gdown ldown >>= \ res2 ->
476 return (combiner res1 res2)
478 sequenceRn [] = returnRn []
479 sequenceRn (m:ms) = m `thenRn` \ r ->
480 sequenceRn ms `thenRn` \ rs ->
483 sequenceRn_ [] = returnRn ()
484 sequenceRn_ (m:ms) = m `thenRn_` sequenceRn_ ms
486 mapRn f [] = returnRn []
488 = f x `thenRn` \ r ->
489 mapRn f xs `thenRn` \ rs ->
492 mapRn_ f [] = returnRn ()
497 foldlRn k z [] = returnRn z
498 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
501 mapAndUnzipRn f [] = returnRn ([],[])
502 mapAndUnzipRn f (x:xs)
503 = f x `thenRn` \ (r1, r2) ->
504 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
505 returnRn (r1:rs1, r2:rs2)
507 mapAndUnzip3Rn f [] = returnRn ([],[],[])
508 mapAndUnzip3Rn f (x:xs)
509 = f x `thenRn` \ (r1, r2, r3) ->
510 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
511 returnRn (r1:rs1, r2:rs2, r3:rs3)
513 mapMaybeRn f [] = returnRn []
514 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
515 mapMaybeRn f xs `thenRn` \ rs ->
517 Nothing -> returnRn rs
518 Just r -> returnRn (r:rs)
520 flatMapRn f [] = returnRn []
521 flatMapRn f (x:xs) = f x `thenRn` \ r ->
522 flatMapRn f xs `thenRn` \ rs ->
528 %************************************************************************
530 \subsection{Boring plumbing for common part}
532 %************************************************************************
536 \subsubsection{ Errors and warnings}
537 %=====================
540 failWithRn :: a -> Message -> RnM d a
541 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
542 = readIORef errs_var >>= \ (warns,errs) ->
543 writeIORef errs_var (warns, errs `snocBag` err) >>
546 err = addShortErrLocLine loc msg
548 warnWithRn :: a -> Message -> RnM d a
549 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
550 = readIORef errs_var >>= \ (warns,errs) ->
551 writeIORef errs_var (warns `snocBag` warn, errs) >>
554 warn = addShortWarnLocLine loc msg
556 addErrRn :: Message -> RnM d ()
557 addErrRn err = failWithRn () err
559 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
560 checkRn False err = addErrRn err
561 checkRn True err = returnRn ()
563 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
564 warnCheckRn False err = addWarnRn err
565 warnCheckRn True err = returnRn ()
567 addWarnRn :: Message -> RnM d ()
568 addWarnRn warn = warnWithRn () warn
570 checkErrsRn :: RnM d Bool -- True <=> no errors so far
571 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
572 = readIORef errs_var >>= \ (warns,errs) ->
573 return (isEmptyBag errs)
575 doptRn :: DynFlag -> RnM d Bool
576 doptRn dflag (RnDown { rn_dflags = dflags}) l_down
577 = return (dopt dflag dflags)
579 getDOptsRn :: RnM d DynFlags
580 getDOptsRn (RnDown { rn_dflags = dflags}) l_down
586 \subsubsection{Source location}
587 %=====================
590 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
591 pushSrcLocRn loc' m down l_down
592 = m (down {rn_loc = loc'}) l_down
594 getSrcLocRn :: RnM d SrcLoc
595 getSrcLocRn down l_down
596 = return (rn_loc down)
600 \subsubsection{The finder and home symbol table}
601 %=====================
604 getHomeIfaceTableRn :: RnM d HomeIfaceTable
605 getHomeIfaceTableRn down l_down = return (rn_hit down)
607 getTypeEnvRn :: RnM d (Name -> Maybe TyThing)
608 getTypeEnvRn down l_down = return (rn_done down)
612 \subsubsection{Name supply}
613 %=====================
616 getNameSupplyRn :: RnM d (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv)
617 getNameSupplyRn rn_down l_down
618 = readIORef (rn_ns rn_down)
620 setNameSupplyRn :: (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv) -> RnM d ()
621 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
622 = writeIORef names_var names'
624 getUniqRn :: RnM d Unique
625 getUniqRn (RnDown {rn_ns = names_var}) l_down
626 = readIORef names_var >>= \ (us, cache, ipcache) ->
628 (us1,us') = splitUniqSupply us
630 writeIORef names_var (us', cache, ipcache) >>
631 return (uniqFromSupply us1)
635 \subsubsection{ Module}
636 %=====================
639 getModuleRn :: RnM d Module
640 getModuleRn (RnDown {rn_mod = mod}) l_down
643 setModuleRn :: Module -> RnM d a -> RnM d a
644 setModuleRn new_mod enclosed_thing rn_down l_down
645 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
649 %************************************************************************
651 \subsection{Plumbing for rename-source part}
653 %************************************************************************
656 \subsubsection{ RnEnv}
657 %=====================
660 getLocalNameEnv :: RnMS LocalRdrEnv
661 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
664 getGlobalNameEnv :: RnMS GlobalRdrEnv
665 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
668 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
669 setLocalNameEnv local_env' m rn_down l_down
670 = m rn_down (l_down {rn_lenv = local_env'})
672 getFixityEnv :: RnMS LocalFixityEnv
673 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
676 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
677 extendFixityEnv fixes enclosed_scope
678 rn_down l_down@(SDown {rn_fixenv = fixity_env})
680 new_fixity_env = extendNameEnvList fixity_env fixes
682 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
686 \subsubsection{ Mode}
687 %=====================
690 getModeRn :: RnMS RnMode
691 getModeRn rn_down (SDown {rn_mode = mode})
694 setModeRn :: RnMode -> RnMS a -> RnMS a
695 setModeRn new_mode thing_inside rn_down l_down
696 = thing_inside rn_down (l_down {rn_mode = new_mode})
700 %************************************************************************
702 \subsection{Plumbing for rename-globals part}
704 %************************************************************************
707 getIfacesRn :: RnM d Ifaces
708 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
709 = readIORef iface_var
711 setIfacesRn :: Ifaces -> RnM d ()
712 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
713 = writeIORef iface_var ifaces