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