[project @ 2002-03-05 14:18:53 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 import HsSyn            
27 import RdrHsSyn
28 import RnHsSyn          ( RenamedFixitySig )
29 import HscTypes         ( AvailEnv, emptyAvailEnv, lookupType,
30                           NameSupply(..), 
31                           ImportedModuleInfo, WhetherHasOrphans, ImportVersion, 
32                           PersistentRenamerState(..),  RdrExportItem,
33                           DeclsMap, IfaceInsts, IfaceRules, 
34                           HomeSymbolTable, TyThing,
35                           PersistentCompilerState(..), GlobalRdrEnv, 
36                           LocalRdrEnv,
37                           HomeIfaceTable, PackageIfaceTable )
38 import BasicTypes       ( Version, defaultFixity )
39 import ErrUtils         ( addShortErrLocLine, addShortWarnLocLine,
40                           Message, Messages, errorsFound, warningsFound,
41                           printErrorsAndWarnings
42                         )
43 import RdrName          ( RdrName, dummyRdrVarName, rdrNameModule, rdrNameOcc,
44                           RdrNameEnv, emptyRdrEnv, extendRdrEnv, 
45                           addListToRdrEnv, rdrEnvToList, rdrEnvElts
46                         )
47 import Name             ( Name, OccName, NamedThing(..), 
48                           nameOccName,
49                           decode, mkLocalName, mkKnownKeyGlobal
50                         )
51 import NameEnv          ( NameEnv, lookupNameEnv, emptyNameEnv,
52                           extendNameEnvList )
53 import Module           ( Module, ModuleName, ModuleSet, emptyModuleSet,
54                           PackageName )
55 import PrelInfo         ( ghcPrimExports, 
56                           cCallableClassDecl, cReturnableClassDecl, assertDecl )
57 import PrelNames        ( mkUnboundName, gHC_PRIM_Name )
58 import NameSet          
59 import CmdLineOpts      ( DynFlags, DynFlag(..), dopt )
60 import SrcLoc           ( SrcLoc, generatedSrcLoc, noSrcLoc )
61 import Unique           ( Unique )
62 import FiniteMap        ( FiniteMap )
63 import Maybes           ( seqMaybe )
64 import Bag              ( Bag, emptyBag, isEmptyBag, snocBag )
65 import UniqSupply
66 import Outputable
67
68 import IOExts           ( IORef, newIORef, readIORef, writeIORef, 
69                           fixIO, unsafePerformIO )
70 import IO               ( hPutStr, stderr )
71         
72 infixr 9 `thenRn`, `thenRn_`
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection{Somewhat magical interface to other monads}
79 %*                                                                      *
80 %************************************************************************
81
82 \begin{code}
83 ioToRnM :: IO r -> RnM d (Either IOError r)
84 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok)) 
85                             `catch` 
86                             (\ err -> return (Left err))
87
88 ioToRnM_no_fail :: IO r -> RnM d r
89 ioToRnM_no_fail io rn_down g_down 
90    = (io >>= \ ok -> return ok) 
91      `catch` 
92      (\ err -> panic "ioToRnM_no_fail: the I/O operation failed!")
93             
94 traceRn :: SDoc -> RnM d ()
95 traceRn msg = ifOptRn Opt_D_dump_rn_trace (putDocRn msg)
96
97 traceHiDiffsRn :: SDoc -> RnM d ()
98 traceHiDiffsRn msg = ifOptRn Opt_D_dump_hi_diffs (putDocRn msg)
99
100 putDocRn :: SDoc -> RnM d ()
101 putDocRn msg = ioToRnM (printErrs alwaysQualify msg)    `thenRn_`
102                returnRn ()
103 \end{code}
104
105
106 %************************************************************************
107 %*                                                                      *
108 \subsection{Data types}
109 %*                                                                      *
110 %************************************************************************
111
112 %===================================================
113 \subsubsection{         MONAD TYPES}
114 %===================================================
115
116 \begin{code}
117 type RnM d r = RnDown -> d -> IO r
118 type RnMS r  = RnM SDown r              -- Renaming source
119 type RnMG r  = RnM ()    r              -- Getting global names etc
120
121         -- Common part
122 data RnDown
123   = RnDown {
124         rn_mod     :: Module,           -- This module
125         rn_loc     :: SrcLoc,           -- Current locn
126
127         rn_dflags  :: DynFlags,
128
129         rn_hit     :: HomeIfaceTable,
130         rn_done    :: Name -> Maybe TyThing,    -- Tells what things (both in the
131                                                 -- home package and other packages)
132                                                 -- were already available (i.e. in
133                                                 -- the relevant SymbolTable) before 
134                                                 -- compiling this module
135                         -- The Name passed to rn_done is guaranteed to be a Global,
136                         -- so it has a Module, so it can be looked up
137
138         rn_errs    :: IORef Messages,
139         rn_ns      :: IORef NameSupply,
140         rn_ifaces  :: IORef Ifaces
141     }
142
143         -- For renaming source code
144 data SDown = SDown {
145                   rn_mode :: RnMode,
146
147                   rn_genv :: GlobalRdrEnv,      -- Top level environment
148
149                   rn_avails :: AvailEnv,        
150                         -- Top level AvailEnv; contains all the things that
151                         -- are nameable in the top-level scope, regardless of
152                         -- *how* they can be named (qualified, unqualified...)
153                         -- It is used only to map a Class to its class ops, and 
154                         -- hence to resolve the binders in an instance decl
155
156                   rn_lenv :: LocalRdrEnv,       -- Local name envt
157                         --   Does *not* include global name envt; may shadow it
158                         --   Includes both ordinary variables and type variables;
159                         --   they are kept distinct because tyvar have a different
160                         --   occurrence contructor (Name.TvOcc)
161                         -- We still need the unsullied global name env so that
162                         --   we can look up record field names
163
164                   rn_fixenv :: LocalFixityEnv   -- Local fixities (for non-top-level
165                                                 -- declarations)
166                         -- The global fixities are held in the
167                         -- HIT or PIT.  Why?  See the comments
168                         -- with RnIfaces.lookupLocalFixity
169                 }
170
171 data RnMode     = SourceMode            -- Renaming source code
172                 | InterfaceMode         -- Renaming interface declarations.  
173                 | CmdLineMode           -- Renaming a command-line expression
174
175 isInterfaceMode InterfaceMode = True
176 isInterfaceMode _ = False
177
178 isCmdLineMode CmdLineMode = True
179 isCmdLineMode _ = False
180 \end{code}
181
182 %===================================================
183 \subsubsection{         ENVIRONMENTS}
184 %===================================================
185
186 \begin{code}
187 --------------------------------
188 type LocalFixityEnv = NameEnv RenamedFixitySig
189         -- We keep the whole fixity sig so that we
190         -- can report line-number info when there is a duplicate
191         -- fixity declaration
192
193 emptyLocalFixityEnv :: LocalFixityEnv
194 emptyLocalFixityEnv = emptyNameEnv
195
196 lookupLocalFixity :: LocalFixityEnv -> Name -> Fixity
197 lookupLocalFixity env name
198   = case lookupNameEnv env name of 
199         Just (FixitySig _ fix _) -> fix
200         Nothing                  -> defaultFixity
201 \end{code}
202
203 %************************************************************************
204 %*                                                                      *
205 \subsection{Interface file stuff}
206 %*                                                                      *
207 %************************************************************************
208
209 \begin{code}
210 type IfaceDeprecs = Maybe (Either DeprecTxt [(RdrName,DeprecTxt)])
211         -- Nothing        => NoDeprecs
212         -- Just (Left t)  => DeprecAll
213         -- Just (Right p) => DeprecSome
214
215 data ParsedIface
216   = ParsedIface {
217       pi_mod       :: ModuleName,
218       pi_pkg       :: PackageName,
219       pi_vers      :: Version,                          -- Module version number
220       pi_orphan    :: WhetherHasOrphans,                -- Whether this module has orphans
221       pi_usages    :: [ImportVersion OccName],          -- Usages
222       pi_exports   :: (Version, [RdrExportItem]),       -- Exports
223       pi_decls     :: [(Version, RdrNameTyClDecl)],     -- Local definitions
224       pi_fixity    :: [(RdrName,Fixity)],               -- Local fixity declarations,
225       pi_insts     :: [RdrNameInstDecl],                -- Local instance declarations
226       pi_rules     :: (Version, [RdrNameRuleDecl]),     -- Rules, with their version
227       pi_deprecs   :: IfaceDeprecs                      -- Deprecations
228     }
229 \end{code}
230
231 %************************************************************************
232 %*                                                                      *
233 \subsection{Wired-in interfaces}
234 %*                                                                      *
235 %************************************************************************
236
237 \begin{code}
238 ghcPrimIface :: ParsedIface
239 ghcPrimIface = ParsedIface {
240       pi_mod     = gHC_PRIM_Name,
241       pi_pkg     = FSLIT("base"),
242       pi_vers    = 1,
243       pi_orphan  = False,
244       pi_usages  = [],
245       pi_exports = (1, [(gHC_PRIM_Name, ghcPrimExports)]),
246       pi_decls   = [(1,cCallableClassDecl), 
247                     (1,cReturnableClassDecl), 
248                     (1,assertDecl)],
249       pi_fixity  = [],
250       pi_insts   = [],
251       pi_rules   = (1,[]),
252       pi_deprecs = Nothing
253  }
254 \end{code}
255
256 %************************************************************************
257 %*                                                                      *
258 \subsection{The renamer state}
259 %*                                                                      *
260 %************************************************************************
261
262 \begin{code}
263 data Ifaces = Ifaces {
264     -- PERSISTENT FIELDS
265         iPIT :: PackageIfaceTable,
266                 -- The ModuleIFaces for modules in other packages
267                 -- whose interfaces we have opened
268                 -- The declarations in these interface files are held in
269                 -- iDecls, iInsts, iRules (below), not in the mi_decls fields
270                 -- of the iPIT.  What _is_ in the iPIT is:
271                 --      * The Module 
272                 --      * Version info
273                 --      * Its exports
274                 --      * Fixities
275                 --      * Deprecations
276                 -- The iPIT field is initialised from the compiler's persistent
277                 -- package symbol table, and the renamer incrementally adds
278                 -- to it.
279
280         iImpModInfo :: ImportedModuleInfo,
281                         -- Modules that we know something about, because they are mentioned
282                         -- in interface files, BUT which we have not loaded yet.  
283                         -- No module is both in here and in the PIT
284
285         iDecls :: DeclsMap,     
286                 -- A single, global map of Names to unslurped decls
287
288         iInsts :: IfaceInsts,
289                 -- The as-yet un-slurped instance decls; this bag is depleted when we
290                 -- slurp an instance decl so that we don't slurp the same one twice.
291                 -- Each is 'gated' by the names that must be available before
292                 -- this instance decl is needed.
293
294         iRules :: IfaceRules,
295                 -- Similar to instance decls, only for rules
296
297     -- EPHEMERAL FIELDS
298     -- These fields persist during the compilation of a single module only
299         iSlurp :: NameSet,
300                 -- All the names (whether "big" or "small", whether wired-in or not,
301                 -- whether locally defined or not) that have been slurped in so far.
302                 --
303                 -- It's used for two things:
304                 --      a) To record what we've already slurped, so
305                 --         we can no-op if we try to slurp it again
306                 --      b) As the 'gates' for importing rules.  We import a rule
307                 --         if all its LHS free vars have been slurped
308
309         iVSlurp :: (ModuleSet, NameSet)
310                 -- The Names are all the (a) non-wired-in
311                 --                       (b) "big"
312                 --                       (c) non-locally-defined
313                 --                       (d) home-package
314                 -- names that have been slurped in so far, with their versions.
315                 -- This is used to generate the "usage" information for this module.
316                 -- Subset of the previous field.
317                 --
318                 -- The module set is the non-home-package modules from which we have
319                 -- slurped at least one name.
320                 -- It's worth keeping separately, because there's no very easy 
321                 -- way to distinguish the "big" names from the "non-big" ones.
322                 -- But this is a decision we might want to revisit.
323     }
324 \end{code}
325
326
327 %************************************************************************
328 %*                                                                      *
329 \subsection{Main monad code}
330 %*                                                                      *
331 %************************************************************************
332
333 \begin{code}
334 runRn dflags hit hst pcs mod do_rn
335   = do { (pcs, msgs, r) <- initRn dflags hit hst pcs mod do_rn ;
336          printErrorsAndWarnings alwaysQualify msgs ;
337          return (pcs, errorsFound msgs, r)
338     }
339
340 initRn :: DynFlags
341        -> HomeIfaceTable -> HomeSymbolTable
342        -> PersistentCompilerState
343        -> Module
344        -> RnMG t
345        -> IO (PersistentCompilerState, Messages, t)     
346
347 initRn dflags hit hst pcs mod do_rn
348   = do 
349         let prs = pcs_PRS pcs
350         let pte = pcs_PTE pcs
351         let ifaces = Ifaces { iPIT   = pcs_PIT pcs,
352                               iDecls = prsDecls prs,
353                               iInsts = prsInsts prs,
354                               iRules = prsRules prs,
355
356                               iImpModInfo = prsImpMods prs,
357                               iSlurp      = unitNameSet (mkUnboundName dummyRdrVarName),
358                                 -- Pretend that the dummy unbound name has already been
359                                 -- slurped.  This is what's returned for an out-of-scope name,
360                                 -- and we don't want thereby to try to suck it in!
361                               iVSlurp = (emptyModuleSet, emptyNameSet)
362                       }
363         names_var <- newIORef (prsOrig prs)
364         errs_var  <- newIORef (emptyBag,emptyBag)
365         iface_var <- newIORef ifaces
366         let rn_down = RnDown { rn_mod = mod,
367                                rn_loc = noSrcLoc, 
368         
369                                rn_dflags = dflags,
370                                rn_hit    = hit,
371                                rn_done   = lookupType hst pte,
372                                              
373                                rn_ns     = names_var, 
374                                rn_errs   = errs_var, 
375                                rn_ifaces = iface_var,
376                              }
377         
378         -- do the business
379         res <- do_rn rn_down ()
380         
381         -- Grab state and record it
382         (warns, errs)   <- readIORef errs_var
383         new_ifaces      <- readIORef iface_var
384         new_orig        <- readIORef names_var
385         let new_prs = prs { prsOrig    = new_orig,
386                             prsImpMods = iImpModInfo new_ifaces,
387                             prsDecls   = iDecls new_ifaces,
388                             prsInsts   = iInsts new_ifaces,
389                             prsRules   = iRules new_ifaces }
390         let new_pcs = pcs { pcs_PIT = iPIT new_ifaces, 
391                             pcs_PRS = new_prs }
392         
393         return (new_pcs, (warns, errs), res)
394
395 initRnMS :: GlobalRdrEnv -> AvailEnv -> LocalRdrEnv -> LocalFixityEnv -> RnMode
396          -> RnMS a -> RnM d a
397
398 initRnMS rn_env avails local_env fixity_env mode thing_inside rn_down g_down
399         -- The fixity_env appears in both the rn_fixenv field
400         -- and in the HIT.  See comments with RnHiFiles.lookupFixityRn
401   = let
402         s_down = SDown { rn_genv = rn_env, rn_avails = avails, 
403                          rn_lenv = local_env, rn_fixenv = fixity_env, 
404                          rn_mode = mode }
405     in
406     thing_inside rn_down s_down
407
408 initIfaceRnMS :: Module -> RnMS r -> RnM d r
409 initIfaceRnMS mod thing_inside 
410   = initRnMS emptyRdrEnv emptyAvailEnv emptyRdrEnv 
411              emptyLocalFixityEnv InterfaceMode
412              (setModuleRn mod thing_inside)
413 \end{code}
414
415 @renameDerivedCode@ is used to rename stuff ``out-of-line'';
416 that is, not as part of the main renamer.
417 Sole examples: derived definitions,
418 which are only generated in the type checker.
419
420 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
421 once you must either split it, or install a fresh unique supply.
422
423 \begin{code}
424 renameDerivedCode :: DynFlags 
425                   -> Module
426                   -> PersistentRenamerState
427                   -> RnMS r
428                   -> r
429
430 renameDerivedCode dflags mod prs thing_inside
431   = unsafePerformIO $
432         -- It's not really unsafe!  When renaming source code we
433         -- only do any I/O if we need to read in a fixity declaration;
434         -- and that doesn't happen in pragmas etc
435
436     do  { us <- mkSplitUniqSupply 'r'
437         ; names_var <- newIORef ((prsOrig prs) { nsUniqs = us })
438         ; errs_var <- newIORef (emptyBag,emptyBag)
439
440         ; let rn_down = RnDown { rn_dflags = dflags,
441                                  rn_loc    = generatedSrcLoc, rn_ns = names_var,
442                                  rn_errs   = errs_var, 
443                                  rn_mod    = mod, 
444                                  rn_done   = bogus "rn_done",   
445                                  rn_hit    = bogus "rn_hit",
446                                  rn_ifaces = bogus "rn_ifaces"
447                                }
448         ; let s_down = SDown { rn_mode = InterfaceMode, 
449                                -- So that we can refer to PrelBase.True etc
450                                rn_avails = emptyAvailEnv,
451                                rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
452                                rn_fixenv = emptyLocalFixityEnv }
453
454         ; result <- thing_inside rn_down s_down
455         ; messages <- readIORef errs_var
456
457         ; if bad messages then
458                 do { hPutStr stderr "Urk!  renameDerivedCode found errors or warnings"
459                    ; printErrorsAndWarnings alwaysQualify messages
460                    }
461            else
462                 return()
463
464         ; return result
465         }
466   where
467 #ifdef DEBUG
468     bad messages = errorsFound messages || warningsFound messages
469 #else
470     bad messages = errorsFound messages
471 #endif
472
473 bogus s = panic ("rnameSourceCode: " ++ s)  -- Used for unused record fields
474
475 {-# INLINE thenRn #-}
476 {-# INLINE thenRn_ #-}
477 {-# INLINE returnRn #-}
478 {-# INLINE andRn #-}
479
480 returnRn :: a -> RnM d a
481 thenRn   :: RnM d a -> (a -> RnM d b) -> RnM d b
482 thenRn_  :: RnM d a -> RnM d b -> RnM d b
483 andRn    :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
484 mapRn    :: (a -> RnM d b) -> [a] -> RnM d [b]
485 mapRn_   :: (a -> RnM d b) -> [a] -> RnM d ()
486 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
487 flatMapRn  :: (a -> RnM d [b])       -> [a] -> RnM d [b]
488 sequenceRn  :: [RnM d a] -> RnM d [a]
489 sequenceRn_ :: [RnM d a] -> RnM d ()
490 foldlRn :: (b  -> a -> RnM d b) -> b -> [a] -> RnM d b
491 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
492 fixRn    :: (a -> RnM d a) -> RnM d a
493
494 returnRn v gdown ldown  = return v
495 thenRn m k gdown ldown  = m gdown ldown >>= \ r -> k r gdown ldown
496 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
497 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
498 andRn combiner m1 m2 gdown ldown
499   = m1 gdown ldown >>= \ res1 ->
500     m2 gdown ldown >>= \ res2 ->
501     return (combiner res1 res2)
502
503 sequenceRn []     = returnRn []
504 sequenceRn (m:ms) =  m                  `thenRn` \ r ->
505                      sequenceRn ms      `thenRn` \ rs ->
506                      returnRn (r:rs)
507
508 sequenceRn_ []     = returnRn ()
509 sequenceRn_ (m:ms) = m `thenRn_` sequenceRn_ ms
510
511 mapRn f []     = returnRn []
512 mapRn f (x:xs)
513   = f x         `thenRn` \ r ->
514     mapRn f xs  `thenRn` \ rs ->
515     returnRn (r:rs)
516
517 mapRn_ f []     = returnRn ()
518 mapRn_ f (x:xs) = 
519     f x         `thenRn_`
520     mapRn_ f xs
521
522 foldlRn k z [] = returnRn z
523 foldlRn k z (x:xs) = k z x      `thenRn` \ z' ->
524                      foldlRn k z' xs
525
526 mapAndUnzipRn f [] = returnRn ([],[])
527 mapAndUnzipRn f (x:xs)
528   = f x                 `thenRn` \ (r1,  r2)  ->
529     mapAndUnzipRn f xs  `thenRn` \ (rs1, rs2) ->
530     returnRn (r1:rs1, r2:rs2)
531
532 mapAndUnzip3Rn f [] = returnRn ([],[],[])
533 mapAndUnzip3Rn f (x:xs)
534   = f x                 `thenRn` \ (r1,  r2,  r3)  ->
535     mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
536     returnRn (r1:rs1, r2:rs2, r3:rs3)
537
538 mapMaybeRn f []     = returnRn []
539 mapMaybeRn f (x:xs) = f x               `thenRn` \ maybe_r ->
540                       mapMaybeRn f xs   `thenRn` \ rs ->
541                       case maybe_r of
542                         Nothing -> returnRn rs
543                         Just r  -> returnRn (r:rs)
544
545 flatMapRn f []     = returnRn []
546 flatMapRn f (x:xs) = f x                `thenRn` \ r ->
547                      flatMapRn f xs     `thenRn` \ rs ->
548                      returnRn (r ++ rs)
549 \end{code}
550
551
552
553 %************************************************************************
554 %*                                                                      *
555 \subsection{Boring plumbing for common part}
556 %*                                                                      *
557 %************************************************************************
558
559
560 %================
561 \subsubsection{  Errors and warnings}
562 %=====================
563
564 \begin{code}
565 failWithRn :: a -> Message -> RnM d a
566 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
567   = readIORef  errs_var                                         >>=  \ (warns,errs) ->
568     writeIORef errs_var (warns, errs `snocBag` err)             >> 
569     return res
570   where
571     err = addShortErrLocLine loc msg
572
573 warnWithRn :: a -> Message -> RnM d a
574 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
575   = readIORef  errs_var                                         >>=  \ (warns,errs) ->
576     writeIORef errs_var (warns `snocBag` warn, errs)    >> 
577     return res
578   where
579     warn = addShortWarnLocLine loc msg
580
581 tryRn :: RnM d a -> RnM d (Either Messages a)
582 tryRn try_this down@(RnDown {rn_errs = errs_var}) l_down
583   = do current_msgs <- readIORef errs_var
584        writeIORef errs_var (emptyBag,emptyBag)
585        a <- try_this down l_down
586        (warns, errs) <- readIORef errs_var
587        writeIORef errs_var current_msgs
588        if (isEmptyBag errs)
589           then return (Right a)
590           else return (Left (warns,errs))
591
592 setErrsRn :: Messages -> RnM d ()
593 setErrsRn msgs down@(RnDown {rn_errs = errs_var}) l_down
594   = do writeIORef errs_var msgs; return ()
595
596 addErrRn :: Message -> RnM d ()
597 addErrRn err = failWithRn () err
598
599 checkRn :: Bool -> Message -> RnM d ()  -- Check that a condition is true
600 checkRn False err = addErrRn err
601 checkRn True  err = returnRn ()
602
603 warnCheckRn :: Bool -> Message -> RnM d ()      -- Check that a condition is true
604 warnCheckRn False err = addWarnRn err
605 warnCheckRn True  err = returnRn ()
606
607 addWarnRn :: Message -> RnM d ()
608 addWarnRn warn = warnWithRn () warn
609
610 checkErrsRn :: RnM d Bool               -- True <=> no errors so far
611 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
612   = readIORef  errs_var                                         >>=  \ (warns,errs) ->
613     return (isEmptyBag errs)
614
615 doptRn :: DynFlag -> RnM d Bool
616 doptRn dflag (RnDown { rn_dflags = dflags}) l_down
617    = return (dopt dflag dflags)
618
619 ifOptRn :: DynFlag -> RnM d a -> RnM d ()
620 ifOptRn dflag thing_inside down@(RnDown { rn_dflags = dflags}) l_down
621   | dopt dflag dflags = thing_inside down l_down >> return ()
622   | otherwise         = return ()
623
624 getDOptsRn :: RnM d DynFlags
625 getDOptsRn (RnDown { rn_dflags = dflags}) l_down
626    = return dflags
627 \end{code}
628
629
630 %================
631 \subsubsection{Source location}
632 %=====================
633
634 \begin{code}
635 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
636 pushSrcLocRn loc' m down l_down
637   = m (down {rn_loc = loc'}) l_down
638
639 getSrcLocRn :: RnM d SrcLoc
640 getSrcLocRn down l_down
641   = return (rn_loc down)
642 \end{code}
643
644 %================
645 \subsubsection{The finder and home symbol table}
646 %=====================
647
648 \begin{code}
649 getHomeIfaceTableRn :: RnM d HomeIfaceTable
650 getHomeIfaceTableRn down l_down = return (rn_hit down)
651
652 getTypeEnvRn :: RnM d (Name -> Maybe TyThing)
653 getTypeEnvRn down l_down = return (rn_done down)
654
655 extendTypeEnvRn :: NameEnv TyThing -> RnM d a -> RnM d a
656 extendTypeEnvRn env inside down l_down
657   = inside down{rn_done=new_rn_done} l_down
658   where new_rn_done = \nm -> lookupNameEnv env nm `seqMaybe` rn_done down nm
659 \end{code}
660
661 %================
662 \subsubsection{Name supply}
663 %=====================
664
665 \begin{code}
666 getNameSupplyRn :: RnM d NameSupply
667 getNameSupplyRn rn_down l_down
668   = readIORef (rn_ns rn_down)
669
670 setNameSupplyRn :: NameSupply -> RnM d ()
671 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
672   = writeIORef names_var names'
673
674 getUniqRn :: RnM d Unique
675 getUniqRn (RnDown {rn_ns = names_var}) l_down
676  = readIORef names_var >>= \ ns ->
677    let
678      (us1,us') = splitUniqSupply (nsUniqs ns)
679    in
680    writeIORef names_var (ns {nsUniqs = us'})    >>
681    return (uniqFromSupply us1)
682 \end{code}
683
684 %================
685 \subsubsection{  Module}
686 %=====================
687
688 \begin{code}
689 getModuleRn :: RnM d Module
690 getModuleRn (RnDown {rn_mod = mod}) l_down
691   = return mod
692
693 setModuleRn :: Module -> RnM d a -> RnM d a
694 setModuleRn new_mod enclosed_thing rn_down l_down
695   = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
696 \end{code}
697
698
699 %************************************************************************
700 %*                                                                      *
701 \subsection{Plumbing for rename-source part}
702 %*                                                                      *
703 %************************************************************************
704
705 %================
706 \subsubsection{  RnEnv}
707 %=====================
708
709 \begin{code}
710 getLocalNameEnv :: RnMS LocalRdrEnv
711 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
712   = return local_env
713
714 getGlobalNameEnv :: RnMS GlobalRdrEnv
715 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
716   = return global_env
717
718 getGlobalAvails :: RnMS AvailEnv
719 getGlobalAvails  rn_down (SDown {rn_avails = avails})
720   = return avails
721
722 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
723 setLocalNameEnv local_env' m rn_down l_down
724   = m rn_down (l_down {rn_lenv = local_env'})
725
726 getFixityEnv :: RnMS LocalFixityEnv
727 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
728   = return fixity_env
729
730 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
731 extendFixityEnv fixes enclosed_scope
732                 rn_down l_down@(SDown {rn_fixenv = fixity_env})
733   = let
734         new_fixity_env = extendNameEnvList fixity_env fixes
735     in
736     enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
737 \end{code}
738
739 %================
740 \subsubsection{  Mode}
741 %=====================
742
743 \begin{code}
744 getModeRn :: RnMS RnMode
745 getModeRn rn_down (SDown {rn_mode = mode})
746   = return mode
747
748 setModeRn :: RnMode -> RnMS a -> RnMS a
749 setModeRn new_mode thing_inside rn_down l_down
750   = thing_inside rn_down (l_down {rn_mode = new_mode})
751 \end{code}
752
753
754 %************************************************************************
755 %*                                                                      *
756 \subsection{Plumbing for rename-globals part}
757 %*                                                                      *
758 %************************************************************************
759
760 \begin{code}
761 getIfacesRn :: RnM d Ifaces
762 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
763   = readIORef iface_var
764
765 setIfacesRn :: Ifaces -> RnM d ()
766 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
767   = writeIORef iface_var ifaces
768 \end{code}