[project @ 1999-09-15 13:48:25 by sof]
[ghc-hetmet.git] / ghc / compiler / rename / RnMonad.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnMonad]{The monad used by the renamer}
5
6 \begin{code}
7 module RnMonad(
8         module RnMonad,
9         Module,
10         FiniteMap,
11         Bag,
12         Name,
13         RdrNameHsDecl,
14         RdrNameInstDecl,
15         Version,
16         NameSet,
17         OccName,
18         Fixity
19     ) where
20
21 #include "HsVersions.h"
22
23 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 302
24 import PrelIOBase       ( fixIO )       -- Should be in GlaExts
25 #else
26 import IOBase           ( fixIO )
27 #endif
28 import IOExts           ( IORef, newIORef, readIORef, writeIORef, unsafePerformIO )
29         
30 import HsSyn            
31 import RdrHsSyn
32 import RnHsSyn          ( RenamedFixitySig )
33 import BasicTypes       ( Version )
34 import SrcLoc           ( noSrcLoc )
35 import ErrUtils         ( addShortErrLocLine, addShortWarnLocLine,
36                           pprBagOfErrors, ErrMsg, WarnMsg, Message
37                         )
38 import Name             ( Name, OccName, NamedThing(..),
39                           isLocallyDefinedName, nameModule, nameOccName,
40                           decode, mkLocalName
41                         )
42 import Module           ( Module, ModuleName, ModuleHiMap, SearchPath, WhereFrom,
43                           mkModuleHiMaps, moduleName, mkVanillaModule, mkSearchPath
44                         )
45 import NameSet          
46 import RdrName          ( RdrName, dummyRdrVarName, rdrNameOcc )
47 import CmdLineOpts      ( opt_D_dump_rn_trace, opt_IgnoreIfacePragmas, opt_HiMap )
48 import PrelInfo         ( builtinNames )
49 import TysWiredIn       ( boolTyCon )
50 import SrcLoc           ( SrcLoc, mkGeneratedSrcLoc )
51 import Unique           ( Unique, getUnique, unboundKey )
52 import UniqFM           ( UniqFM )
53 import FiniteMap        ( FiniteMap, emptyFM, bagToFM, lookupFM, addToFM, addListToFM, 
54                           addListToFM_C, addToFM_C, eltsFM, fmToList
55                         )
56 import Bag              ( Bag, mapBag, emptyBag, isEmptyBag, snocBag )
57 import Maybes           ( mapMaybe )
58 import UniqSet
59 import UniqFM
60 import UniqSupply
61 import Util
62 import Outputable
63
64 infixr 9 `thenRn`, `thenRn_`
65 \end{code}
66
67
68 %************************************************************************
69 %*                                                                      *
70 \subsection{Somewhat magical interface to other monads}
71 %*                                                                      *
72 %************************************************************************
73
74 \begin{code}
75 ioToRnM :: IO r -> RnM d (Either IOError r)
76 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok)) 
77                             `catch` 
78                             (\ err -> return (Left err))
79             
80 traceRn :: SDoc -> RnM d ()
81 traceRn msg | opt_D_dump_rn_trace = putDocRn msg
82             | otherwise           = returnRn ()
83
84 putDocRn :: SDoc -> RnM d ()
85 putDocRn msg = ioToRnM (printErrs msg)  `thenRn_`
86                returnRn ()
87 \end{code}
88
89
90 %************************************************************************
91 %*                                                                      *
92 \subsection{Data types}
93 %*                                                                      *
94 %************************************************************************
95
96 %===================================================
97 \subsubsection{         MONAD TYPES}
98 %===================================================
99
100 \begin{code}
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
104
105         -- Common part
106 data RnDown = RnDown {
107                   rn_mod     :: ModuleName,
108                   rn_loc     :: SrcLoc,
109                   rn_ns      :: IORef RnNameSupply,
110                   rn_errs    :: IORef (Bag WarnMsg, Bag ErrMsg),
111                   rn_ifaces  :: IORef Ifaces,
112                   rn_hi_maps :: (ModuleHiMap,   -- for .hi files
113                                  ModuleHiMap)   -- for .hi-boot files
114                 }
115
116         -- For renaming source code
117 data SDown = SDown {
118                   rn_mode :: RnMode,
119
120                   rn_genv :: GlobalRdrEnv,
121                         --   Global envt; the fixity component gets extended
122                         --   with local fixity decls
123
124                   rn_lenv :: LocalRdrEnv,       -- Local name envt
125                         --   Does *not* include global name envt; may shadow it
126                         --   Includes both ordinary variables and type variables;
127                         --   they are kept distinct because tyvar have a different
128                         --   occurrence contructor (Name.TvOcc)
129                         -- We still need the unsullied global name env so that
130                         --   we can look up record field names
131
132                   rn_fixenv :: FixityEnv        -- Local fixities
133                                                 -- The global ones are held in the
134                                                 -- rn_ifaces field
135                 }
136
137 data RnMode     = SourceMode                    -- Renaming source code
138                 | InterfaceMode                 -- Renaming interface declarations.  
139 \end{code}
140
141 %===================================================
142 \subsubsection{         ENVIRONMENTS}
143 %===================================================
144
145 \begin{code}
146 --------------------------------
147 type RdrNameEnv a = FiniteMap RdrName a
148 type GlobalRdrEnv = RdrNameEnv [Name]   -- The list is because there may be name clashes
149                                         -- These only get reported on lookup,
150                                         -- not on construction
151 type LocalRdrEnv  = RdrNameEnv Name
152
153 emptyRdrEnv  :: RdrNameEnv a
154 lookupRdrEnv :: RdrNameEnv a -> RdrName -> Maybe a
155 addListToRdrEnv :: RdrNameEnv a -> [(RdrName,a)] -> RdrNameEnv a
156 extendRdrEnv    :: RdrNameEnv a -> RdrName -> a -> RdrNameEnv a
157
158 emptyRdrEnv  = emptyFM
159 lookupRdrEnv = lookupFM
160 addListToRdrEnv = addListToFM
161 rdrEnvElts      = eltsFM
162 extendRdrEnv    = addToFM
163 rdrEnvToList    = fmToList
164
165 --------------------------------
166 type NameEnv a = UniqFM a       -- Domain is Name
167
168 emptyNameEnv   :: NameEnv a
169 nameEnvElts    :: NameEnv a -> [a]
170 addToNameEnv_C :: (a->a->a) -> NameEnv a -> Name -> a -> NameEnv a
171 addToNameEnv   :: NameEnv a -> Name -> a -> NameEnv a
172 plusNameEnv    :: NameEnv a -> NameEnv a -> NameEnv a
173 extendNameEnv  :: NameEnv a -> [(Name,a)] -> NameEnv a
174 lookupNameEnv  :: NameEnv a -> Name -> Maybe a
175 delFromNameEnv :: NameEnv a -> Name -> NameEnv a
176 elemNameEnv    :: Name -> NameEnv a -> Bool
177
178 emptyNameEnv   = emptyUFM
179 nameEnvElts    = eltsUFM
180 addToNameEnv_C = addToUFM_C
181 addToNameEnv   = addToUFM
182 plusNameEnv    = plusUFM
183 extendNameEnv  = addListToUFM
184 lookupNameEnv  = lookupUFM
185 delFromNameEnv = delFromUFM
186 elemNameEnv    = elemUFM
187
188 --------------------------------
189 type FixityEnv = NameEnv RenamedFixitySig
190         -- We keep the whole fixity sig so that we
191         -- can report line-number info when there is a duplicate
192         -- fixity declaration
193 \end{code}
194
195 \begin{code}
196 --------------------------------
197 type RnNameSupply
198  = ( UniqSupply
199
200    , FiniteMap String Int
201         -- This is used as a name supply for dictionary functions
202         -- From the inst decl we derive a string, usually by glomming together
203         -- the class and tycon name -- but it doesn't matter exactly how;
204         -- this map then gives a unique int for each inst decl with that
205         -- string.  (In Haskell 98 there can only be one,
206         -- but not so in more extended versions; also class CC type T
207         -- and class C type TT might both give the string CCT
208         --      
209         -- We could just use one Int for all the instance decls, but this
210         -- way the uniques change less when you add an instance decl,   
211         -- hence less recompilation
212
213    , FiniteMap (ModuleName, OccName) Name
214         -- Ensures that one (module,occname) pair gets one unique
215    )
216
217
218 --------------------------------
219 data ExportEnv    = ExportEnv Avails Fixities
220 type Avails       = [AvailInfo]
221 type Fixities     = [(Name, Fixity)]
222
223 type ExportAvails = (FiniteMap ModuleName Avails,
224         -- Used to figure out "module M" export specifiers
225         -- Includes avails only from *unqualified* imports
226         -- (see 1.4 Report Section 5.1.1)
227
228         NameEnv AvailInfo)      -- Used to figure out all other export specifiers.
229                                 -- Maps a Name to the AvailInfo that contains it
230
231
232 data GenAvailInfo name  = Avail name     -- An ordinary identifier
233                         | AvailTC name   -- The name of the type or class
234                                   [name] -- The available pieces of type/class.
235                                          -- NB: If the type or class is itself
236                                          -- to be in scope, it must be in this list.
237                                          -- Thus, typically: AvailTC Eq [Eq, ==, /=]
238
239 type AvailInfo    = GenAvailInfo Name
240 type RdrAvailInfo = GenAvailInfo OccName
241 \end{code}
242
243 %===================================================
244 \subsubsection{         INTERFACE FILE STUFF}
245 %===================================================
246
247 \begin{code}
248 type ExportItem          = (ModuleName, [RdrAvailInfo])
249 type VersionInfo name    = [ImportVersion name]
250
251 type ImportVersion name  = (ModuleName, Version, WhetherHasOrphans, WhatsImported name)
252
253 type WhetherHasOrphans   = Bool
254         -- An "orphan" is 
255         --      * an instance decl in a module other than the defn module for 
256         --              one of the tycons or classes in the instance head
257         --      * a transformation rule in a module other than the one defining
258         --              the function in the head of the rule.
259
260 data WhatsImported name  = Everything 
261                          | Specifically [LocalVersion name] -- List guaranteed non-empty
262
263     -- ("M", hif, ver, Everything) means there was a "module M" in 
264     -- this module's export list, so we just have to go by M's version, "ver",
265     -- not the list of LocalVersions.
266
267
268 type LocalVersion name   = (name, Version)
269
270 data ParsedIface
271   = ParsedIface {
272       pi_mod       :: Version,                          -- Module version number
273       pi_orphan    :: WhetherHasOrphans,                -- Whether this module has orphans
274       pi_usages    :: [ImportVersion OccName],          -- Usages
275       pi_exports   :: [ExportItem],                     -- Exports
276       pi_decls     :: [(Version, RdrNameHsDecl)],       -- Local definitions
277       pi_insts     :: [RdrNameInstDecl],                -- Local instance declarations
278       pi_rules     :: [RdrNameRuleDecl]                 -- Rules
279     }
280
281 type InterfaceDetails = (WhetherHasOrphans,
282                          VersionInfo Name, -- Version information for what this module imports
283                          ExportEnv)        -- What modules this one depends on
284
285
286 -- needed by Main to fish out the fixities assoc list.
287 getIfaceFixities :: InterfaceDetails -> Fixities
288 getIfaceFixities (_, _, ExportEnv _ fs) = fs
289
290
291 type RdrNamePragma = ()                         -- Fudge for now
292 -------------------
293
294 data Ifaces = Ifaces {
295                 iImpModInfo :: ImportedModuleInfo,
296                                 -- Modules this one depends on: that is, the union 
297                                 -- of the modules its *direct* imports depend on.
298                                 -- NB: The direct imports have .hi files that enumerate *all* the
299                                 -- dependencies (direct or not) of the imported module.
300
301                 iDecls :: DeclsMap,     -- A single, global map of Names to decls
302
303                 iFixes :: FixityEnv,    -- A single, global map of Names to fixities
304
305                 iSlurp :: NameSet,
306                 -- All the names (whether "big" or "small", whether wired-in or not,
307                 -- whether locally defined or not) that have been slurped in so far.
308
309                 iVSlurp :: [(Name,Version)],
310                 -- All the (a) non-wired-in (b) "big" (c) non-locally-defined 
311                 -- names that have been slurped in so far, with their versions.
312                 -- This is used to generate the "usage" information for this module.
313                 -- Subset of the previous field.
314
315                 iInsts :: Bag GatedDecl,
316                 -- The as-yet un-slurped instance decls; this bag is depleted when we
317                 -- slurp an instance decl so that we don't slurp the same one twice.
318                 -- Each is 'gated' by the names that must be available before
319                 -- this instance decl is needed.
320
321                 iRules :: Bag GatedDecl
322                         -- Ditto transformation rules
323         }
324
325 type GatedDecl = (NameSet, (Module, RdrNameHsDecl))
326
327 type ImportedModuleInfo 
328      = FiniteMap ModuleName (Version, Bool, Maybe (Module, Bool, Avails))
329                 -- Suppose the domain element is module 'A'
330                 --
331                 -- The first Bool is True if A contains 
332                 -- 'orphan' rules or instance decls
333
334                 -- The second Bool is true if the interface file actually
335                 -- read was an .hi-boot file
336
337                 -- Nothing => A's interface not yet read, but this module has
338                 --            imported a module, B, that itself depends on A
339                 --
340                 -- Just xx => A's interface has been read.  The Module in 
341                 --              the Just has the correct Dll flag
342
343                 -- This set is used to decide whether to look for
344                 -- A.hi or A.hi-boot when importing A.f.
345                 -- Basically, we look for A.hi if A is in the map, and A.hi-boot
346                 -- otherwise
347
348 type DeclsMap = NameEnv (Version, AvailInfo, Bool, (Module, RdrNameHsDecl))
349                 -- A DeclsMap contains a binding for each Name in the declaration
350                 -- including the constructors of a type decl etc.
351                 -- The Bool is True just for the 'main' Name.
352 \end{code}
353
354
355 %************************************************************************
356 %*                                                                      *
357 \subsection{Main monad code}
358 %*                                                                      *
359 %************************************************************************
360
361 \begin{code}
362 initRn :: ModuleName -> UniqSupply -> SearchPath -> SrcLoc
363        -> RnMG r
364        -> IO (r, Bag ErrMsg, Bag WarnMsg)
365
366 initRn mod us dirs loc do_rn = do
367   himaps    <- mkModuleHiMaps dirs
368   names_var <- newIORef (us, emptyFM, builtins)
369   errs_var  <- newIORef (emptyBag,emptyBag)
370   iface_var <- newIORef emptyIfaces 
371   let
372         rn_down = RnDown { rn_loc = loc, rn_ns = names_var, 
373                            rn_errs = errs_var, 
374                            rn_hi_maps = himaps, 
375                            rn_ifaces = iface_var,
376                            rn_mod = mod }
377
378         -- do the business
379   res <- do_rn rn_down ()
380
381         -- grab errors and return
382   (warns, errs) <- readIORef errs_var
383
384   return (res, errs, warns)
385
386
387 initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r
388 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
389   = let
390         s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv, 
391                          rn_fixenv = fixity_env, rn_mode = mode }
392     in
393     thing_inside rn_down s_down
394
395 initIfaceRnMS :: Module -> RnMS r -> RnM d r
396 initIfaceRnMS mod thing_inside 
397   = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
398     setModuleRn (moduleName mod) thing_inside
399
400 emptyIfaces :: Ifaces
401 emptyIfaces = Ifaces { iImpModInfo = emptyFM,
402                        iDecls = emptyNameEnv,
403                        iFixes = emptyNameEnv,
404                        iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
405                         -- Pretend that the dummy unbound name has already been
406                         -- slurped.  This is what's returned for an out-of-scope name,
407                         -- and we don't want thereby to try to suck it in!
408                        iVSlurp = [],
409                        iInsts = emptyBag,
410                        iRules = emptyBag
411               }
412
413 -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
414 -- during compiler debugging.
415 mkUnboundName :: RdrName -> Name
416 mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc
417
418 isUnboundName :: Name -> Bool
419 isUnboundName name = getUnique name == unboundKey
420
421 builtins :: FiniteMap (ModuleName,OccName) Name
422 builtins = 
423    bagToFM (
424    mapBag (\ name ->  ((moduleName (nameModule name), nameOccName name), name))
425           builtinNames)
426 \end{code}
427
428 @renameSourceCode@ is used to rename stuff ``out-of-line'';
429 that is, not as part of the main renamer.
430 Sole examples: derived definitions,
431 which are only generated in the type checker.
432
433 The @RnNameSupply@ includes a @UniqueSupply@, so if you call it more than
434 once you must either split it, or install a fresh unique supply.
435
436 \begin{code}
437 renameSourceCode :: ModuleName
438                  -> RnNameSupply
439                  -> RnMS r
440                  -> r
441
442 renameSourceCode mod_name name_supply m
443   = unsafePerformIO (
444         -- It's not really unsafe!  When renaming source code we
445         -- only do any I/O if we need to read in a fixity declaration;
446         -- and that doesn't happen in pragmas etc
447
448         mkModuleHiMaps (mkSearchPath opt_HiMap) >>= \ himaps ->
449         newIORef name_supply            >>= \ names_var ->
450         newIORef (emptyBag,emptyBag)    >>= \ errs_var ->
451         let
452             rn_down = RnDown { rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,
453                                rn_errs = errs_var, rn_hi_maps = himaps,
454                                rn_mod = mod_name }
455             s_down = SDown { rn_mode = InterfaceMode,
456                                -- So that we can refer to PrelBase.True etc
457                              rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
458                              rn_fixenv = emptyNameEnv }
459         in
460         m rn_down s_down                        >>= \ result ->
461         
462         readIORef errs_var                      >>= \ (warns,errs) ->
463
464         (if not (isEmptyBag errs) then
465                 pprTrace "Urk! renameSourceCode found errors" (display errs) 
466 #ifdef DEBUG
467          else if not (isEmptyBag warns) then
468                 pprTrace "Note: renameSourceCode found warnings" (display warns)
469 #endif
470          else
471                 id) $
472
473         return result
474     )
475   where
476     display errs = pprBagOfErrors errs
477
478 {-# INLINE thenRn #-}
479 {-# INLINE thenRn_ #-}
480 {-# INLINE returnRn #-}
481 {-# INLINE andRn #-}
482
483 returnRn :: a -> RnM d a
484 thenRn   :: RnM d a -> (a -> RnM d b) -> RnM d b
485 thenRn_  :: RnM d a -> RnM d b -> RnM d b
486 andRn    :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
487 mapRn    :: (a -> RnM d b) -> [a] -> RnM d [b]
488 mapRn_   :: (a -> RnM d b) -> [a] -> RnM d ()
489 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
490 sequenceRn :: [RnM d a] -> RnM d [a]
491 foldlRn :: (b  -> a -> RnM d b) -> b -> [a] -> RnM d b
492 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
493 fixRn    :: (a -> RnM d a) -> RnM d a
494
495 returnRn v gdown ldown  = return v
496 thenRn m k gdown ldown  = m gdown ldown >>= \ r -> k r gdown ldown
497 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
498 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
499 andRn combiner m1 m2 gdown ldown
500   = m1 gdown ldown >>= \ res1 ->
501     m2 gdown ldown >>= \ res2 ->
502     return (combiner res1 res2)
503
504 sequenceRn []     = returnRn []
505 sequenceRn (m:ms) =  m                  `thenRn` \ r ->
506                      sequenceRn ms      `thenRn` \ rs ->
507                      returnRn (r:rs)
508
509 mapRn f []     = returnRn []
510 mapRn f (x:xs)
511   = f x         `thenRn` \ r ->
512     mapRn f xs  `thenRn` \ rs ->
513     returnRn (r:rs)
514
515 mapRn_ f []     = returnRn ()
516 mapRn_ f (x:xs) = 
517     f x         `thenRn_`
518     mapRn_ f xs
519
520 foldlRn k z [] = returnRn z
521 foldlRn k z (x:xs) = k z x      `thenRn` \ z' ->
522                      foldlRn k z' xs
523
524 mapAndUnzipRn f [] = returnRn ([],[])
525 mapAndUnzipRn f (x:xs)
526   = f x                 `thenRn` \ (r1,  r2)  ->
527     mapAndUnzipRn f xs  `thenRn` \ (rs1, rs2) ->
528     returnRn (r1:rs1, r2:rs2)
529
530 mapAndUnzip3Rn f [] = returnRn ([],[],[])
531 mapAndUnzip3Rn f (x:xs)
532   = f x                 `thenRn` \ (r1,  r2,  r3)  ->
533     mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
534     returnRn (r1:rs1, r2:rs2, r3:rs3)
535
536 mapMaybeRn f []     = returnRn []
537 mapMaybeRn f (x:xs) = f x               `thenRn` \ maybe_r ->
538                       mapMaybeRn f xs   `thenRn` \ rs ->
539                       case maybe_r of
540                         Nothing -> returnRn rs
541                         Just r  -> returnRn (r:rs)
542 \end{code}
543
544
545
546 %************************************************************************
547 %*                                                                      *
548 \subsection{Boring plumbing for common part}
549 %*                                                                      *
550 %************************************************************************
551
552
553 %================
554 \subsubsection{  Errors and warnings}
555 %=====================
556
557 \begin{code}
558 failWithRn :: a -> Message -> RnM d a
559 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
560   = readIORef  errs_var                                         >>=  \ (warns,errs) ->
561     writeIORef errs_var (warns, errs `snocBag` err)             >> 
562     return res
563   where
564     err = addShortErrLocLine loc msg
565
566 warnWithRn :: a -> Message -> RnM d a
567 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
568   = readIORef  errs_var                                         >>=  \ (warns,errs) ->
569     writeIORef errs_var (warns `snocBag` warn, errs)    >> 
570     return res
571   where
572     warn = addShortWarnLocLine loc msg
573
574 addErrRn :: Message -> RnM d ()
575 addErrRn err = failWithRn () err
576
577 checkRn :: Bool -> Message -> RnM d ()  -- Check that a condition is true
578 checkRn False err = addErrRn err
579 checkRn True  err = returnRn ()
580
581 warnCheckRn :: Bool -> Message -> RnM d ()      -- Check that a condition is true
582 warnCheckRn False err = addWarnRn err
583 warnCheckRn True  err = returnRn ()
584
585 addWarnRn :: Message -> RnM d ()
586 addWarnRn warn = warnWithRn () warn
587
588 checkErrsRn :: RnM d Bool               -- True <=> no errors so far
589 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
590   = readIORef  errs_var                                         >>=  \ (warns,errs) ->
591     return (isEmptyBag errs)
592 \end{code}
593
594
595 %================
596 \subsubsection{  Source location}
597 %=====================
598
599 \begin{code}
600 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
601 pushSrcLocRn loc' m down l_down
602   = m (down {rn_loc = loc'}) l_down
603
604 getSrcLocRn :: RnM d SrcLoc
605 getSrcLocRn down l_down
606   = return (rn_loc down)
607 \end{code}
608
609 %================
610 \subsubsection{  Name supply}
611 %=====================
612
613 \begin{code}
614 getNameSupplyRn :: RnM d RnNameSupply
615 getNameSupplyRn rn_down l_down
616   = readIORef (rn_ns rn_down)
617
618 setNameSupplyRn :: RnNameSupply -> RnM d ()
619 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
620   = writeIORef names_var names'
621
622 -- See comments with RnNameSupply above.
623 newInstUniq :: String -> RnM d Int
624 newInstUniq key (RnDown {rn_ns = names_var}) l_down
625   = readIORef names_var                         >>= \ (us, mapInst, cache) ->
626     let
627         uniq = case lookupFM mapInst key of
628                    Just x  -> x+1
629                    Nothing -> 0
630         mapInst' = addToFM mapInst key uniq
631     in
632     writeIORef names_var (us, mapInst', cache)  >>
633     return uniq
634
635 getUniqRn :: RnM d Unique
636 getUniqRn (RnDown {rn_ns = names_var}) l_down
637  = readIORef names_var >>= \ (us, mapInst, cache) ->
638    let
639      (us1,us') = splitUniqSupply us
640    in
641    writeIORef names_var (us', mapInst, cache)  >>
642    return (uniqFromSupply us1)
643 \end{code}
644
645 %================
646 \subsubsection{  Module}
647 %=====================
648
649 \begin{code}
650 getModuleRn :: RnM d ModuleName
651 getModuleRn (RnDown {rn_mod = mod_name}) l_down
652   = return mod_name
653
654 setModuleRn :: ModuleName -> RnM d a -> RnM d a
655 setModuleRn new_mod enclosed_thing rn_down l_down
656   = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
657 \end{code}
658
659
660 %************************************************************************
661 %*                                                                      *
662 \subsection{Plumbing for rename-source part}
663 %*                                                                      *
664 %************************************************************************
665
666 %================
667 \subsubsection{  RnEnv}
668 %=====================
669
670 \begin{code}
671 getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)
672 getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})
673   = return (global_env, local_env)
674
675 getLocalNameEnv :: RnMS LocalRdrEnv
676 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
677   = return local_env
678
679 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
680 setLocalNameEnv local_env' m rn_down l_down
681   = m rn_down (l_down {rn_lenv = local_env'})
682
683 getFixityEnv :: RnMS FixityEnv
684 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
685   = return fixity_env
686
687 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
688 extendFixityEnv fixes enclosed_scope
689                 rn_down l_down@(SDown {rn_fixenv = fixity_env})
690   = let
691         new_fixity_env = extendNameEnv fixity_env fixes
692     in
693     enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
694 \end{code}
695
696 %================
697 \subsubsection{  Mode}
698 %=====================
699
700 \begin{code}
701 getModeRn :: RnMS RnMode
702 getModeRn rn_down (SDown {rn_mode = mode})
703   = return mode
704
705 setModeRn :: RnMode -> RnMS a -> RnMS a
706 setModeRn new_mode thing_inside rn_down l_down
707   = thing_inside rn_down (l_down {rn_mode = new_mode})
708 \end{code}
709
710
711 %************************************************************************
712 %*                                                                      *
713 \subsection{Plumbing for rename-globals part}
714 %*                                                                      *
715 %************************************************************************
716
717 \begin{code}
718 getIfacesRn :: RnM d Ifaces
719 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
720   = readIORef iface_var
721
722 setIfacesRn :: Ifaces -> RnM d ()
723 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
724   = writeIORef iface_var ifaces
725
726 getHiMaps :: RnM d (ModuleHiMap, ModuleHiMap)
727 getHiMaps (RnDown {rn_hi_maps = himaps}) _ 
728   = return himaps
729 \end{code}
730
731 \begin{code}
732 lookupModuleRn :: ModuleName -> RnM d Module
733 lookupModuleRn x = 
734   getHiMaps `thenRn` \ (himap, _) ->
735   case lookupFM himap x of
736     Nothing    -> returnRn (mkVanillaModule x)
737     Just (_,x) -> returnRn x
738
739 \end{code}