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, mkKnownKeyGlobal,
49 NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv,
52 import Module ( Module, ModuleName, WhereFrom, moduleName )
54 import CmdLineOpts ( DynFlags, dopt_D_dump_rn_trace )
55 import SrcLoc ( SrcLoc, mkGeneratedSrcLoc )
56 import Unique ( Unique )
57 import FiniteMap ( FiniteMap, emptyFM, listToFM, plusFM )
58 import Bag ( Bag, mapBag, emptyBag, isEmptyBag, snocBag )
61 import CmFind ( Finder )
62 import PrelNames ( mkUnboundName )
63 import HscTypes ( GlobalSymbolTable, OrigNameEnv, AvailEnv,
64 WhetherHasOrphans, ImportVersion, ExportItem,
65 PersistentRenamerState(..), IsBootInterface, Avails,
66 DeclsMap, IfaceInsts, IfaceRules, DeprecationEnv )
68 infixr 9 `thenRn`, `thenRn_`
72 %************************************************************************
74 \subsection{Somewhat magical interface to other monads}
76 %************************************************************************
79 ioToRnM :: IO r -> RnM d (Either IOError r)
80 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
82 (\ err -> return (Left err))
84 traceRn :: SDoc -> RnM d ()
86 = doptsRn dopt_D_dump_rn_trace `thenRn` \b ->
87 if b then putDocRn msg else returnRn ()
89 putDocRn :: SDoc -> RnM d ()
90 putDocRn msg = ioToRnM (printErrs msg) `thenRn_`
95 %************************************************************************
97 \subsection{Data types}
99 %************************************************************************
101 %===================================================
102 \subsubsection{ MONAD TYPES}
103 %===================================================
106 type RnM d r = RnDown -> d -> IO r
107 type RnMS r = RnM SDown r -- Renaming source
108 type RnMG r = RnM () r -- Getting global names etc
113 rn_mod :: Module, -- This module
114 rn_loc :: SrcLoc, -- Current locn
117 rn_dflags :: DynFlags,
118 rn_gst :: GlobalSymbolTable, -- Both home modules and packages,
119 -- at the moment we started compiling
122 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
123 rn_ns :: IORef (UniqSupply, OrigNameEnv),
124 rn_ifaces :: IORef Ifaces
127 -- For renaming source code
131 rn_genv :: GlobalRdrEnv, -- Global envt
133 rn_lenv :: LocalRdrEnv, -- Local name envt
134 -- Does *not* include global name envt; may shadow it
135 -- Includes both ordinary variables and type variables;
136 -- they are kept distinct because tyvar have a different
137 -- occurrence contructor (Name.TvOcc)
138 -- We still need the unsullied global name env so that
139 -- we can look up record field names
141 rn_fixenv :: FixityEnv -- Local fixities
142 -- The global fixities are held in the
143 -- rn_ifaces field. Why? See the comments
144 -- with RnIfaces.lookupFixity
147 data RnMode = SourceMode -- Renaming source code
148 | InterfaceMode -- Renaming interface declarations.
151 %===================================================
152 \subsubsection{ ENVIRONMENTS}
153 %===================================================
156 --------------------------------
157 type GlobalRdrEnv = RdrNameEnv [Name] -- The list is because there may be name clashes
158 -- These only get reported on lookup,
159 -- not on construction
160 type LocalRdrEnv = RdrNameEnv Name
162 --------------------------------
163 type FixityEnv = NameEnv RenamedFixitySig
164 -- We keep the whole fixity sig so that we
165 -- can report line-number info when there is a duplicate
166 -- fixity declaration
168 lookupFixity :: FixityEnv -> Name -> Fixity
169 lookupFixity env name
170 = case lookupNameEnv env name of
171 Just (FixitySig _ fix _) -> fix
172 Nothing -> defaultFixity
176 type ExportAvails = (FiniteMap ModuleName Avails,
177 -- Used to figure out "module M" export specifiers
178 -- Includes avails only from *unqualified* imports
179 -- (see 1.4 Report Section 5.1.1)
181 AvailEnv) -- Used to figure out all other export specifiers.
184 %===================================================
185 \subsubsection{ INTERFACE FILE STUFF}
186 %===================================================
192 pi_mod :: Module, -- Complete with package info
193 pi_vers :: Version, -- Module version number
194 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
195 pi_usages :: [ImportVersion OccName], -- Usages
196 pi_exports :: [ExportItem], -- Exports
197 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
198 pi_decls :: [(Version, RdrNameHsDecl)], -- Local definitions
199 pi_fixity :: (Version, [RdrNameFixitySig]), -- Local fixity declarations, with their version
200 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
201 pi_deprecs :: [RdrNameDeprecation] -- Deprecations
205 type RdrNamePragma = () -- Fudge for now
210 %************************************************************************
212 \subsection{The renamer state}
214 %************************************************************************
217 data Ifaces = Ifaces {
220 iImpModInfo :: ImportedModuleInfo,
221 -- Modules this one depends on: that is, the union
222 -- of the modules its *direct* imports depend on.
223 -- NB: The direct imports have .hi files that enumerate *all* the
224 -- dependencies (direct or not) of the imported module.
226 iDecls :: DeclsMap, -- A single, global map of Names to decls
227 -- we can get away with importing them abstractly
229 iInsts :: IfaceInsts,
230 -- The as-yet un-slurped instance decls; this bag is depleted when we
231 -- slurp an instance decl so that we don't slurp the same one twice.
232 -- Each is 'gated' by the names that must be available before
233 -- this instance decl is needed.
235 iRules :: IfaceRules,
236 -- Similar to instance decls, only for rules
238 -- SEMI-EPHEMERAL FIELDS
239 -- iFixes and iDeprecs are accumulated here while one module
240 -- is compiled, but are transferred to the package symbol table
241 -- at the end. We don't add them to the table as we encounter them
242 -- because doing so would require us to have a mutable symbol table
245 iFixes :: FixityEnv, -- A single, global map of Names to fixities
246 -- See comments with RnIfaces.lookupFixity
247 iDeprecs :: DeprecationEnv,
250 -- These fields persist during the compilation of a single module only
253 -- All the names (whether "big" or "small", whether wired-in or not,
254 -- whether locally defined or not) that have been slurped in so far.
256 iVSlurp :: [(Name,Version)]
257 -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
258 -- names that have been slurped in so far, with their versions.
259 -- This is used to generate the "usage" information for this module.
260 -- Subset of the previous field.
263 type ImportedModuleInfo
264 = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface,
265 Maybe (Module, Version, Version, Version, WhereFrom, Avails))
266 -- The three Versions are module version, fixity version, rules version
268 -- Suppose the domain element is module 'A'
270 -- The first Bool is True if A contains
271 -- 'orphan' rules or instance decls
273 -- The second Bool is true if the interface file actually
274 -- read was an .hi-boot file
276 -- Nothing => A's interface not yet read, but this module has
277 -- imported a module, B, that itself depends on A
279 -- Just xx => A's interface has been read. The Module in
280 -- the Just has the correct Dll flag
282 -- This set is used to decide whether to look for
283 -- A.hi or A.hi-boot when importing A.f.
284 -- Basically, we look for A.hi if A is in the map, and A.hi-boot
289 %************************************************************************
291 \subsection{Main monad code}
293 %************************************************************************
296 initRn :: DynFlags -> Finder -> GlobalSymbolTable
297 -> PersistentRenamerState
300 -> IO (t, Bag WarnMsg, Bag ErrMsg)
302 initRn dflags finder gst prs mod loc do_rn
303 = do uniqs <- mkSplitUniqSupply 'r'
304 names_var <- newIORef (uniqs, prsOrig prs)
305 errs_var <- newIORef (emptyBag,emptyBag)
306 iface_var <- newIORef (initIfaces prs)
307 let rn_down = RnDown { rn_mod = mod,
316 rn_ifaces = iface_var,
320 res <- do_rn rn_down ()
322 -- grab errors and return
323 (warns, errs) <- readIORef errs_var
325 return (res, errs, warns)
328 initIfaces :: PersistentRenamerState -> Ifaces
330 = Ifaces { iDecls = prsDecls prs,
331 iInsts = prsInsts prs,
332 iRules = prsRules prs,
334 iFixes = emptyNameEnv,
335 iDeprecs = emptyNameEnv,
337 iImpModInfo = emptyFM,
338 --iDeferred = emptyNameSet,
339 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
340 -- Pretend that the dummy unbound name has already been
341 -- slurped. This is what's returned for an out-of-scope name,
342 -- and we don't want thereby to try to suck it in!
347 initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r
348 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
350 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
351 rn_fixenv = fixity_env, rn_mode = mode }
353 thing_inside rn_down s_down
355 initIfaceRnMS :: Module -> RnMS r -> RnM d r
356 initIfaceRnMS mod thing_inside
357 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
358 setModuleRn mod thing_inside
362 @renameSourceCode@ is used to rename stuff ``out-of-line'';
363 that is, not as part of the main renamer.
364 Sole examples: derived definitions,
365 which are only generated in the type checker.
367 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
368 once you must either split it, or install a fresh unique supply.
371 renameSourceCode :: DynFlags
373 -> PersistentRenamerState
377 renameSourceCode dflags mod prs m
379 -- It's not really unsafe! When renaming source code we
380 -- only do any I/O if we need to read in a fixity declaration;
381 -- and that doesn't happen in pragmas etc
383 mkSplitUniqSupply 'r' >>= \ new_us ->
384 newIORef (new_us, prsOrig prs) >>= \ names_var ->
385 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
387 rn_down = RnDown { rn_dflags = dflags,
388 rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,
391 rn_ifaces = panic "rnameSourceCode: rn_ifaces" -- Not required
393 s_down = SDown { rn_mode = InterfaceMode,
394 -- So that we can refer to PrelBase.True etc
395 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
396 rn_fixenv = emptyNameEnv }
398 m rn_down s_down >>= \ result ->
400 readIORef errs_var >>= \ (warns,errs) ->
402 (if not (isEmptyBag errs) then
403 pprTrace "Urk! renameSourceCode found errors" (display errs)
405 else if not (isEmptyBag warns) then
406 pprTrace "Note: renameSourceCode found warnings" (display warns)
414 display errs = pprBagOfErrors errs
416 {-# INLINE thenRn #-}
417 {-# INLINE thenRn_ #-}
418 {-# INLINE returnRn #-}
421 returnRn :: a -> RnM d a
422 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
423 thenRn_ :: RnM d a -> RnM d b -> RnM d b
424 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
425 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
426 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
427 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
428 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
429 sequenceRn :: [RnM d a] -> RnM d [a]
430 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
431 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
432 fixRn :: (a -> RnM d a) -> RnM d a
434 returnRn v gdown ldown = return v
435 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
436 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
437 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
438 andRn combiner m1 m2 gdown ldown
439 = m1 gdown ldown >>= \ res1 ->
440 m2 gdown ldown >>= \ res2 ->
441 return (combiner res1 res2)
443 sequenceRn [] = returnRn []
444 sequenceRn (m:ms) = m `thenRn` \ r ->
445 sequenceRn ms `thenRn` \ rs ->
448 mapRn f [] = returnRn []
450 = f x `thenRn` \ r ->
451 mapRn f xs `thenRn` \ rs ->
454 mapRn_ f [] = returnRn ()
459 foldlRn k z [] = returnRn z
460 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
463 mapAndUnzipRn f [] = returnRn ([],[])
464 mapAndUnzipRn f (x:xs)
465 = f x `thenRn` \ (r1, r2) ->
466 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
467 returnRn (r1:rs1, r2:rs2)
469 mapAndUnzip3Rn f [] = returnRn ([],[],[])
470 mapAndUnzip3Rn f (x:xs)
471 = f x `thenRn` \ (r1, r2, r3) ->
472 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
473 returnRn (r1:rs1, r2:rs2, r3:rs3)
475 mapMaybeRn f [] = returnRn []
476 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
477 mapMaybeRn f xs `thenRn` \ rs ->
479 Nothing -> returnRn rs
480 Just r -> returnRn (r:rs)
482 flatMapRn f [] = returnRn []
483 flatMapRn f (x:xs) = f x `thenRn` \ r ->
484 flatMapRn f xs `thenRn` \ rs ->
490 %************************************************************************
492 \subsection{Boring plumbing for common part}
494 %************************************************************************
498 \subsubsection{ Errors and warnings}
499 %=====================
502 failWithRn :: a -> Message -> RnM d a
503 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
504 = readIORef errs_var >>= \ (warns,errs) ->
505 writeIORef errs_var (warns, errs `snocBag` err) >>
508 err = addShortErrLocLine loc msg
510 warnWithRn :: a -> Message -> RnM d a
511 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
512 = readIORef errs_var >>= \ (warns,errs) ->
513 writeIORef errs_var (warns `snocBag` warn, errs) >>
516 warn = addShortWarnLocLine loc msg
518 addErrRn :: Message -> RnM d ()
519 addErrRn err = failWithRn () err
521 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
522 checkRn False err = addErrRn err
523 checkRn True err = returnRn ()
525 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
526 warnCheckRn False err = addWarnRn err
527 warnCheckRn True err = returnRn ()
529 addWarnRn :: Message -> RnM d ()
530 addWarnRn warn = warnWithRn () warn
532 checkErrsRn :: RnM d Bool -- True <=> no errors so far
533 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
534 = readIORef errs_var >>= \ (warns,errs) ->
535 return (isEmptyBag errs)
537 doptsRn :: (DynFlags -> Bool) -> RnM d Bool
538 doptsRn dopt (RnDown { rn_dflags = dflags}) l_down
539 = return (dopt dflags)
544 \subsubsection{ Source location}
545 %=====================
548 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
549 pushSrcLocRn loc' m down l_down
550 = m (down {rn_loc = loc'}) l_down
552 getSrcLocRn :: RnM d SrcLoc
553 getSrcLocRn down l_down
554 = return (rn_loc down)
558 \subsubsection{ Name supply}
559 %=====================
562 getNameSupplyRn :: RnM d (UniqSupply, OrigNameEnv)
563 getNameSupplyRn rn_down l_down
564 = readIORef (rn_ns rn_down)
566 setNameSupplyRn :: (UniqSupply, OrigNameEnv) -> RnM d ()
567 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
568 = writeIORef names_var names'
570 getUniqRn :: RnM d Unique
571 getUniqRn (RnDown {rn_ns = names_var}) l_down
572 = readIORef names_var >>= \ (us, {-cache,-} ipcache) ->
574 (us1,us') = splitUniqSupply us
576 writeIORef names_var (us', {-cache,-} ipcache) >>
577 return (uniqFromSupply us1)
581 \subsubsection{ Module}
582 %=====================
585 getModuleRn :: RnM d Module
586 getModuleRn (RnDown {rn_mod = mod}) l_down
589 setModuleRn :: Module -> RnM d a -> RnM d a
590 setModuleRn new_mod enclosed_thing rn_down l_down
591 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
595 %************************************************************************
597 \subsection{Plumbing for rename-source part}
599 %************************************************************************
602 \subsubsection{ RnEnv}
603 %=====================
606 getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)
607 getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})
608 = return (global_env, local_env)
610 getLocalNameEnv :: RnMS LocalRdrEnv
611 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
614 getGlobalNameEnv :: RnMS GlobalRdrEnv
615 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
618 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
619 setLocalNameEnv local_env' m rn_down l_down
620 = m rn_down (l_down {rn_lenv = local_env'})
622 getFixityEnv :: RnMS FixityEnv
623 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
626 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
627 extendFixityEnv fixes enclosed_scope
628 rn_down l_down@(SDown {rn_fixenv = fixity_env})
630 new_fixity_env = extendNameEnvList fixity_env fixes
632 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
636 \subsubsection{ Mode}
637 %=====================
640 getModeRn :: RnMS RnMode
641 getModeRn rn_down (SDown {rn_mode = mode})
644 setModeRn :: RnMode -> RnMS a -> RnMS a
645 setModeRn new_mode thing_inside rn_down l_down
646 = thing_inside rn_down (l_down {rn_mode = new_mode})
650 %************************************************************************
652 \subsection{Plumbing for rename-globals part}
654 %************************************************************************
657 getIfacesRn :: RnM d Ifaces
658 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
659 = readIORef iface_var
661 setIfacesRn :: Ifaces -> RnM d ()
662 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
663 = writeIORef iface_var ifaces