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"
28 import RnHsSyn ( RenamedFixitySig )
29 import HscTypes ( AvailEnv, emptyAvailEnv, lookupType,
31 ImportedModuleInfo, WhetherHasOrphans, ImportVersion,
32 PersistentRenamerState(..), RdrExportItem,
33 DeclsMap, IfaceInsts, IfaceRules,
34 HomeSymbolTable, TyThing,
35 PersistentCompilerState(..), GlobalRdrEnv,
37 HomeIfaceTable, PackageIfaceTable )
38 import BasicTypes ( Version, defaultFixity,
39 Fixity(..), FixityDirection(..) )
40 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
41 Message, Messages, errorsFound, warningsFound,
42 printErrorsAndWarnings
44 import RdrName ( RdrName, dummyRdrVarName, rdrNameModule, rdrNameOcc,
45 RdrNameEnv, emptyRdrEnv, extendRdrEnv,
46 addListToRdrEnv, rdrEnvToList, rdrEnvElts
50 import Name ( Name, OccName, NamedThing(..),
51 nameOccName, nameRdrName,
52 decode, mkInternalName
54 import NameEnv ( NameEnv, lookupNameEnv, emptyNameEnv,
56 import Module ( Module, ModuleName, ModuleSet, emptyModuleSet,
57 PackageName, preludePackage )
58 import PrelInfo ( ghcPrimExports,
59 cCallableClassDecl, cReturnableClassDecl, assertDecl )
60 import PrelNames ( mkUnboundName, gHC_PRIM_Name )
62 import CmdLineOpts ( DynFlags, DynFlag(..), dopt )
63 import SrcLoc ( SrcLoc, generatedSrcLoc, noSrcLoc )
64 import Unique ( Unique )
65 import FiniteMap ( FiniteMap )
66 import Maybes ( seqMaybe )
67 import Bag ( Bag, emptyBag, isEmptyBag, snocBag )
71 import DATA_IOREF ( IORef, newIORef, readIORef, writeIORef )
72 import UNSAFE_IO ( unsafePerformIO )
73 import FIX_IO ( fixIO )
75 import IO ( hPutStr, stderr )
77 infixr 9 `thenRn`, `thenRn_`
81 %************************************************************************
83 \subsection{Somewhat magical interface to other monads}
85 %************************************************************************
88 ioToRnM :: IO r -> RnM d (Either IOError r)
89 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
91 (\ err -> return (Left err))
93 ioToRnM_no_fail :: IO r -> RnM d r
94 ioToRnM_no_fail io rn_down g_down
95 = (io >>= \ ok -> return ok)
97 (\ err -> panic "ioToRnM_no_fail: the I/O operation failed!")
99 traceRn :: SDoc -> RnM d ()
100 traceRn msg = ifOptRn Opt_D_dump_rn_trace (putDocRn msg)
102 traceHiDiffsRn :: SDoc -> RnM d ()
103 traceHiDiffsRn msg = ifOptRn Opt_D_dump_hi_diffs (putDocRn msg)
105 putDocRn :: SDoc -> RnM d ()
106 putDocRn msg = ioToRnM (printErrs alwaysQualify msg) `thenRn_`
111 %************************************************************************
113 \subsection{Data types}
115 %************************************************************************
117 %===================================================
118 \subsubsection{ MONAD TYPES}
119 %===================================================
122 type RnM d r = RnDown -> d -> IO r
123 type RnMS r = RnM SDown r -- Renaming source
124 type RnMG r = RnM () r -- Getting global names etc
129 rn_mod :: Module, -- This module
130 rn_loc :: SrcLoc, -- Current locn
132 rn_dflags :: DynFlags,
134 rn_hit :: HomeIfaceTable,
135 rn_done :: Name -> Maybe TyThing, -- Tells what things (both in the
136 -- home package and other packages)
137 -- were already available (i.e. in
138 -- the relevant SymbolTable) before
139 -- compiling this module
140 -- The Name passed to rn_done is guaranteed to be a Global,
141 -- so it has a Module, so it can be looked up
143 rn_errs :: IORef Messages,
144 rn_ns :: IORef NameSupply,
145 rn_ifaces :: IORef Ifaces
148 -- For renaming source code
152 rn_genv :: GlobalRdrEnv, -- Top level environment
154 rn_avails :: AvailEnv,
155 -- Top level AvailEnv; contains all the things that
156 -- are nameable in the top-level scope, regardless of
157 -- *how* they can be named (qualified, unqualified...)
158 -- It is used only to map a Class to its class ops, and
159 -- hence to resolve the binders in an instance decl
161 rn_lenv :: LocalRdrEnv, -- Local name envt
162 -- Does *not* include global name envt; may shadow it
163 -- Includes both ordinary variables and type variables;
164 -- they are kept distinct because tyvar have a different
165 -- occurrence contructor (Name.TvOcc)
166 -- We still need the unsullied global name env so that
167 -- we can look up record field names
169 rn_fixenv :: LocalFixityEnv -- Local fixities (for non-top-level
171 -- The global fixities are held in the
172 -- HIT or PIT. Why? See the comments
173 -- with RnIfaces.lookupLocalFixity
176 data RnMode = SourceMode -- Renaming source code
177 | InterfaceMode -- Renaming interface declarations.
178 | CmdLineMode -- Renaming a command-line expression
180 isInterfaceMode InterfaceMode = True
181 isInterfaceMode _ = False
183 isCmdLineMode CmdLineMode = True
184 isCmdLineMode _ = False
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
193 emptyLocalFixityEnv :: LocalFixityEnv
194 emptyLocalFixityEnv = emptyNameEnv
198 %************************************************************************
200 \subsection{Interface file stuff}
202 %************************************************************************
205 type IfaceDeprecs = Maybe (Either DeprecTxt [(RdrName,DeprecTxt)])
206 -- Nothing => NoDeprecs
207 -- Just (Left t) => DeprecAll
208 -- Just (Right p) => DeprecSome
212 pi_mod :: ModuleName,
213 pi_pkg :: PackageName,
214 pi_vers :: Version, -- Module version number
215 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
216 pi_usages :: [ImportVersion OccName], -- Usages
217 pi_exports :: (Version, [RdrExportItem]), -- Exports
218 pi_decls :: [(Version, RdrNameTyClDecl)], -- Local definitions
219 pi_fixity :: [(RdrName,Fixity)], -- Local fixity declarations,
220 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
221 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
222 pi_deprecs :: IfaceDeprecs -- Deprecations
226 %************************************************************************
228 \subsection{Wired-in interfaces}
230 %************************************************************************
233 ghcPrimIface :: ParsedIface
234 ghcPrimIface = ParsedIface {
235 pi_mod = gHC_PRIM_Name,
236 pi_pkg = preludePackage,
240 pi_exports = (1, [(gHC_PRIM_Name, ghcPrimExports)]),
241 pi_decls = [(1,cCallableClassDecl),
242 (1,cReturnableClassDecl),
244 pi_fixity = [(nameRdrName (idName seqId), Fixity 0 InfixR)],
252 %************************************************************************
254 \subsection{The renamer state}
256 %************************************************************************
259 data Ifaces = Ifaces {
261 iPIT :: PackageIfaceTable,
262 -- The ModuleIFaces for modules in other packages
263 -- whose interfaces we have opened
264 -- The declarations in these interface files are held in
265 -- iDecls, iInsts, iRules (below), not in the mi_decls fields
266 -- of the iPIT. What _is_ in the iPIT is:
272 -- The iPIT field is initialised from the compiler's persistent
273 -- package symbol table, and the renamer incrementally adds
276 iImpModInfo :: ImportedModuleInfo,
277 -- Modules that we know something about, because they are mentioned
278 -- in interface files, BUT which we have not loaded yet.
279 -- No module is both in here and in the PIT
282 -- A single, global map of Names to unslurped decls
284 iInsts :: IfaceInsts,
285 -- The as-yet un-slurped instance decls; this bag is depleted when we
286 -- slurp an instance decl so that we don't slurp the same one twice.
287 -- Each is 'gated' by the names that must be available before
288 -- this instance decl is needed.
290 iRules :: IfaceRules,
291 -- Similar to instance decls, only for rules
294 -- These fields persist during the compilation of a single module only
296 -- All the names (whether "big" or "small", whether wired-in or not,
297 -- whether locally defined or not) that have been slurped in so far.
299 -- It's used for two things:
300 -- a) To record what we've already slurped, so
301 -- we can no-op if we try to slurp it again
302 -- b) As the 'gates' for importing rules. We import a rule
303 -- if all its LHS free vars have been slurped
305 iVSlurp :: (ModuleSet, NameSet)
306 -- The Names are all the (a) non-wired-in
308 -- (c) non-locally-defined
310 -- names that have been slurped in so far, with their versions.
311 -- This is used to generate the "usage" information for this module.
312 -- Subset of the previous field.
314 -- The module set is the non-home-package modules from which we have
315 -- slurped at least one name.
316 -- It's worth keeping separately, because there's no very easy
317 -- way to distinguish the "big" names from the "non-big" ones.
318 -- But this is a decision we might want to revisit.
323 %************************************************************************
325 \subsection{Main monad code}
327 %************************************************************************
330 runRn dflags hit hst pcs mod do_rn
331 = do { (pcs, msgs, r) <- initRn dflags hit hst pcs mod do_rn ;
332 printErrorsAndWarnings alwaysQualify msgs ;
333 return (pcs, errorsFound msgs, r)
337 -> HomeIfaceTable -> HomeSymbolTable
338 -> PersistentCompilerState
341 -> IO (PersistentCompilerState, Messages, t)
343 initRn dflags hit hst pcs mod do_rn
345 let prs = pcs_PRS pcs
346 let pte = pcs_PTE pcs
347 let ifaces = Ifaces { iPIT = pcs_PIT pcs,
348 iDecls = prsDecls prs,
349 iInsts = prsInsts prs,
350 iRules = prsRules prs,
352 iImpModInfo = prsImpMods prs,
353 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
354 -- Pretend that the dummy unbound name has already been
355 -- slurped. This is what's returned for an out-of-scope name,
356 -- and we don't want thereby to try to suck it in!
357 iVSlurp = (emptyModuleSet, emptyNameSet)
359 names_var <- newIORef (prsOrig prs)
360 errs_var <- newIORef (emptyBag,emptyBag)
361 iface_var <- newIORef ifaces
362 let rn_down = RnDown { rn_mod = mod,
367 rn_done = lookupType hst pte,
371 rn_ifaces = iface_var,
375 res <- do_rn rn_down ()
377 -- Grab state and record it
378 (warns, errs) <- readIORef errs_var
379 new_ifaces <- readIORef iface_var
380 new_orig <- readIORef names_var
381 let new_prs = prs { prsOrig = new_orig,
382 prsImpMods = iImpModInfo new_ifaces,
383 prsDecls = iDecls new_ifaces,
384 prsInsts = iInsts new_ifaces,
385 prsRules = iRules new_ifaces }
386 let new_pcs = pcs { pcs_PIT = iPIT new_ifaces,
389 return (new_pcs, (warns, errs), res)
391 initRnMS :: GlobalRdrEnv -> AvailEnv -> LocalRdrEnv -> LocalFixityEnv -> RnMode
394 initRnMS rn_env avails local_env fixity_env mode thing_inside rn_down g_down
395 -- The fixity_env appears in both the rn_fixenv field
396 -- and in the HIT. See comments with RnHiFiles.lookupFixityRn
398 s_down = SDown { rn_genv = rn_env, rn_avails = avails,
399 rn_lenv = local_env, rn_fixenv = fixity_env,
402 thing_inside rn_down s_down
404 initIfaceRnMS :: Module -> RnMS r -> RnM d r
405 initIfaceRnMS mod thing_inside
406 = initRnMS emptyRdrEnv emptyAvailEnv emptyRdrEnv
407 emptyLocalFixityEnv InterfaceMode
408 (setModuleRn mod thing_inside)
411 @renameDerivedCode@ is used to rename stuff ``out-of-line'';
412 that is, not as part of the main renamer.
413 Sole examples: derived definitions,
414 which are only generated in the type checker.
416 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
417 once you must either split it, or install a fresh unique supply.
420 renameDerivedCode :: DynFlags
422 -> PersistentRenamerState
426 renameDerivedCode dflags mod prs thing_inside
428 -- It's not really unsafe! When renaming source code we
429 -- only do any I/O if we need to read in a fixity declaration;
430 -- and that doesn't happen in pragmas etc
432 do { us <- mkSplitUniqSupply 'r'
433 ; names_var <- newIORef ((prsOrig prs) { nsUniqs = us })
434 ; errs_var <- newIORef (emptyBag,emptyBag)
436 ; let rn_down = RnDown { rn_dflags = dflags,
437 rn_loc = generatedSrcLoc, rn_ns = names_var,
440 rn_done = bogus "rn_done",
441 rn_hit = bogus "rn_hit",
442 rn_ifaces = bogus "rn_ifaces"
444 ; let s_down = SDown { rn_mode = InterfaceMode,
445 -- So that we can refer to PrelBase.True etc
446 rn_avails = emptyAvailEnv,
447 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
448 rn_fixenv = emptyLocalFixityEnv }
450 ; result <- thing_inside rn_down s_down
451 ; messages <- readIORef errs_var
453 ; if bad messages then
454 do { hPutStr stderr "Urk! renameDerivedCode found errors or warnings"
455 ; printErrorsAndWarnings alwaysQualify messages
464 bad messages = errorsFound messages || warningsFound messages
466 bad messages = errorsFound messages
469 bogus s = panic ("rnameSourceCode: " ++ s) -- Used for unused record fields
471 {-# INLINE thenRn #-}
472 {-# INLINE thenRn_ #-}
473 {-# INLINE returnRn #-}
476 returnRn :: a -> RnM d a
477 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
478 thenRn_ :: RnM d a -> RnM d b -> RnM d b
479 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
480 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
481 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
482 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
483 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
484 sequenceRn :: [RnM d a] -> RnM d [a]
485 sequenceRn_ :: [RnM d a] -> RnM d ()
486 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
487 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
488 fixRn :: (a -> RnM d a) -> RnM d a
490 returnRn v gdown ldown = return v
491 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
492 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
493 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
494 andRn combiner m1 m2 gdown ldown
495 = m1 gdown ldown >>= \ res1 ->
496 m2 gdown ldown >>= \ res2 ->
497 return (combiner res1 res2)
499 sequenceRn [] = returnRn []
500 sequenceRn (m:ms) = m `thenRn` \ r ->
501 sequenceRn ms `thenRn` \ rs ->
504 sequenceRn_ [] = returnRn ()
505 sequenceRn_ (m:ms) = m `thenRn_` sequenceRn_ ms
507 mapRn f [] = returnRn []
509 = f x `thenRn` \ r ->
510 mapRn f xs `thenRn` \ rs ->
513 mapRn_ f [] = returnRn ()
518 foldlRn k z [] = returnRn z
519 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
522 mapAndUnzipRn f [] = returnRn ([],[])
523 mapAndUnzipRn f (x:xs)
524 = f x `thenRn` \ (r1, r2) ->
525 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
526 returnRn (r1:rs1, r2:rs2)
528 mapAndUnzip3Rn f [] = returnRn ([],[],[])
529 mapAndUnzip3Rn f (x:xs)
530 = f x `thenRn` \ (r1, r2, r3) ->
531 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
532 returnRn (r1:rs1, r2:rs2, r3:rs3)
534 mapMaybeRn f [] = returnRn []
535 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
536 mapMaybeRn f xs `thenRn` \ rs ->
538 Nothing -> returnRn rs
539 Just r -> returnRn (r:rs)
541 flatMapRn f [] = returnRn []
542 flatMapRn f (x:xs) = f x `thenRn` \ r ->
543 flatMapRn f xs `thenRn` \ rs ->
549 %************************************************************************
551 \subsection{Boring plumbing for common part}
553 %************************************************************************
557 \subsubsection{ Errors and warnings}
558 %=====================
561 failWithRn :: a -> Message -> RnM d a
562 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
563 = readIORef errs_var >>= \ (warns,errs) ->
564 writeIORef errs_var (warns, errs `snocBag` err) >>
567 err = addShortErrLocLine loc msg
569 warnWithRn :: a -> Message -> RnM d a
570 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
571 = readIORef errs_var >>= \ (warns,errs) ->
572 writeIORef errs_var (warns `snocBag` warn, errs) >>
575 warn = addShortWarnLocLine loc msg
577 tryRn :: RnM d a -> RnM d (Either Messages a)
578 tryRn try_this down@(RnDown {rn_errs = errs_var}) l_down
579 = do current_msgs <- readIORef errs_var
580 writeIORef errs_var (emptyBag,emptyBag)
581 a <- try_this down l_down
582 (warns, errs) <- readIORef errs_var
583 writeIORef errs_var current_msgs
585 then return (Right a)
586 else return (Left (warns,errs))
588 setErrsRn :: Messages -> RnM d ()
589 setErrsRn msgs down@(RnDown {rn_errs = errs_var}) l_down
590 = do writeIORef errs_var msgs; return ()
592 addErrRn :: Message -> RnM d ()
593 addErrRn err = failWithRn () err
595 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
596 checkRn False err = addErrRn err
597 checkRn True err = returnRn ()
599 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
600 warnCheckRn False err = addWarnRn err
601 warnCheckRn True err = returnRn ()
603 addWarnRn :: Message -> RnM d ()
604 addWarnRn warn = warnWithRn () warn
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)
611 doptRn :: DynFlag -> RnM d Bool
612 doptRn dflag (RnDown { rn_dflags = dflags}) l_down
613 = return (dopt dflag dflags)
615 ifOptRn :: DynFlag -> RnM d a -> RnM d ()
616 ifOptRn dflag thing_inside down@(RnDown { rn_dflags = dflags}) l_down
617 | dopt dflag dflags = thing_inside down l_down >> return ()
618 | otherwise = return ()
620 getDOptsRn :: RnM d DynFlags
621 getDOptsRn (RnDown { rn_dflags = dflags}) l_down
627 \subsubsection{Source location}
628 %=====================
631 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
632 pushSrcLocRn loc' m down l_down
633 = m (down {rn_loc = loc'}) l_down
635 getSrcLocRn :: RnM d SrcLoc
636 getSrcLocRn down l_down
637 = return (rn_loc down)
641 \subsubsection{The finder and home symbol table}
642 %=====================
645 getHomeIfaceTableRn :: RnM d HomeIfaceTable
646 getHomeIfaceTableRn down l_down = return (rn_hit down)
648 getTypeEnvRn :: RnM d (Name -> Maybe TyThing)
649 getTypeEnvRn down l_down = return (rn_done down)
651 extendTypeEnvRn :: NameEnv TyThing -> RnM d a -> RnM d a
652 extendTypeEnvRn env inside down l_down
653 = inside down{rn_done=new_rn_done} l_down
654 where new_rn_done = \nm -> lookupNameEnv env nm `seqMaybe` rn_done down nm
658 \subsubsection{Name supply}
659 %=====================
662 getNameSupplyRn :: RnM d NameSupply
663 getNameSupplyRn rn_down l_down
664 = readIORef (rn_ns rn_down)
666 setNameSupplyRn :: NameSupply -> RnM d ()
667 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
668 = writeIORef names_var names'
670 getUniqRn :: RnM d Unique
671 getUniqRn (RnDown {rn_ns = names_var}) l_down
672 = readIORef names_var >>= \ ns ->
674 (us1,us') = splitUniqSupply (nsUniqs ns)
676 writeIORef names_var (ns {nsUniqs = us'}) >>
677 return (uniqFromSupply us1)
681 \subsubsection{ Module}
682 %=====================
685 getModuleRn :: RnM d Module
686 getModuleRn (RnDown {rn_mod = mod}) l_down
689 setModuleRn :: Module -> RnM d a -> RnM d a
690 setModuleRn new_mod enclosed_thing rn_down l_down
691 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
695 %************************************************************************
697 \subsection{Plumbing for rename-source part}
699 %************************************************************************
702 \subsubsection{ RnEnv}
703 %=====================
706 getLocalNameEnv :: RnMS LocalRdrEnv
707 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
710 getGlobalNameEnv :: RnMS GlobalRdrEnv
711 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
714 getGlobalAvails :: RnMS AvailEnv
715 getGlobalAvails rn_down (SDown {rn_avails = avails})
718 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
719 setLocalNameEnv local_env' m rn_down l_down
720 = m rn_down (l_down {rn_lenv = local_env'})
722 getFixityEnv :: RnMS LocalFixityEnv
723 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
726 setFixityEnv :: LocalFixityEnv -> RnMS a -> RnMS a
727 setFixityEnv fixes enclosed_scope rn_down l_down
728 = enclosed_scope rn_down (l_down {rn_fixenv = fixes})
732 \subsubsection{ Mode}
733 %=====================
736 getModeRn :: RnMS RnMode
737 getModeRn rn_down (SDown {rn_mode = mode})
740 setModeRn :: RnMode -> RnMS a -> RnMS a
741 setModeRn new_mode thing_inside rn_down l_down
742 = thing_inside rn_down (l_down {rn_mode = new_mode})
746 %************************************************************************
748 \subsection{Plumbing for rename-globals part}
750 %************************************************************************
753 getIfacesRn :: RnM d Ifaces
754 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
755 = readIORef iface_var
757 setIfacesRn :: Ifaces -> RnM d ()
758 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
759 = writeIORef iface_var ifaces