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 BasicTypes ( Version, defaultFixity )
39 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
40 pprBagOfErrors, ErrMsg, WarnMsg, Message
42 import RdrName ( RdrName, dummyRdrVarName, rdrNameModule, rdrNameOcc,
43 RdrNameEnv, emptyRdrEnv, extendRdrEnv,
44 lookupRdrEnv, addListToRdrEnv, rdrEnvToList, rdrEnvElts
46 import Name ( Name, OccName, NamedThing(..), getSrcLoc,
47 isLocallyDefinedName, nameModule, nameOccName,
48 decode, mkLocalName, mkUnboundName, mkKnownKeyGlobal,
49 NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv, extendNameEnvList
51 import Module ( Module, ModuleName, ModuleHiMap, SearchPath, WhereFrom,
52 mkModuleHiMaps, moduleName, mkSearchPath
55 import CmdLineOpts ( opt_D_dump_rn_trace, opt_HiMap )
56 import PrelInfo ( wiredInNames, knownKeyRdrNames )
57 import SrcLoc ( SrcLoc, mkGeneratedSrcLoc )
58 import Unique ( Unique )
59 import FiniteMap ( FiniteMap, emptyFM, listToFM, plusFM )
60 import Bag ( Bag, mapBag, emptyBag, isEmptyBag, snocBag )
64 infixr 9 `thenRn`, `thenRn_`
68 %************************************************************************
70 \subsection{Somewhat magical interface to other monads}
72 %************************************************************************
75 ioToRnM :: IO r -> RnM d (Either IOError r)
76 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
78 (\ err -> return (Left err))
80 traceRn :: SDoc -> RnM d ()
81 traceRn msg | opt_D_dump_rn_trace = putDocRn msg
82 | otherwise = returnRn ()
84 putDocRn :: SDoc -> RnM d ()
85 putDocRn msg = ioToRnM (printErrs msg) `thenRn_`
90 %************************************************************************
92 \subsection{Data types}
94 %************************************************************************
96 %===================================================
97 \subsubsection{ MONAD TYPES}
98 %===================================================
101 type RnM d r = RnDown -> d -> IO r
102 type RnMS r = RnM SDown r -- Renaming source
103 type RnMG r = RnM () r -- Getting global names etc
108 rn_mod :: Module, -- This module
109 rn_loc :: SrcLoc, -- Current locn
112 rn_flags :: DynFlags,
113 rn_gst :: GlobalSymbolTable, -- Both home modules and packages,
114 -- at the moment we started compiling
117 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
118 rn_ns :: IORef NameSupply,
119 rn_ifaces :: IORef Ifaces,
122 -- For renaming source code
126 rn_genv :: GlobalRdrEnv, -- Global envt
128 rn_lenv :: LocalRdrEnv, -- Local name envt
129 -- Does *not* include global name envt; may shadow it
130 -- Includes both ordinary variables and type variables;
131 -- they are kept distinct because tyvar have a different
132 -- occurrence contructor (Name.TvOcc)
133 -- We still need the unsullied global name env so that
134 -- we can look up record field names
136 rn_fixenv :: FixityEnv -- Local fixities
137 -- The global fixities are held in the
138 -- rn_ifaces field. Why? See the comments
139 -- with RnIfaces.lookupFixity
142 data RnMode = SourceMode -- Renaming source code
143 | InterfaceMode -- Renaming interface declarations.
146 %===================================================
147 \subsubsection{ ENVIRONMENTS}
148 %===================================================
151 --------------------------------
152 type GlobalRdrEnv = RdrNameEnv [Name] -- The list is because there may be name clashes
153 -- These only get reported on lookup,
154 -- not on construction
155 type LocalRdrEnv = RdrNameEnv Name
157 --------------------------------
158 type FixityEnv = NameEnv RenamedFixitySig
159 -- We keep the whole fixity sig so that we
160 -- can report line-number info when there is a duplicate
161 -- fixity declaration
163 lookupFixity :: FixityEnv -> Name -> Fixity
164 lookupFixity env name
165 = case lookupNameEnv env name of
166 Just (FixitySig _ fix _) -> fix
167 Nothing -> defaultFixity
171 type ExportAvails = (FiniteMap ModuleName Avails,
172 -- Used to figure out "module M" export specifiers
173 -- Includes avails only from *unqualified* imports
174 -- (see 1.4 Report Section 5.1.1)
176 AvailEnv) -- Used to figure out all other export specifiers.
179 %===================================================
180 \subsubsection{ INTERFACE FILE STUFF}
181 %===================================================
184 type ExportItem = (ModuleName, [RdrAvailInfo])
186 type ImportVersion name = (ModuleName, WhetherHasOrphans, IsBootInterface, WhatsImported name)
188 type ModVersionInfo = (Version, -- Version of the whole module
189 Version, -- Version number for all fixity decls together
190 Version) -- ...ditto all rules together
192 type WhetherHasOrphans = Bool
194 -- * an instance decl in a module other than the defn module for
195 -- one of the tycons or classes in the instance head
196 -- * a transformation rule in a module other than the one defining
197 -- the function in the head of the rule.
199 type IsBootInterface = Bool
201 data WhatsImported name = NothingAtAll -- The module is below us in the
202 -- hierarchy, but we import nothing
204 | Everything Version -- The module version
206 | Specifically Version -- Module version
207 Version -- Fixity version
208 Version -- Rules version
209 [(name,Version)] -- List guaranteed non-empty
211 -- 'Specifically' doesn't let you say "I imported f but none of the fixities in
212 -- the module. If you use anything in the module you get its fixity and rule version
213 -- So if the fixities or rules change, you'll recompile, even if you don't use either.
214 -- This is easy to implement, and it's safer: you might not have used the rules last
215 -- time round, but if someone has added a new rule you might need it this time
217 -- 'Everything' means there was a "module M" in
218 -- this module's export list, so we just have to go by M's version,
219 -- not the list of (name,version) pairs
223 pi_mod :: Module, -- Complete with package info
224 pi_vers :: Version, -- Module version number
225 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
226 pi_usages :: [ImportVersion OccName], -- Usages
227 pi_exports :: [ExportItem], -- Exports
228 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
229 pi_decls :: [(Version, RdrNameHsDecl)], -- Local definitions
230 pi_fixity :: (Version, [RdrNameFixitySig]), -- Local fixity declarations, with their version
231 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
232 pi_deprecs :: [RdrNameDeprecation] -- Deprecations
236 type RdrNamePragma = () -- Fudge for now
239 %************************************************************************
241 \subsection{The renamer state}
243 %************************************************************************
246 data Ifaces = Ifaces {
249 iImpModInfo :: ImportedModuleInfo,
250 -- Modules this one depends on: that is, the union
251 -- of the modules its *direct* imports depend on.
252 -- NB: The direct imports have .hi files that enumerate *all* the
253 -- dependencies (direct or not) of the imported module.
255 iDecls :: DeclsMap, -- A single, global map of Names to decls
256 -- we can get away with importing them abstractly
258 iInsts :: IfaceInsts,
259 -- The as-yet un-slurped instance decls; this bag is depleted when we
260 -- slurp an instance decl so that we don't slurp the same one twice.
261 -- Each is 'gated' by the names that must be available before
262 -- this instance decl is needed.
264 iRules :: IfaceRules,
265 -- Similar to instance decls, only for rules
267 -- SEMI-EPHEMERAL FIELDS
268 -- iFixes and iDeprecs are accumulated here while one module
269 -- is compiled, but are transferred to the package symbol table
270 -- at the end. We don't add them to the table as we encounter them
271 -- because doing so would require us to have a mutable symbol table
274 iFixes :: FixityEnv, -- A single, global map of Names to fixities
275 -- See comments with RnIfaces.lookupFixity
276 iDeprecs :: DeprecationEnv,
280 -- These fields persist during the compilation of a single module only
283 -- All the names (whether "big" or "small", whether wired-in or not,
284 -- whether locally defined or not) that have been slurped in so far.
286 iVSlurp :: [(Name,Version)],
287 -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
288 -- names that have been slurped in so far, with their versions.
289 -- This is used to generate the "usage" information for this module.
290 -- Subset of the previous field.
293 type ImportedModuleInfo
294 = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface,
295 Maybe (Module, Version, Version, Version, WhereFrom, Avails))
296 -- The three Versions are module version, fixity version, rules version
298 -- Suppose the domain element is module 'A'
300 -- The first Bool is True if A contains
301 -- 'orphan' rules or instance decls
303 -- The second Bool is true if the interface file actually
304 -- read was an .hi-boot file
306 -- Nothing => A's interface not yet read, but this module has
307 -- imported a module, B, that itself depends on A
309 -- Just xx => A's interface has been read. The Module in
310 -- the Just has the correct Dll flag
312 -- This set is used to decide whether to look for
313 -- A.hi or A.hi-boot when importing A.f.
314 -- Basically, we look for A.hi if A is in the map, and A.hi-boot
319 %************************************************************************
321 \subsection{Main monad code}
323 %************************************************************************
326 initRn :: DynFlags -> Finder -> GlobalSymbolTable
327 -> PersistentRenamerState
330 -> IO (r, Bag ErrMsg, Bag WarnMsg)
332 initRn flags finder gst prs mod loc do_rn = do
333 himaps <- mkModuleHiMaps dirs
334 names_var <- newIORef (prsNS pcs)
335 errs_var <- newIORef (emptyBag,emptyBag)
336 iface_var <- newIORef (initIfaces prs)
338 rn_down = RnDown { rn_mod = mod,
347 rn_ifaces = iface_var,
351 res <- do_rn rn_down ()
353 -- grab errors and return
354 (warns, errs) <- readIORef errs_var
356 return (res, errs, warns)
359 initIfaces :: PersistentRenamerState -> Ifaces
361 = Ifaces { iDecls = prsDecls prs,
362 iInsts = prsInsts prs,
363 iRules = prsRules rules,
365 iFixes = emptyNameEnv,
366 iDeprecs = emptyNameEnv,
368 iImpModInfo = emptyFM,
369 iDeferred = emptyNameSet,
370 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
371 -- Pretend that the dummy unbound name has already been
372 -- slurped. This is what's returned for an out-of-scope name,
373 -- and we don't want thereby to try to suck it in!
378 initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r
379 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
381 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
382 rn_fixenv = fixity_env, rn_mode = mode }
384 thing_inside rn_down s_down
386 initIfaceRnMS :: Module -> RnMS r -> RnM d r
387 initIfaceRnMS mod thing_inside
388 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
389 setModuleRn mod thing_inside
391 builtins :: FiniteMap (ModuleName,OccName) Name
392 builtins = listToFM wired_in `plusFM` listToFM known_key
394 wired_in = [ ((moduleName (nameModule name), nameOccName name), name)
395 | name <- wiredInNames ]
397 known_key = [ ((rdrNameModule rdr_name, rdrNameOcc rdr_name), mkKnownKeyGlobal rdr_name uniq)
398 | (rdr_name, uniq) <- knownKeyRdrNames ]
401 @renameSourceCode@ is used to rename stuff ``out-of-line'';
402 that is, not as part of the main renamer.
403 Sole examples: derived definitions,
404 which are only generated in the type checker.
406 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
407 once you must either split it, or install a fresh unique supply.
410 renameSourceCode :: Module
415 renameSourceCode mod name_supply m
417 -- It's not really unsafe! When renaming source code we
418 -- only do any I/O if we need to read in a fixity declaration;
419 -- and that doesn't happen in pragmas etc
421 mkModuleHiMaps (mkSearchPath opt_HiMap) >>= \ himaps ->
422 newIORef name_supply >>= \ names_var ->
423 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
425 rn_down = RnDown { rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,
426 rn_errs = errs_var, rn_hi_maps = himaps,
428 rn_ifaces = panic "rnameSourceCode: rn_ifaces" -- Not required
430 s_down = SDown { rn_mode = InterfaceMode,
431 -- So that we can refer to PrelBase.True etc
432 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
433 rn_fixenv = emptyNameEnv }
435 m rn_down s_down >>= \ result ->
437 readIORef errs_var >>= \ (warns,errs) ->
439 (if not (isEmptyBag errs) then
440 pprTrace "Urk! renameSourceCode found errors" (display errs)
442 else if not (isEmptyBag warns) then
443 pprTrace "Note: renameSourceCode found warnings" (display warns)
451 display errs = pprBagOfErrors errs
453 {-# INLINE thenRn #-}
454 {-# INLINE thenRn_ #-}
455 {-# INLINE returnRn #-}
458 returnRn :: a -> RnM d a
459 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
460 thenRn_ :: RnM d a -> RnM d b -> RnM d b
461 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
462 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
463 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
464 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
465 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
466 sequenceRn :: [RnM d a] -> RnM d [a]
467 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
468 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
469 fixRn :: (a -> RnM d a) -> RnM d a
471 returnRn v gdown ldown = return v
472 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
473 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
474 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
475 andRn combiner m1 m2 gdown ldown
476 = m1 gdown ldown >>= \ res1 ->
477 m2 gdown ldown >>= \ res2 ->
478 return (combiner res1 res2)
480 sequenceRn [] = returnRn []
481 sequenceRn (m:ms) = m `thenRn` \ r ->
482 sequenceRn ms `thenRn` \ rs ->
485 mapRn f [] = returnRn []
487 = f x `thenRn` \ r ->
488 mapRn f xs `thenRn` \ rs ->
491 mapRn_ f [] = returnRn ()
496 foldlRn k z [] = returnRn z
497 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
500 mapAndUnzipRn f [] = returnRn ([],[])
501 mapAndUnzipRn f (x:xs)
502 = f x `thenRn` \ (r1, r2) ->
503 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
504 returnRn (r1:rs1, r2:rs2)
506 mapAndUnzip3Rn f [] = returnRn ([],[],[])
507 mapAndUnzip3Rn f (x:xs)
508 = f x `thenRn` \ (r1, r2, r3) ->
509 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
510 returnRn (r1:rs1, r2:rs2, r3:rs3)
512 mapMaybeRn f [] = returnRn []
513 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
514 mapMaybeRn f xs `thenRn` \ rs ->
516 Nothing -> returnRn rs
517 Just r -> returnRn (r:rs)
519 flatMapRn f [] = returnRn []
520 flatMapRn f (x:xs) = f x `thenRn` \ r ->
521 flatMapRn f xs `thenRn` \ rs ->
527 %************************************************************************
529 \subsection{Boring plumbing for common part}
531 %************************************************************************
535 \subsubsection{ Errors and warnings}
536 %=====================
539 failWithRn :: a -> Message -> RnM d a
540 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
541 = readIORef errs_var >>= \ (warns,errs) ->
542 writeIORef errs_var (warns, errs `snocBag` err) >>
545 err = addShortErrLocLine loc msg
547 warnWithRn :: a -> Message -> RnM d a
548 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
549 = readIORef errs_var >>= \ (warns,errs) ->
550 writeIORef errs_var (warns `snocBag` warn, errs) >>
553 warn = addShortWarnLocLine loc msg
555 addErrRn :: Message -> RnM d ()
556 addErrRn err = failWithRn () err
558 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
559 checkRn False err = addErrRn err
560 checkRn True err = returnRn ()
562 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
563 warnCheckRn False err = addWarnRn err
564 warnCheckRn True err = returnRn ()
566 addWarnRn :: Message -> RnM d ()
567 addWarnRn warn = warnWithRn () warn
569 checkErrsRn :: RnM d Bool -- True <=> no errors so far
570 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
571 = readIORef errs_var >>= \ (warns,errs) ->
572 return (isEmptyBag errs)
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{ Name supply}
592 %=====================
595 getNameSupplyRn :: RnM d NameSupply
596 getNameSupplyRn rn_down l_down
597 = readIORef (rn_ns rn_down)
599 setNameSupplyRn :: NameSupply -> RnM d ()
600 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
601 = writeIORef names_var names'
603 getUniqRn :: RnM d Unique
604 getUniqRn (RnDown {rn_ns = names_var}) l_down
605 = readIORef names_var >>= \ (us, cache, ipcache) ->
607 (us1,us') = splitUniqSupply us
609 writeIORef names_var (us', cache, ipcache) >>
610 return (uniqFromSupply us1)
614 \subsubsection{ Module}
615 %=====================
618 getModuleRn :: RnM d Module
619 getModuleRn (RnDown {rn_mod = mod}) l_down
622 setModuleRn :: Module -> RnM d a -> RnM d a
623 setModuleRn new_mod enclosed_thing rn_down l_down
624 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
628 %************************************************************************
630 \subsection{Plumbing for rename-source part}
632 %************************************************************************
635 \subsubsection{ RnEnv}
636 %=====================
639 getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)
640 getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})
641 = return (global_env, local_env)
643 getLocalNameEnv :: RnMS LocalRdrEnv
644 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
647 getGlobalNameEnv :: RnMS GlobalRdrEnv
648 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
651 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
652 setLocalNameEnv local_env' m rn_down l_down
653 = m rn_down (l_down {rn_lenv = local_env'})
655 getFixityEnv :: RnMS FixityEnv
656 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
659 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
660 extendFixityEnv fixes enclosed_scope
661 rn_down l_down@(SDown {rn_fixenv = fixity_env})
663 new_fixity_env = extendNameEnvList fixity_env fixes
665 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
669 \subsubsection{ Mode}
670 %=====================
673 getModeRn :: RnMS RnMode
674 getModeRn rn_down (SDown {rn_mode = mode})
677 setModeRn :: RnMode -> RnMS a -> RnMS a
678 setModeRn new_mode thing_inside rn_down l_down
679 = thing_inside rn_down (l_down {rn_mode = new_mode})
683 %************************************************************************
685 \subsection{Plumbing for rename-globals part}
687 %************************************************************************
690 getIfacesRn :: RnM d Ifaces
691 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
692 = readIORef iface_var
694 setIfacesRn :: Ifaces -> RnM d ()
695 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
696 = writeIORef iface_var ifaces
698 getHiMaps :: RnM d (SearchPath, ModuleHiMap, ModuleHiMap)
699 getHiMaps (RnDown {rn_hi_maps = himaps}) _