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