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