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 ( Finder,
39 AvailEnv, lookupTypeEnv,
40 OrigNameEnv(..), OrigNameNameEnv, OrigNameIParamEnv,
41 WhetherHasOrphans, ImportVersion,
42 PersistentRenamerState(..), IsBootInterface, Avails,
43 DeclsMap, IfaceInsts, IfaceRules,
44 HomeSymbolTable, PackageSymbolTable,
45 PersistentCompilerState(..), GlobalRdrEnv,
46 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 lookupRdrEnv, addListToRdrEnv, rdrEnvToList, rdrEnvElts
55 import Name ( Name, OccName, NamedThing(..), getSrcLoc,
56 isLocallyDefinedName, nameModule, 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 )
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 )
73 infixr 9 `thenRn`, `thenRn_`
77 %************************************************************************
79 \subsection{Somewhat magical interface to other monads}
81 %************************************************************************
84 ioToRnM :: IO r -> RnM d (Either IOError r)
85 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
87 (\ err -> return (Left err))
89 traceRn :: SDoc -> RnM d ()
91 = doptRn Opt_D_dump_rn_trace `thenRn` \b ->
92 if b then putDocRn msg else returnRn ()
94 putDocRn :: SDoc -> RnM d ()
95 putDocRn msg = ioToRnM (printErrs msg) `thenRn_`
100 %************************************************************************
102 \subsection{Data types}
104 %************************************************************************
106 %===================================================
107 \subsubsection{ MONAD TYPES}
108 %===================================================
111 type RnM d r = RnDown -> d -> IO r
112 type RnMS r = RnM SDown r -- Renaming source
113 type RnMG r = RnM () r -- Getting global names etc
118 rn_mod :: Module, -- This module
119 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])
199 pi_mod :: Module, -- Complete with package info
200 pi_vers :: Version, -- Module version number
201 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
202 pi_usages :: [ImportVersion OccName], -- Usages
203 pi_exports :: [ExportItem], -- Exports
204 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
205 pi_decls :: [(Version, RdrNameHsDecl)], -- Local definitions
206 pi_fixity :: (Version, [RdrNameFixitySig]), -- Local fixity declarations,
207 -- with their version
208 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
209 pi_deprecs :: [RdrNameDeprecation] -- Deprecations
213 %************************************************************************
215 \subsection{The renamer state}
217 %************************************************************************
220 data Ifaces = Ifaces {
222 iPIT :: PackageIfaceTable,
223 -- The ModuleIFaces for modules in other packages
224 -- whose interfaces we have opened
225 -- The declarations in these interface files are held in
226 -- iDecls, iInsts, iRules (below), not in the mi_decls fields
227 -- of the iPIT. What _is_ in the iPIT is:
233 -- The iPIT field is initialised from the compiler's persistent
234 -- package symbol table, and the renamer incrementally adds
238 -- A single, global map of Names to unslurped decls
240 iInsts :: IfaceInsts,
241 -- The as-yet un-slurped instance decls; this bag is depleted when we
242 -- slurp an instance decl so that we don't slurp the same one twice.
243 -- Each is 'gated' by the names that must be available before
244 -- this instance decl is needed.
246 iRules :: IfaceRules,
247 -- Similar to instance decls, only for rules
250 -- These fields persist during the compilation of a single module only
251 iImpModInfo :: ImportedModuleInfo,
252 -- Modules this one depends on: that is, the union
253 -- of the modules its *direct* imports depend on.
254 -- NB: The direct imports have .hi files that enumerate *all* the
255 -- dependencies (direct or not) of the imported module.
258 -- All the names (whether "big" or "small", whether wired-in or not,
259 -- whether locally defined or not) that have been slurped in so far.
262 -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
263 -- names that have been slurped in so far, with their versions.
264 -- This is used to generate the "usage" information for this module.
265 -- Subset of the previous field.
266 -- It's worth keeping separately, because there's no very easy
267 -- way to distinguish the "big" names from the "non-big" ones.
268 -- But this is a decision we might want to revisit.
271 type ImportedModuleInfo = FiniteMap ModuleName
272 (WhetherHasOrphans, IsBootInterface, IsLoaded)
277 %************************************************************************
279 \subsection{Main monad code}
281 %************************************************************************
288 -> PersistentCompilerState
292 -> IO (t, PersistentCompilerState, (Bag WarnMsg, Bag ErrMsg))
294 initRn dflags finder hit hst pcs mod loc do_rn
296 let prs = pcs_PRS pcs
297 let pst = pcs_PST pcs
299 uniqs <- mkSplitUniqSupply 'r'
300 names_var <- newIORef (uniqs, origNames (prsOrig prs),
301 origIParam (prsOrig prs))
302 errs_var <- newIORef (emptyBag,emptyBag)
303 iface_var <- newIORef (initIfaces pcs)
304 let rn_down = RnDown { rn_mod = mod,
310 rn_done = is_done hst pst,
314 rn_ifaces = iface_var,
318 res <- do_rn rn_down ()
320 -- Grab state and record it
321 (warns, errs) <- readIORef errs_var
322 new_ifaces <- readIORef iface_var
323 (_, new_origN, new_origIP) <- readIORef names_var
324 let new_orig = Orig { origNames = new_origN, origIParam = new_origIP }
325 let new_prs = prs { prsOrig = new_orig,
326 prsDecls = iDecls new_ifaces,
327 prsInsts = iInsts new_ifaces,
328 prsRules = iRules new_ifaces }
329 let new_pcs = pcs { pcs_PIT = iPIT new_ifaces,
332 return (res, new_pcs, (warns, errs))
334 is_done :: HomeSymbolTable -> PackageSymbolTable -> Name -> Bool
335 -- Returns True iff the name is in either symbol table
336 is_done hst pst n = maybeToBool (lookupTypeEnv pst n `seqMaybe` lookupTypeEnv hst n)
338 lookupIface :: HomeInterfaceTable -> PackageInterfaceTable -> ModuleName -> ModIface
339 lookupIface hit pit mod = lookupModuleEnvByName hit mod `orElse`
340 lookupModuleEnvByName pit mod `orElse`
341 pprPanic "lookupIface" (ppr mod)
343 initIfaces :: PersistentCompilerState -> Ifaces
344 initIfaces (PCS { pcs_PIT = pit, pcs_PRS = prs })
345 = Ifaces { iPIT = pit,
346 iDecls = prsDecls prs,
347 iInsts = prsInsts prs,
348 iRules = prsRules prs,
350 iImpModInfo = emptyFM,
351 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
352 -- Pretend that the dummy unbound name has already been
353 -- slurped. This is what's returned for an out-of-scope name,
354 -- and we don't want thereby to try to suck it in!
359 initRnMS :: GlobalRdrEnv -> LocalFixityEnv -> RnMode -> RnMS r -> RnM d r
360 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
362 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
363 rn_fixenv = fixity_env, rn_mode = mode }
365 thing_inside rn_down s_down
367 initIfaceRnMS :: Module -> RnMS r -> RnM d r
368 initIfaceRnMS mod thing_inside
369 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
370 setModuleRn mod thing_inside
374 @renameSourceCode@ is used to rename stuff ``out-of-line'';
375 that is, not as part of the main renamer.
376 Sole examples: derived definitions,
377 which are only generated in the type checker.
379 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
380 once you must either split it, or install a fresh unique supply.
383 renameSourceCode :: DynFlags
385 -> PersistentRenamerState
389 renameSourceCode dflags mod prs m
391 -- It's not really unsafe! When renaming source code we
392 -- only do any I/O if we need to read in a fixity declaration;
393 -- and that doesn't happen in pragmas etc
395 mkSplitUniqSupply 'r' >>= \ new_us ->
396 newIORef (new_us, origNames (prsOrig prs),
397 origIParam (prsOrig prs)) >>= \ names_var ->
398 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
400 rn_down = RnDown { rn_dflags = dflags,
401 rn_loc = generatedSrcLoc, rn_ns = names_var,
404 rn_ifaces = panic "rnameSourceCode: rn_ifaces", -- Not required
405 rn_finder = panic "rnameSourceCode: rn_finder" -- Not required
407 s_down = SDown { rn_mode = InterfaceMode,
408 -- So that we can refer to PrelBase.True etc
409 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
410 rn_fixenv = emptyNameEnv }
412 m rn_down s_down >>= \ result ->
414 readIORef errs_var >>= \ (warns,errs) ->
416 (if not (isEmptyBag errs) then
417 pprTrace "Urk! renameSourceCode found errors" (display errs)
419 else if not (isEmptyBag warns) then
420 pprTrace "Note: renameSourceCode found warnings" (display warns)
428 display errs = pprBagOfErrors errs
430 {-# INLINE thenRn #-}
431 {-# INLINE thenRn_ #-}
432 {-# INLINE returnRn #-}
435 returnRn :: a -> RnM d a
436 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
437 thenRn_ :: RnM d a -> RnM d b -> RnM d b
438 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
439 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
440 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
441 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
442 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
443 sequenceRn :: [RnM d a] -> RnM d [a]
444 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
445 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
446 fixRn :: (a -> RnM d a) -> RnM d a
448 returnRn v gdown ldown = return v
449 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
450 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
451 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
452 andRn combiner m1 m2 gdown ldown
453 = m1 gdown ldown >>= \ res1 ->
454 m2 gdown ldown >>= \ res2 ->
455 return (combiner res1 res2)
457 sequenceRn [] = returnRn []
458 sequenceRn (m:ms) = m `thenRn` \ r ->
459 sequenceRn ms `thenRn` \ rs ->
462 mapRn f [] = returnRn []
464 = f x `thenRn` \ r ->
465 mapRn f xs `thenRn` \ rs ->
468 mapRn_ f [] = returnRn ()
473 foldlRn k z [] = returnRn z
474 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
477 mapAndUnzipRn f [] = returnRn ([],[])
478 mapAndUnzipRn f (x:xs)
479 = f x `thenRn` \ (r1, r2) ->
480 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
481 returnRn (r1:rs1, r2:rs2)
483 mapAndUnzip3Rn f [] = returnRn ([],[],[])
484 mapAndUnzip3Rn f (x:xs)
485 = f x `thenRn` \ (r1, r2, r3) ->
486 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
487 returnRn (r1:rs1, r2:rs2, r3:rs3)
489 mapMaybeRn f [] = returnRn []
490 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
491 mapMaybeRn f xs `thenRn` \ rs ->
493 Nothing -> returnRn rs
494 Just r -> returnRn (r:rs)
496 flatMapRn f [] = returnRn []
497 flatMapRn f (x:xs) = f x `thenRn` \ r ->
498 flatMapRn f xs `thenRn` \ rs ->
504 %************************************************************************
506 \subsection{Boring plumbing for common part}
508 %************************************************************************
512 \subsubsection{ Errors and warnings}
513 %=====================
516 failWithRn :: a -> Message -> RnM d a
517 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
518 = readIORef errs_var >>= \ (warns,errs) ->
519 writeIORef errs_var (warns, errs `snocBag` err) >>
522 err = addShortErrLocLine loc msg
524 warnWithRn :: a -> Message -> RnM d a
525 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
526 = readIORef errs_var >>= \ (warns,errs) ->
527 writeIORef errs_var (warns `snocBag` warn, errs) >>
530 warn = addShortWarnLocLine loc msg
532 addErrRn :: Message -> RnM d ()
533 addErrRn err = failWithRn () err
535 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
536 checkRn False err = addErrRn err
537 checkRn True err = returnRn ()
539 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
540 warnCheckRn False err = addWarnRn err
541 warnCheckRn True err = returnRn ()
543 addWarnRn :: Message -> RnM d ()
544 addWarnRn warn = warnWithRn () warn
546 checkErrsRn :: RnM d Bool -- True <=> no errors so far
547 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
548 = readIORef errs_var >>= \ (warns,errs) ->
549 return (isEmptyBag errs)
551 doptRn :: DynFlag -> RnM d Bool
552 doptRn dflag (RnDown { rn_dflags = dflags}) l_down
553 = return (dopt dflag dflags)
555 getDOptsRn :: RnM d DynFlags
556 getDOptsRn (RnDown { rn_dflags = dflags}) l_down
562 \subsubsection{Source location}
563 %=====================
566 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
567 pushSrcLocRn loc' m down l_down
568 = m (down {rn_loc = loc'}) l_down
570 getSrcLocRn :: RnM d SrcLoc
571 getSrcLocRn down l_down
572 = return (rn_loc down)
576 \subsubsection{The finder and home symbol table}
577 %=====================
580 getFinderRn :: RnM d Finder
581 getFinderRn down l_down = return (rn_finder down)
583 getHomeIfaceTableRn :: RnM d HomeIfaceTable
584 getHomeIfaceTableRn down l_down = return (rn_hit down)
586 checkAlreadyAvailable :: Name -> RnM d Bool
587 checkAlreadyAvailable name down l_down = return (rn_done down name)
591 \subsubsection{Name supply}
592 %=====================
595 getNameSupplyRn :: RnM d (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv)
596 getNameSupplyRn rn_down l_down
597 = readIORef (rn_ns rn_down)
599 setNameSupplyRn :: (UniqSupply, OrigNameNameEnv, OrigNameIParamEnv) -> RnM d ()
600 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
601 = writeIORef names_var names'
603 getUniqRn :: RnM d Unique
604 getUniqRn (RnDown {rn_ns = names_var}) l_down
605 = readIORef names_var >>= \ (us, cache, ipcache) ->
607 (us1,us') = splitUniqSupply us
609 writeIORef names_var (us', cache, ipcache) >>
610 return (uniqFromSupply us1)
614 \subsubsection{ Module}
615 %=====================
618 getModuleRn :: RnM d Module
619 getModuleRn (RnDown {rn_mod = mod}) l_down
622 setModuleRn :: Module -> RnM d a -> RnM d a
623 setModuleRn new_mod enclosed_thing rn_down l_down
624 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
628 %************************************************************************
630 \subsection{Plumbing for rename-source part}
632 %************************************************************************
635 \subsubsection{ RnEnv}
636 %=====================
639 getLocalNameEnv :: RnMS LocalRdrEnv
640 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
643 getGlobalNameEnv :: RnMS GlobalRdrEnv
644 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
647 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
648 setLocalNameEnv local_env' m rn_down l_down
649 = m rn_down (l_down {rn_lenv = local_env'})
651 getFixityEnv :: RnMS LocalFixityEnv
652 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
655 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
656 extendFixityEnv fixes enclosed_scope
657 rn_down l_down@(SDown {rn_fixenv = fixity_env})
659 new_fixity_env = extendNameEnvList fixity_env fixes
661 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
665 \subsubsection{ Mode}
666 %=====================
669 getModeRn :: RnMS RnMode
670 getModeRn rn_down (SDown {rn_mode = mode})
673 setModeRn :: RnMode -> RnMS a -> RnMS a
674 setModeRn new_mode thing_inside rn_down l_down
675 = thing_inside rn_down (l_down {rn_mode = new_mode})
679 %************************************************************************
681 \subsection{Plumbing for rename-globals part}
683 %************************************************************************
686 getIfacesRn :: RnM d Ifaces
687 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
688 = readIORef iface_var
690 setIfacesRn :: Ifaces -> RnM d ()
691 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
692 = writeIORef iface_var ifaces