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, TyThing,
44 PersistentCompilerState(..), GlobalRdrEnv,
45 HomeIfaceTable, PackageIfaceTable,
47 import BasicTypes ( Version, defaultFixity )
48 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
49 pprBagOfErrors, Message, Messages, errorsFound,
50 printErrorsAndWarnings
52 import RdrName ( RdrName, dummyRdrVarName, rdrNameModule, rdrNameOcc,
53 RdrNameEnv, emptyRdrEnv, extendRdrEnv,
54 addListToRdrEnv, rdrEnvToList, rdrEnvElts
56 import Name ( Name, OccName, NamedThing(..),
58 decode, mkLocalName, mkKnownKeyGlobal
60 import Name ( NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv, extendNameEnvList )
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 )
72 infixr 9 `thenRn`, `thenRn_`
76 %************************************************************************
78 \subsection{Somewhat magical interface to other monads}
80 %************************************************************************
83 ioToRnM :: IO r -> RnM d (Either IOError r)
84 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
86 (\ err -> return (Left err))
88 ioToRnM_no_fail :: IO r -> RnM d r
89 ioToRnM_no_fail io rn_down g_down
90 = (io >>= \ ok -> return ok)
92 (\ err -> panic "ioToRnM_no_fail: the I/O operation failed!")
94 traceRn :: SDoc -> RnM d ()
96 = doptRn Opt_D_dump_rn_trace `thenRn` \b ->
97 if b then putDocRn msg else returnRn ()
99 traceHiDiffsRn :: SDoc -> RnM d ()
101 = doptRn Opt_D_dump_hi_diffs `thenRn` \b ->
102 if b then putDocRn msg else returnRn ()
104 putDocRn :: SDoc -> RnM d ()
105 putDocRn msg = ioToRnM (printErrs alwaysQualify msg) `thenRn_`
110 %************************************************************************
112 \subsection{Data types}
114 %************************************************************************
116 %===================================================
117 \subsubsection{ MONAD TYPES}
118 %===================================================
121 type RnM d r = RnDown -> d -> IO r
122 type RnMS r = RnM SDown r -- Renaming source
123 type RnMG r = RnM () r -- Getting global names etc
128 rn_mod :: Module, -- This module
129 rn_loc :: SrcLoc, -- Current locn
131 rn_dflags :: DynFlags,
133 rn_hit :: HomeIfaceTable,
134 rn_done :: Name -> Maybe TyThing, -- Tells what things (both in the
135 -- home package and other packages)
136 -- were already available (i.e. in
137 -- the relevant SymbolTable) before
138 -- compiling this module
139 -- The Name passed to rn_done is guaranteed to be a Global,
140 -- so it has a Module, so it can be looked up
142 rn_errs :: IORef Messages,
144 -- The second and third components are a flattened-out OrigNameEnv
145 rn_ns :: IORef (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv),
146 rn_ifaces :: IORef Ifaces
149 -- For renaming source code
153 rn_genv :: GlobalRdrEnv, -- Top level environment
155 rn_lenv :: LocalRdrEnv, -- Local name envt
156 -- Does *not* include global name envt; may shadow it
157 -- Includes both ordinary variables and type variables;
158 -- they are kept distinct because tyvar have a different
159 -- occurrence contructor (Name.TvOcc)
160 -- We still need the unsullied global name env so that
161 -- we can look up record field names
163 rn_fixenv :: LocalFixityEnv -- Local fixities (for non-top-level
165 -- The global fixities are held in the
166 -- HIT or PIT. Why? See the comments
167 -- with RnIfaces.lookupLocalFixity
170 data RnMode = SourceMode -- Renaming source code
171 | InterfaceMode -- Renaming interface declarations.
174 %===================================================
175 \subsubsection{ ENVIRONMENTS}
176 %===================================================
179 --------------------------------
180 type LocalRdrEnv = RdrNameEnv Name
181 type LocalFixityEnv = NameEnv RenamedFixitySig
182 -- We keep the whole fixity sig so that we
183 -- can report line-number info when there is a duplicate
184 -- fixity declaration
186 lookupLocalFixity :: LocalFixityEnv -> Name -> Fixity
187 lookupLocalFixity env name
188 = case lookupNameEnv env name of
189 Just (FixitySig _ fix _) -> fix
190 Nothing -> defaultFixity
194 type ExportAvails = (FiniteMap ModuleName Avails,
195 -- Used to figure out "module M" export specifiers
196 -- Includes avails only from *unqualified* imports
197 -- (see 1.4 Report Section 5.1.1)
199 AvailEnv) -- Used to figure out all other export specifiers.
202 %===================================================
203 \subsubsection{ INTERFACE FILE STUFF}
204 %===================================================
207 type ExportItem = (ModuleName, [RdrAvailInfo])
208 type IfaceDeprecs = Maybe (Either DeprecTxt [(RdrName,DeprecTxt)])
209 -- Nothing => NoDeprecs
210 -- Just (Left t) => DeprecAll
211 -- Just (Right p) => DeprecSome
215 pi_mod :: Module, -- Complete with package info
216 pi_vers :: Version, -- Module version number
217 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
218 pi_usages :: [ImportVersion OccName], -- Usages
219 pi_exports :: (Version, [ExportItem]), -- Exports
220 pi_decls :: [(Version, RdrNameTyClDecl)], -- Local definitions
221 pi_fixity :: [RdrNameFixitySig], -- Local fixity declarations,
222 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
223 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
224 pi_deprecs :: IfaceDeprecs -- Deprecations
228 %************************************************************************
230 \subsection{The renamer state}
232 %************************************************************************
235 data Ifaces = Ifaces {
237 iPIT :: PackageIfaceTable,
238 -- The ModuleIFaces for modules in other packages
239 -- whose interfaces we have opened
240 -- The declarations in these interface files are held in
241 -- iDecls, iInsts, iRules (below), not in the mi_decls fields
242 -- of the iPIT. What _is_ in the iPIT is:
248 -- The iPIT field is initialised from the compiler's persistent
249 -- package symbol table, and the renamer incrementally adds
253 -- A single, global map of Names to unslurped decls
255 iInsts :: IfaceInsts,
256 -- The as-yet un-slurped instance decls; this bag is depleted when we
257 -- slurp an instance decl so that we don't slurp the same one twice.
258 -- Each is 'gated' by the names that must be available before
259 -- this instance decl is needed.
261 iRules :: IfaceRules,
262 -- Similar to instance decls, only for rules
265 -- These fields persist during the compilation of a single module only
266 iImpModInfo :: ImportedModuleInfo,
267 -- Modules that we know something about, because they are mentioned
268 -- in interface files, BUT which we have not loaded yet.
269 -- No module is both in here and in the PIT
272 -- All the names (whether "big" or "small", whether wired-in or not,
273 -- whether locally defined or not) that have been slurped in so far.
275 iVSlurp :: (ModuleSet, NameSet)
276 -- The Names are all the (a) non-wired-in
278 -- (c) non-locally-defined
280 -- names that have been slurped in so far, with their versions.
281 -- This is used to generate the "usage" information for this module.
282 -- Subset of the previous field.
283 -- The module set is the non-home-package modules from which we have
284 -- slurped at least one name.
285 -- It's worth keeping separately, because there's no very easy
286 -- way to distinguish the "big" names from the "non-big" ones.
287 -- But this is a decision we might want to revisit.
290 type ImportedModuleInfo = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface)
291 -- Contains info ONLY about modules that have not yet
292 --- been loaded into the iPIT
296 %************************************************************************
298 \subsection{Main monad code}
300 %************************************************************************
303 runRn dflags hit hst pcs mod do_rn
304 = do { (pcs, msgs, r) <- initRn dflags hit hst pcs mod do_rn ;
305 printErrorsAndWarnings alwaysQualify msgs ;
306 return (pcs, errorsFound msgs, r)
310 -> HomeIfaceTable -> HomeSymbolTable
311 -> PersistentCompilerState
314 -> IO (PersistentCompilerState, Messages, t)
316 initRn dflags hit hst pcs mod do_rn
318 let prs = pcs_PRS pcs
319 let pte = pcs_PTE pcs
320 let ifaces = Ifaces { iPIT = pcs_PIT pcs,
321 iDecls = prsDecls prs,
322 iInsts = prsInsts prs,
323 iRules = prsRules prs,
325 iImpModInfo = emptyFM,
326 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
327 -- Pretend that the dummy unbound name has already been
328 -- slurped. This is what's returned for an out-of-scope name,
329 -- and we don't want thereby to try to suck it in!
330 iVSlurp = (emptyModuleSet, emptyNameSet)
332 let uniqs = prsNS prs
334 names_var <- newIORef (uniqs, origNames (prsOrig prs),
335 origIParam (prsOrig prs))
336 errs_var <- newIORef (emptyBag,emptyBag)
337 iface_var <- newIORef ifaces
338 let rn_down = RnDown { rn_mod = mod,
343 rn_done = lookupType hst pte,
347 rn_ifaces = iface_var,
351 res <- do_rn rn_down ()
353 -- Grab state and record it
354 (warns, errs) <- readIORef errs_var
355 new_ifaces <- readIORef iface_var
356 (new_NS, new_origN, new_origIP) <- readIORef names_var
357 let new_orig = Orig { origNames = new_origN, origIParam = new_origIP }
358 let new_prs = prs { prsOrig = new_orig,
359 prsDecls = iDecls new_ifaces,
360 prsInsts = iInsts new_ifaces,
361 prsRules = iRules new_ifaces,
363 let new_pcs = pcs { pcs_PIT = iPIT new_ifaces,
366 return (new_pcs, (warns, errs), res)
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 emptyNameEnv InterfaceMode $
380 setModuleRn mod thing_inside
383 @renameSourceCode@ 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 renameSourceCode :: DynFlags
394 -> PersistentRenamerState
398 renameSourceCode dflags mod prs m
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 mkSplitUniqSupply 'r' >>= \ new_us ->
405 newIORef (new_us, origNames (prsOrig prs),
406 origIParam (prsOrig prs)) >>= \ names_var ->
407 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
409 rn_down = RnDown { rn_dflags = dflags,
410 rn_loc = generatedSrcLoc, rn_ns = names_var,
413 rn_done = bogus "rn_done", rn_hit = bogus "rn_hit",
414 rn_ifaces = bogus "rn_ifaces"
416 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 = emptyNameEnv }
421 m rn_down s_down >>= \ result ->
423 readIORef errs_var >>= \ (warns,errs) ->
425 (if not (isEmptyBag errs) then
426 pprTrace "Urk! renameSourceCode found errors" (display errs)
428 else if not (isEmptyBag warns) then
429 pprTrace "Note: renameSourceCode found warnings" (display warns)
437 display errs = pprBagOfErrors errs
439 bogus s = panic ("rnameSourceCode: " ++ s) -- Used for unused record fields
441 {-# INLINE thenRn #-}
442 {-# INLINE thenRn_ #-}
443 {-# INLINE returnRn #-}
446 returnRn :: a -> RnM d a
447 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
448 thenRn_ :: RnM d a -> RnM d b -> RnM d b
449 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
450 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
451 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
452 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
453 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
454 sequenceRn :: [RnM d a] -> RnM d [a]
455 sequenceRn_ :: [RnM d a] -> RnM d ()
456 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
457 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
458 fixRn :: (a -> RnM d a) -> RnM d a
460 returnRn v gdown ldown = return v
461 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
462 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
463 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
464 andRn combiner m1 m2 gdown ldown
465 = m1 gdown ldown >>= \ res1 ->
466 m2 gdown ldown >>= \ res2 ->
467 return (combiner res1 res2)
469 sequenceRn [] = returnRn []
470 sequenceRn (m:ms) = m `thenRn` \ r ->
471 sequenceRn ms `thenRn` \ rs ->
474 sequenceRn_ [] = returnRn ()
475 sequenceRn_ (m:ms) = m `thenRn_` sequenceRn_ ms
477 mapRn f [] = returnRn []
479 = f x `thenRn` \ r ->
480 mapRn f xs `thenRn` \ rs ->
483 mapRn_ f [] = returnRn ()
488 foldlRn k z [] = returnRn z
489 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
492 mapAndUnzipRn f [] = returnRn ([],[])
493 mapAndUnzipRn f (x:xs)
494 = f x `thenRn` \ (r1, r2) ->
495 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
496 returnRn (r1:rs1, r2:rs2)
498 mapAndUnzip3Rn f [] = returnRn ([],[],[])
499 mapAndUnzip3Rn f (x:xs)
500 = f x `thenRn` \ (r1, r2, r3) ->
501 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
502 returnRn (r1:rs1, r2:rs2, r3:rs3)
504 mapMaybeRn f [] = returnRn []
505 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
506 mapMaybeRn f xs `thenRn` \ rs ->
508 Nothing -> returnRn rs
509 Just r -> returnRn (r:rs)
511 flatMapRn f [] = returnRn []
512 flatMapRn f (x:xs) = f x `thenRn` \ r ->
513 flatMapRn f xs `thenRn` \ rs ->
519 %************************************************************************
521 \subsection{Boring plumbing for common part}
523 %************************************************************************
527 \subsubsection{ Errors and warnings}
528 %=====================
531 failWithRn :: a -> Message -> RnM d a
532 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
533 = readIORef errs_var >>= \ (warns,errs) ->
534 writeIORef errs_var (warns, errs `snocBag` err) >>
537 err = addShortErrLocLine loc msg
539 warnWithRn :: a -> Message -> RnM d a
540 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
541 = readIORef errs_var >>= \ (warns,errs) ->
542 writeIORef errs_var (warns `snocBag` warn, errs) >>
545 warn = addShortWarnLocLine loc msg
547 addErrRn :: Message -> RnM d ()
548 addErrRn err = failWithRn () err
550 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
551 checkRn False err = addErrRn err
552 checkRn True err = returnRn ()
554 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
555 warnCheckRn False err = addWarnRn err
556 warnCheckRn True err = returnRn ()
558 addWarnRn :: Message -> RnM d ()
559 addWarnRn warn = warnWithRn () warn
561 checkErrsRn :: RnM d Bool -- True <=> no errors so far
562 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
563 = readIORef errs_var >>= \ (warns,errs) ->
564 return (isEmptyBag errs)
566 doptRn :: DynFlag -> RnM d Bool
567 doptRn dflag (RnDown { rn_dflags = dflags}) l_down
568 = return (dopt dflag dflags)
570 getDOptsRn :: RnM d DynFlags
571 getDOptsRn (RnDown { rn_dflags = dflags}) l_down
577 \subsubsection{Source location}
578 %=====================
581 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
582 pushSrcLocRn loc' m down l_down
583 = m (down {rn_loc = loc'}) l_down
585 getSrcLocRn :: RnM d SrcLoc
586 getSrcLocRn down l_down
587 = return (rn_loc down)
591 \subsubsection{The finder and home symbol table}
592 %=====================
595 getHomeIfaceTableRn :: RnM d HomeIfaceTable
596 getHomeIfaceTableRn down l_down = return (rn_hit down)
598 getTypeEnvRn :: RnM d (Name -> Maybe TyThing)
599 getTypeEnvRn down l_down = return (rn_done down)
603 \subsubsection{Name supply}
604 %=====================
607 getNameSupplyRn :: RnM d (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv)
608 getNameSupplyRn rn_down l_down
609 = readIORef (rn_ns rn_down)
611 setNameSupplyRn :: (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv) -> RnM d ()
612 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
613 = writeIORef names_var names'
615 getUniqRn :: RnM d Unique
616 getUniqRn (RnDown {rn_ns = names_var}) l_down
617 = readIORef names_var >>= \ (us, cache, ipcache) ->
619 (us1,us') = splitUniqSupply us
621 writeIORef names_var (us', cache, ipcache) >>
622 return (uniqFromSupply us1)
626 \subsubsection{ Module}
627 %=====================
630 getModuleRn :: RnM d Module
631 getModuleRn (RnDown {rn_mod = mod}) l_down
634 setModuleRn :: Module -> RnM d a -> RnM d a
635 setModuleRn new_mod enclosed_thing rn_down l_down
636 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
640 %************************************************************************
642 \subsection{Plumbing for rename-source part}
644 %************************************************************************
647 \subsubsection{ RnEnv}
648 %=====================
651 getLocalNameEnv :: RnMS LocalRdrEnv
652 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
655 getGlobalNameEnv :: RnMS GlobalRdrEnv
656 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
659 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
660 setLocalNameEnv local_env' m rn_down l_down
661 = m rn_down (l_down {rn_lenv = local_env'})
663 getFixityEnv :: RnMS LocalFixityEnv
664 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
667 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
668 extendFixityEnv fixes enclosed_scope
669 rn_down l_down@(SDown {rn_fixenv = fixity_env})
671 new_fixity_env = extendNameEnvList fixity_env fixes
673 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
677 \subsubsection{ Mode}
678 %=====================
681 getModeRn :: RnMS RnMode
682 getModeRn rn_down (SDown {rn_mode = mode})
685 setModeRn :: RnMode -> RnMS a -> RnMS a
686 setModeRn new_mode thing_inside rn_down l_down
687 = thing_inside rn_down (l_down {rn_mode = new_mode})
691 %************************************************************************
693 \subsection{Plumbing for rename-globals part}
695 %************************************************************************
698 getIfacesRn :: RnM d Ifaces
699 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
700 = readIORef iface_var
702 setIfacesRn :: Ifaces -> RnM d ()
703 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
704 = writeIORef iface_var ifaces