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