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