2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnMonad]{The monad used by the renamer}
10 module RdrName, -- Re-exports
11 module Name, -- from these two
24 #include "HsVersions.h"
26 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 405
27 import IOExts ( fixIO )
28 #elif defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 302
29 import PrelIOBase ( fixIO ) -- Should be in GlaExts
31 import IOBase ( fixIO )
33 import IOExts ( IORef, newIORef, readIORef, writeIORef, unsafePerformIO )
37 import RnHsSyn ( RenamedFixitySig )
38 import HscTypes ( AvailEnv, lookupTypeEnv,
39 OrigNameEnv(..), OrigNameNameEnv, OrigNameIParamEnv,
40 WhetherHasOrphans, ImportVersion,
41 PersistentRenamerState(..), IsBootInterface, Avails,
42 DeclsMap, IfaceInsts, IfaceRules,
43 HomeSymbolTable, PackageSymbolTable,
44 PersistentCompilerState(..), GlobalRdrEnv,
45 HomeIfaceTable, PackageIfaceTable,
47 import BasicTypes ( Version, defaultFixity )
48 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
49 pprBagOfErrors, ErrMsg, WarnMsg, Message
51 import RdrName ( RdrName, dummyRdrVarName, rdrNameModule, rdrNameOcc,
52 RdrNameEnv, emptyRdrEnv, extendRdrEnv,
53 addListToRdrEnv, rdrEnvToList, rdrEnvElts
55 import Name ( Name, OccName, NamedThing(..), getSrcLoc,
56 isLocallyDefinedName, nameOccName,
57 decode, mkLocalName, mkKnownKeyGlobal,
58 NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv,
61 import Module ( Module, ModuleName )
63 import CmdLineOpts ( DynFlags, DynFlag(..), dopt )
64 import SrcLoc ( SrcLoc, generatedSrcLoc, noSrcLoc )
65 import Unique ( Unique )
66 import FiniteMap ( FiniteMap, emptyFM )
67 import Bag ( Bag, emptyBag, isEmptyBag, snocBag )
70 import PrelNames ( mkUnboundName )
71 import Maybes ( maybeToBool, seqMaybe )
72 import ErrUtils ( printErrorsAndWarnings )
74 infixr 9 `thenRn`, `thenRn_`
78 %************************************************************************
80 \subsection{Somewhat magical interface to other monads}
82 %************************************************************************
85 ioToRnM :: IO r -> RnM d (Either IOError r)
86 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
88 (\ err -> return (Left err))
90 traceRn :: SDoc -> RnM d ()
92 = doptRn Opt_D_dump_rn_trace `thenRn` \b ->
93 if b then putDocRn msg else returnRn ()
95 putDocRn :: SDoc -> RnM d ()
96 putDocRn msg = ioToRnM (printErrs msg) `thenRn_`
101 %************************************************************************
103 \subsection{Data types}
105 %************************************************************************
107 %===================================================
108 \subsubsection{ MONAD TYPES}
109 %===================================================
112 type RnM d r = RnDown -> d -> IO r
113 type RnMS r = RnM SDown r -- Renaming source
114 type RnMG r = RnM () r -- Getting global names etc
119 rn_mod :: Module, -- This module
120 rn_loc :: SrcLoc, -- Current locn
122 rn_dflags :: DynFlags,
124 rn_hit :: HomeIfaceTable,
125 rn_done :: Name -> Bool, -- Tells what things (both in the
126 -- home package and other packages)
127 -- were already available (i.e. in
128 -- the relevant SymbolTable) before
129 -- compiling this module
131 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
133 -- The second and third components are a flattened-out OrigNameEnv
134 rn_ns :: IORef (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv),
135 rn_ifaces :: IORef Ifaces
138 -- For renaming source code
142 rn_genv :: GlobalRdrEnv, -- Global envt
144 rn_lenv :: LocalRdrEnv, -- Local name envt
145 -- Does *not* include global name envt; may shadow it
146 -- Includes both ordinary variables and type variables;
147 -- they are kept distinct because tyvar have a different
148 -- occurrence contructor (Name.TvOcc)
149 -- We still need the unsullied global name env so that
150 -- we can look up record field names
152 rn_fixenv :: LocalFixityEnv -- Local fixities
153 -- The global fixities are held in the
154 -- rn_ifaces field. Why? See the comments
155 -- with RnIfaces.lookupLocalFixity
158 data RnMode = SourceMode -- Renaming source code
159 | InterfaceMode -- Renaming interface declarations.
162 %===================================================
163 \subsubsection{ ENVIRONMENTS}
164 %===================================================
167 --------------------------------
168 type LocalRdrEnv = RdrNameEnv Name
169 type LocalFixityEnv = NameEnv RenamedFixitySig
170 -- We keep the whole fixity sig so that we
171 -- can report line-number info when there is a duplicate
172 -- fixity declaration
174 lookupLocalFixity :: LocalFixityEnv -> Name -> Fixity
175 lookupLocalFixity env name
176 = case lookupNameEnv env name of
177 Just (FixitySig _ fix _) -> fix
178 Nothing -> defaultFixity
182 type ExportAvails = (FiniteMap ModuleName Avails,
183 -- Used to figure out "module M" export specifiers
184 -- Includes avails only from *unqualified* imports
185 -- (see 1.4 Report Section 5.1.1)
187 AvailEnv) -- Used to figure out all other export specifiers.
190 %===================================================
191 \subsubsection{ INTERFACE FILE STUFF}
192 %===================================================
195 type ExportItem = (ModuleName, [RdrAvailInfo])
196 type IfaceDeprecs = Maybe (Either DeprecTxt [(RdrName,DeprecTxt)])
197 -- Nothing => NoDeprecs
198 -- Just (Left t) => DeprecAll
199 -- Just (Right p) => DeprecSome
203 pi_mod :: Module, -- Complete with package info
204 pi_vers :: Version, -- Module version number
205 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
206 pi_usages :: [ImportVersion OccName], -- Usages
207 pi_exports :: (Version, [ExportItem]), -- Exports
208 pi_decls :: [(Version, RdrNameTyClDecl)], -- Local definitions
209 pi_fixity :: [RdrNameFixitySig], -- Local fixity declarations,
210 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
211 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
212 pi_deprecs :: IfaceDeprecs -- Deprecations
216 %************************************************************************
218 \subsection{The renamer state}
220 %************************************************************************
223 data Ifaces = Ifaces {
225 iPIT :: PackageIfaceTable,
226 -- The ModuleIFaces for modules in other packages
227 -- whose interfaces we have opened
228 -- The declarations in these interface files are held in
229 -- iDecls, iInsts, iRules (below), not in the mi_decls fields
230 -- of the iPIT. What _is_ in the iPIT is:
236 -- The iPIT field is initialised from the compiler's persistent
237 -- package symbol table, and the renamer incrementally adds
241 -- A single, global map of Names to unslurped decls
243 iInsts :: IfaceInsts,
244 -- The as-yet un-slurped instance decls; this bag is depleted when we
245 -- slurp an instance decl so that we don't slurp the same one twice.
246 -- Each is 'gated' by the names that must be available before
247 -- this instance decl is needed.
249 iRules :: IfaceRules,
250 -- Similar to instance decls, only for rules
253 -- These fields persist during the compilation of a single module only
254 iImpModInfo :: ImportedModuleInfo,
255 -- Modules this one depends on: that is, the union
256 -- of the modules its *direct* imports depend on.
257 -- NB: The direct imports have .hi files that enumerate *all* the
258 -- dependencies (direct or not) of the imported module.
261 -- All the names (whether "big" or "small", whether wired-in or not,
262 -- whether locally defined or not) that have been slurped in so far.
265 -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
266 -- names that have been slurped in so far, with their versions.
267 -- This is used to generate the "usage" information for this module.
268 -- Subset of the previous field.
269 -- It's worth keeping separately, because there's no very easy
270 -- way to distinguish the "big" names from the "non-big" ones.
271 -- But this is a decision we might want to revisit.
274 type ImportedModuleInfo = FiniteMap ModuleName
275 (WhetherHasOrphans, IsBootInterface, IsLoaded)
280 %************************************************************************
282 \subsection{Main monad code}
284 %************************************************************************
288 -> HomeIfaceTable -> HomeSymbolTable
289 -> PersistentCompilerState
292 -> IO (PersistentCompilerState, Bool, t)
293 -- True <=> found errors
295 initRn dflags hit hst pcs mod do_rn
297 let prs = pcs_PRS pcs
298 let pst = pcs_PST pcs
299 let ifaces = Ifaces { iPIT = pcs_PIT pcs,
300 iDecls = prsDecls prs,
301 iInsts = prsInsts prs,
302 iRules = prsRules prs,
304 iImpModInfo = emptyFM,
305 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
306 -- Pretend that the dummy unbound name has already been
307 -- slurped. This is what's returned for an out-of-scope name,
308 -- and we don't want thereby to try to suck it in!
311 let uniqs = prsNS prs
313 names_var <- newIORef (uniqs, origNames (prsOrig prs),
314 origIParam (prsOrig prs))
315 errs_var <- newIORef (emptyBag,emptyBag)
316 iface_var <- newIORef ifaces
317 let rn_down = RnDown { rn_mod = mod,
322 rn_done = is_done hst pst,
326 rn_ifaces = iface_var,
330 res <- do_rn rn_down ()
332 -- Grab state and record it
333 (warns, errs) <- readIORef errs_var
334 new_ifaces <- readIORef iface_var
335 (new_NS, new_origN, new_origIP) <- readIORef names_var
336 let new_orig = Orig { origNames = new_origN, origIParam = new_origIP }
337 let new_prs = prs { prsOrig = new_orig,
338 prsDecls = iDecls new_ifaces,
339 prsInsts = iInsts new_ifaces,
340 prsRules = iRules new_ifaces,
342 let new_pcs = pcs { pcs_PIT = iPIT new_ifaces,
345 -- Check for warnings
346 printErrorsAndWarnings (warns, errs) ;
348 return (new_pcs, not (isEmptyBag errs), res)
350 is_done :: HomeSymbolTable -> PackageSymbolTable -> Name -> Bool
351 -- Returns True iff the name is in either symbol table
352 is_done hst pst n = maybeToBool (lookupTypeEnv pst n `seqMaybe` lookupTypeEnv hst n)
354 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
356 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
357 rn_fixenv = fixity_env, rn_mode = mode }
359 thing_inside rn_down s_down
361 initIfaceRnMS :: Module -> RnMS r -> RnM d r
362 initIfaceRnMS mod thing_inside
363 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
364 setModuleRn mod thing_inside
368 @renameSourceCode@ is used to rename stuff ``out-of-line'';
369 that is, not as part of the main renamer.
370 Sole examples: derived definitions,
371 which are only generated in the type checker.
373 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
374 once you must either split it, or install a fresh unique supply.
377 renameSourceCode :: DynFlags
379 -> PersistentRenamerState
383 renameSourceCode dflags mod prs m
385 -- It's not really unsafe! When renaming source code we
386 -- only do any I/O if we need to read in a fixity declaration;
387 -- and that doesn't happen in pragmas etc
389 mkSplitUniqSupply 'r' >>= \ new_us ->
390 newIORef (new_us, origNames (prsOrig prs),
391 origIParam (prsOrig prs)) >>= \ names_var ->
392 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
394 rn_down = RnDown { rn_dflags = dflags,
395 rn_loc = generatedSrcLoc, rn_ns = names_var,
398 rn_done = bogus "rn_done", rn_hit = bogus "rn_hit",
399 rn_ifaces = bogus "rn_ifaces"
401 s_down = SDown { rn_mode = InterfaceMode,
402 -- So that we can refer to PrelBase.True etc
403 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
404 rn_fixenv = emptyNameEnv }
406 m rn_down s_down >>= \ result ->
408 readIORef errs_var >>= \ (warns,errs) ->
410 (if not (isEmptyBag errs) then
411 pprTrace "Urk! renameSourceCode found errors" (display errs)
413 else if not (isEmptyBag warns) then
414 pprTrace "Note: renameSourceCode found warnings" (display warns)
422 display errs = pprBagOfErrors errs
424 bogus s = panic ("rnameSourceCode: " ++ s) -- Used for unused record fields
426 {-# INLINE thenRn #-}
427 {-# INLINE thenRn_ #-}
428 {-# INLINE returnRn #-}
431 returnRn :: a -> RnM d a
432 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
433 thenRn_ :: RnM d a -> RnM d b -> RnM d b
434 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
435 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
436 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
437 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
438 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
439 sequenceRn :: [RnM d a] -> RnM d [a]
440 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
441 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
442 fixRn :: (a -> RnM d a) -> RnM d a
444 returnRn v gdown ldown = return v
445 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
446 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
447 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
448 andRn combiner m1 m2 gdown ldown
449 = m1 gdown ldown >>= \ res1 ->
450 m2 gdown ldown >>= \ res2 ->
451 return (combiner res1 res2)
453 sequenceRn [] = returnRn []
454 sequenceRn (m:ms) = m `thenRn` \ r ->
455 sequenceRn ms `thenRn` \ rs ->
458 mapRn f [] = returnRn []
460 = f x `thenRn` \ r ->
461 mapRn f xs `thenRn` \ rs ->
464 mapRn_ f [] = returnRn ()
469 foldlRn k z [] = returnRn z
470 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
473 mapAndUnzipRn f [] = returnRn ([],[])
474 mapAndUnzipRn f (x:xs)
475 = f x `thenRn` \ (r1, r2) ->
476 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
477 returnRn (r1:rs1, r2:rs2)
479 mapAndUnzip3Rn f [] = returnRn ([],[],[])
480 mapAndUnzip3Rn f (x:xs)
481 = f x `thenRn` \ (r1, r2, r3) ->
482 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
483 returnRn (r1:rs1, r2:rs2, r3:rs3)
485 mapMaybeRn f [] = returnRn []
486 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
487 mapMaybeRn f xs `thenRn` \ rs ->
489 Nothing -> returnRn rs
490 Just r -> returnRn (r:rs)
492 flatMapRn f [] = returnRn []
493 flatMapRn f (x:xs) = f x `thenRn` \ r ->
494 flatMapRn f xs `thenRn` \ rs ->
500 %************************************************************************
502 \subsection{Boring plumbing for common part}
504 %************************************************************************
508 \subsubsection{ Errors and warnings}
509 %=====================
512 failWithRn :: a -> Message -> RnM d a
513 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
514 = readIORef errs_var >>= \ (warns,errs) ->
515 writeIORef errs_var (warns, errs `snocBag` err) >>
518 err = addShortErrLocLine loc msg
520 warnWithRn :: a -> Message -> RnM d a
521 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
522 = readIORef errs_var >>= \ (warns,errs) ->
523 writeIORef errs_var (warns `snocBag` warn, errs) >>
526 warn = addShortWarnLocLine loc msg
528 addErrRn :: Message -> RnM d ()
529 addErrRn err = failWithRn () err
531 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
532 checkRn False err = addErrRn err
533 checkRn True err = returnRn ()
535 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
536 warnCheckRn False err = addWarnRn err
537 warnCheckRn True err = returnRn ()
539 addWarnRn :: Message -> RnM d ()
540 addWarnRn warn = warnWithRn () warn
542 checkErrsRn :: RnM d Bool -- True <=> no errors so far
543 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
544 = readIORef errs_var >>= \ (warns,errs) ->
545 return (isEmptyBag errs)
547 doptRn :: DynFlag -> RnM d Bool
548 doptRn dflag (RnDown { rn_dflags = dflags}) l_down
549 = return (dopt dflag dflags)
551 getDOptsRn :: RnM d DynFlags
552 getDOptsRn (RnDown { rn_dflags = dflags}) l_down
558 \subsubsection{Source location}
559 %=====================
562 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
563 pushSrcLocRn loc' m down l_down
564 = m (down {rn_loc = loc'}) l_down
566 getSrcLocRn :: RnM d SrcLoc
567 getSrcLocRn down l_down
568 = return (rn_loc down)
572 \subsubsection{The finder and home symbol table}
573 %=====================
576 getHomeIfaceTableRn :: RnM d HomeIfaceTable
577 getHomeIfaceTableRn down l_down = return (rn_hit down)
579 checkAlreadyAvailable :: Name -> RnM d Bool
580 checkAlreadyAvailable name down l_down = return (rn_done down name)
584 \subsubsection{Name supply}
585 %=====================
588 getNameSupplyRn :: RnM d (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv)
589 getNameSupplyRn rn_down l_down
590 = readIORef (rn_ns rn_down)
592 setNameSupplyRn :: (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv) -> RnM d ()
593 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
594 = writeIORef names_var names'
596 getUniqRn :: RnM d Unique
597 getUniqRn (RnDown {rn_ns = names_var}) l_down
598 = readIORef names_var >>= \ (us, cache, ipcache) ->
600 (us1,us') = splitUniqSupply us
602 writeIORef names_var (us', cache, ipcache) >>
603 return (uniqFromSupply us1)
607 \subsubsection{ Module}
608 %=====================
611 getModuleRn :: RnM d Module
612 getModuleRn (RnDown {rn_mod = mod}) l_down
615 setModuleRn :: Module -> RnM d a -> RnM d a
616 setModuleRn new_mod enclosed_thing rn_down l_down
617 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
621 %************************************************************************
623 \subsection{Plumbing for rename-source part}
625 %************************************************************************
628 \subsubsection{ RnEnv}
629 %=====================
632 getLocalNameEnv :: RnMS LocalRdrEnv
633 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
636 getGlobalNameEnv :: RnMS GlobalRdrEnv
637 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
640 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
641 setLocalNameEnv local_env' m rn_down l_down
642 = m rn_down (l_down {rn_lenv = local_env'})
644 getFixityEnv :: RnMS LocalFixityEnv
645 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
648 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
649 extendFixityEnv fixes enclosed_scope
650 rn_down l_down@(SDown {rn_fixenv = fixity_env})
652 new_fixity_env = extendNameEnvList fixity_env fixes
654 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
658 \subsubsection{ Mode}
659 %=====================
662 getModeRn :: RnMS RnMode
663 getModeRn rn_down (SDown {rn_mode = mode})
666 setModeRn :: RnMode -> RnMS a -> RnMS a
667 setModeRn new_mode thing_inside rn_down l_down
668 = thing_inside rn_down (l_down {rn_mode = new_mode})
672 %************************************************************************
674 \subsection{Plumbing for rename-globals part}
676 %************************************************************************
679 getIfacesRn :: RnM d Ifaces
680 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
681 = readIORef iface_var
683 setIfacesRn :: Ifaces -> RnM d ()
684 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
685 = writeIORef iface_var ifaces