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