2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnMonad]{The monad used by the renamer}
21 #include "HsVersions.h"
23 import PrelIOBase ( fixIO ) -- Should be in GlaExts
24 import IOExts ( IORef, newIORef, readIORef, writeIORef, unsafePerformIO )
28 import RnHsSyn ( RenamedFixitySig )
29 import BasicTypes ( Version )
30 import SrcLoc ( noSrcLoc )
31 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
32 pprBagOfErrors, ErrMsg, WarnMsg, Message
34 import Name ( Name, OccName, NamedThing(..),
35 isLocallyDefinedName, nameModule, nameOccName,
38 import Module ( Module, ModuleName, ModuleHiMap, SearchPath, WhereFrom,
39 mkModuleHiMaps, moduleName
42 import RdrName ( RdrName, dummyRdrVarName, rdrNameOcc )
43 import CmdLineOpts ( opt_D_dump_rn_trace, opt_IgnoreIfacePragmas )
44 import PrelInfo ( builtinNames )
45 import TysWiredIn ( boolTyCon )
46 import SrcLoc ( SrcLoc, mkGeneratedSrcLoc )
47 import Unique ( Unique, getUnique, unboundKey )
48 import UniqFM ( UniqFM )
49 import FiniteMap ( FiniteMap, emptyFM, bagToFM, lookupFM, addToFM, addListToFM,
50 addListToFM_C, addToFM_C, eltsFM, fmToList
52 import Bag ( Bag, mapBag, emptyBag, isEmptyBag, snocBag )
53 import Maybes ( mapMaybe )
60 infixr 9 `thenRn`, `thenRn_`
64 %************************************************************************
66 \subsection{Somewhat magical interface to other monads}
68 %************************************************************************
71 ioToRnM :: IO r -> RnM d (Either IOError r)
72 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
74 (\ err -> return (Left err))
76 traceRn :: SDoc -> RnM d ()
77 traceRn msg | opt_D_dump_rn_trace = putDocRn msg
78 | otherwise = returnRn ()
80 putDocRn :: SDoc -> RnM d ()
81 putDocRn msg = ioToRnM (printErrs msg) `thenRn_`
86 %************************************************************************
88 \subsection{Data types}
90 %************************************************************************
92 ===================================================
94 ===================================================
97 type RnM d r = RnDown -> d -> IO r
98 type RnMS r = RnM SDown r -- Renaming source
99 type RnMG r = RnM () r -- Getting global names etc
102 data RnDown = RnDown {
103 rn_mod :: ModuleName,
105 rn_omit :: Name -> Bool, -- True <=> omit qualifier when printing
106 rn_ns :: IORef RnNameSupply,
107 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
108 rn_ifaces :: IORef Ifaces,
109 rn_hi_maps :: (ModuleHiMap, -- for .hi files
110 ModuleHiMap) -- for .hi-boot files
113 -- For renaming source code
117 rn_genv :: GlobalRdrEnv, -- Global envt; the fixity component gets extended
118 -- with local fixity decls
120 rn_lenv :: LocalRdrEnv, -- Local name envt
121 -- Does *not* includes global name envt; may shadow it
122 -- Includes both ordinary variables and type variables;
123 -- they are kept distinct because tyvar have a different
124 -- occurrence contructor (Name.TvOcc)
125 -- We still need the unsullied global name env so that
126 -- we can look up record field names
128 rn_fixenv :: FixityEnv -- Local fixities
129 -- The global ones are held in the
133 data RnMode = SourceMode -- Renaming source code
134 | InterfaceMode -- Renaming interface declarations.
137 ===================================================
139 ===================================================
142 --------------------------------
143 type RdrNameEnv a = FiniteMap RdrName a
144 type GlobalRdrEnv = RdrNameEnv [Name] -- The list is because there may be name clashes
145 -- These only get reported on lookup,
146 -- not on construction
147 type LocalRdrEnv = RdrNameEnv Name
149 emptyRdrEnv :: RdrNameEnv a
150 lookupRdrEnv :: RdrNameEnv a -> RdrName -> Maybe a
151 addListToRdrEnv :: RdrNameEnv a -> [(RdrName,a)] -> RdrNameEnv a
152 extendRdrEnv :: RdrNameEnv a -> RdrName -> a -> RdrNameEnv a
154 emptyRdrEnv = emptyFM
155 lookupRdrEnv = lookupFM
156 addListToRdrEnv = addListToFM
158 extendRdrEnv = addToFM
159 rdrEnvToList = fmToList
161 --------------------------------
162 type NameEnv a = UniqFM a -- Domain is Name
164 emptyNameEnv :: NameEnv a
165 nameEnvElts :: NameEnv a -> [a]
166 addToNameEnv_C :: (a->a->a) -> NameEnv a -> Name -> a -> NameEnv a
167 addToNameEnv :: NameEnv a -> Name -> a -> NameEnv a
168 plusNameEnv :: NameEnv a -> NameEnv a -> NameEnv a
169 extendNameEnv :: NameEnv a -> [(Name,a)] -> NameEnv a
170 lookupNameEnv :: NameEnv a -> Name -> Maybe a
171 delFromNameEnv :: NameEnv a -> Name -> NameEnv a
172 elemNameEnv :: Name -> NameEnv a -> Bool
174 emptyNameEnv = emptyUFM
175 nameEnvElts = eltsUFM
176 addToNameEnv_C = addToUFM_C
177 addToNameEnv = addToUFM
178 plusNameEnv = plusUFM
179 extendNameEnv = addListToUFM
180 lookupNameEnv = lookupUFM
181 delFromNameEnv = delFromUFM
182 elemNameEnv = elemUFM
184 --------------------------------
185 type FixityEnv = NameEnv RenamedFixitySig
186 -- We keep the whole fixity sig so that we
187 -- can report line-number info when there is a duplicate
188 -- fixity declaration
192 --------------------------------
196 , FiniteMap (OccName, OccName) Int
197 -- This is used as a name supply for dictionary functions
198 -- From the inst decl we derive a (class, tycon) pair;
199 -- this map then gives a unique int for each inst decl with that
200 -- (class, tycon) pair. (In Haskell 98 there can only be one,
201 -- but not so in more extended versions.)
203 -- We could just use one Int for all the instance decls, but this
204 -- way the uniques change less when you add an instance decl,
205 -- hence less recompilation
207 , FiniteMap (ModuleName, OccName) Name
208 -- Ensures that one (module,occname) pair gets one unique
212 --------------------------------
213 data ExportEnv = ExportEnv Avails Fixities
214 type Avails = [AvailInfo]
215 type Fixities = [(Name, Fixity)]
217 type ExportAvails = (FiniteMap ModuleName Avails, -- Used to figure out "module M" export specifiers
218 -- Includes avails only from *unqualified* imports
219 -- (see 1.4 Report Section 5.1.1)
221 NameEnv AvailInfo) -- Used to figure out all other export specifiers.
222 -- Maps a Name to the AvailInfo that contains it
225 data GenAvailInfo name = Avail name -- An ordinary identifier
226 | AvailTC name -- The name of the type or class
227 [name] -- The available pieces of type/class. NB: If the type or
228 -- class is itself to be in scope, it must be in this list.
229 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
230 type AvailInfo = GenAvailInfo Name
231 type RdrAvailInfo = GenAvailInfo OccName
234 ===================================================
236 ===================================================
239 type ExportItem = (ModuleName, [RdrAvailInfo])
240 type VersionInfo name = [ImportVersion name]
242 type ImportVersion name = (ModuleName, Version, WhetherHasOrphans, WhatsImported name)
244 type WhetherHasOrphans = Bool
246 -- * an instance decl in a module other than the defn module for
247 -- one of the tycons or classes in the instance head
248 -- * a transformation rule in a module other than the one defining
249 -- the function in the head of the rule.
251 data WhatsImported name = Everything
252 | Specifically [LocalVersion name] -- List guaranteed non-empty
254 -- ("M", hif, ver, Everything) means there was a "module M" in
255 -- this module's export list, so we just have to go by M's version, "ver",
256 -- not the list of LocalVersions.
259 type LocalVersion name = (name, Version)
263 pi_mod :: Version, -- Module version number
264 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
265 pi_usages :: [ImportVersion OccName], -- Usages
266 pi_exports :: [ExportItem], -- Exports
267 pi_decls :: [(Version, RdrNameHsDecl)], -- Local definitions
268 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
269 pi_rules :: [RdrNameRuleDecl] -- Rules
272 type InterfaceDetails = (WhetherHasOrphans,
273 VersionInfo Name, -- Version information for what this module imports
274 ExportEnv) -- What modules this one depends on
277 -- needed by Main to fish out the fixities assoc list.
278 getIfaceFixities :: InterfaceDetails -> Fixities
279 getIfaceFixities (_, _, ExportEnv _ fs) = fs
282 type RdrNamePragma = () -- Fudge for now
285 data Ifaces = Ifaces {
286 iImpModInfo :: ImportedModuleInfo,
287 -- Modules this one depends on: that is, the union
288 -- of the modules its direct imports depend on.
290 iDecls :: DeclsMap, -- A single, global map of Names to decls
292 iFixes :: FixityEnv, -- A single, global map of Names to fixities
294 iSlurp :: NameSet, -- All the names (whether "big" or "small", whether wired-in or not,
295 -- whether locally defined or not) that have been slurped in so far.
297 iVSlurp :: [(Name,Version)], -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
298 -- names that have been slurped in so far, with their versions.
299 -- This is used to generate the "usage" information for this module.
300 -- Subset of the previous field.
302 iInsts :: Bag GatedDecl,
303 -- The as-yet un-slurped instance decls; this bag is depleted when we
304 -- slurp an instance decl so that we don't slurp the same one twice.
305 -- Each is 'gated' by the names that must be available before
306 -- this instance decl is needed.
308 iRules :: Bag GatedDecl
309 -- Ditto transformation rules
312 type GatedDecl = (NameSet, (Module, RdrNameHsDecl))
314 type ImportedModuleInfo
315 = FiniteMap ModuleName (Version, Bool, Maybe (Module, Bool, Avails))
316 -- Suppose the domain element is module 'A'
318 -- The first Bool is True if A contains
319 -- 'orphan' rules or instance decls
321 -- The second Bool is true if the interface file actually
322 -- read was an .hi-boot file
324 -- Nothing => A's interface not yet read, but this module has
325 -- imported a module, B, that itself depends on A
327 -- Just xx => A's interface has been read. The Module in
328 -- the Just has the correct Dll flag
330 -- This set is used to decide whether to look for
331 -- A.hi or A.hi-boot when importing A.f.
332 -- Basically, we look for A.hi if A is in the map, and A.hi-boot
335 type DeclsMap = NameEnv (Version, AvailInfo, Bool, (Module, RdrNameHsDecl))
336 -- A DeclsMap contains a binding for each Name in the declaration
337 -- including the constructors of a type decl etc.
338 -- The Bool is True just for the 'main' Name.
342 %************************************************************************
344 \subsection{Main monad code}
346 %************************************************************************
349 initRn :: ModuleName -> UniqSupply -> SearchPath -> SrcLoc
351 -> IO (r, Bag ErrMsg, Bag WarnMsg)
353 initRn mod us dirs loc do_rn = do
354 himaps <- mkModuleHiMaps dirs
355 names_var <- newIORef (us, emptyFM, builtins)
356 errs_var <- newIORef (emptyBag,emptyBag)
357 iface_var <- newIORef emptyIfaces
359 rn_down = RnDown { rn_loc = loc, rn_omit = \n -> False, rn_ns = names_var,
362 rn_ifaces = iface_var,
366 res <- do_rn rn_down ()
368 -- grab errors and return
369 (warns, errs) <- readIORef errs_var
371 return (res, errs, warns)
374 initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r
375 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
377 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
378 rn_fixenv = fixity_env, rn_mode = mode }
380 thing_inside rn_down s_down
382 initIfaceRnMS :: Module -> RnMS r -> RnM d r
383 initIfaceRnMS mod thing_inside
384 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
385 setModuleRn (moduleName mod) thing_inside
387 emptyIfaces :: Ifaces
388 emptyIfaces = Ifaces { iImpModInfo = emptyFM,
389 iDecls = emptyNameEnv,
390 iFixes = emptyNameEnv,
391 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
392 -- Pretend that the dummy unbound name has already been
393 -- slurped. This is what's returned for an out-of-scope name,
394 -- and we don't want thereby to try to suck it in!
400 -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
401 -- during compiler debugging.
402 mkUnboundName :: RdrName -> Name
403 mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc
405 isUnboundName :: Name -> Bool
406 isUnboundName name = getUnique name == unboundKey
408 builtins :: FiniteMap (ModuleName,OccName) Name
411 mapBag (\ name -> ((moduleName (nameModule name), nameOccName name), name))
415 @renameSourceCode@ is used to rename stuff "out-of-line"; that is, not as part of
416 the main renamer. Sole examples: derived definitions, which are only generated
419 The @RnNameSupply@ includes a @UniqueSupply@, so if you call it more than
420 once you must either split it, or install a fresh unique supply.
423 renameSourceCode :: ModuleName
428 renameSourceCode mod_name name_supply m
430 -- It's not really unsafe! When renaming source code we
431 -- only do any I/O if we need to read in a fixity declaration;
432 -- and that doesn't happen in pragmas etc
434 newIORef name_supply >>= \ names_var ->
435 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
437 rn_down = RnDown { rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,
440 s_down = SDown { rn_mode = InterfaceMode, -- So that we can refer to PrelBase.True etc
441 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
442 rn_fixenv = emptyNameEnv }
444 m rn_down s_down >>= \ result ->
446 readIORef errs_var >>= \ (warns,errs) ->
448 (if not (isEmptyBag errs) then
449 pprTrace "Urk! renameSourceCode found errors" (display errs)
451 else if not (isEmptyBag warns) then
452 pprTrace "Note: renameSourceCode found warnings" (display warns)
460 display errs = pprBagOfErrors errs
462 {-# INLINE thenRn #-}
463 {-# INLINE thenRn_ #-}
464 {-# INLINE returnRn #-}
467 returnRn :: a -> RnM d a
468 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
469 thenRn_ :: RnM d a -> RnM d b -> RnM d b
470 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
471 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
472 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
473 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
474 sequenceRn :: [RnM d a] -> RnM d [a]
475 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
476 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
477 fixRn :: (a -> RnM d a) -> RnM d a
479 returnRn v gdown ldown = return v
480 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
481 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
482 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
483 andRn combiner m1 m2 gdown ldown
484 = m1 gdown ldown >>= \ res1 ->
485 m2 gdown ldown >>= \ res2 ->
486 return (combiner res1 res2)
488 sequenceRn [] = returnRn []
489 sequenceRn (m:ms) = m `thenRn` \ r ->
490 sequenceRn ms `thenRn` \ rs ->
493 mapRn f [] = returnRn []
495 = f x `thenRn` \ r ->
496 mapRn f xs `thenRn` \ rs ->
499 mapRn_ f [] = returnRn ()
504 foldlRn k z [] = returnRn z
505 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
508 mapAndUnzipRn f [] = returnRn ([],[])
509 mapAndUnzipRn f (x:xs)
510 = f x `thenRn` \ (r1, r2) ->
511 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
512 returnRn (r1:rs1, r2:rs2)
514 mapAndUnzip3Rn f [] = returnRn ([],[],[])
515 mapAndUnzip3Rn f (x:xs)
516 = f x `thenRn` \ (r1, r2, r3) ->
517 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
518 returnRn (r1:rs1, r2:rs2, r3:rs3)
520 mapMaybeRn f [] = returnRn []
521 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
522 mapMaybeRn f xs `thenRn` \ rs ->
524 Nothing -> returnRn rs
525 Just r -> returnRn (r:rs)
530 %************************************************************************
532 \subsection{Boring plumbing for common part}
534 %************************************************************************
537 ================ Errors and warnings =====================
540 failWithRn :: a -> Message -> RnM d a
541 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
542 = readIORef errs_var >>= \ (warns,errs) ->
543 writeIORef errs_var (warns, errs `snocBag` err) >>
546 err = addShortErrLocLine loc msg
548 warnWithRn :: a -> Message -> RnM d a
549 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
550 = readIORef errs_var >>= \ (warns,errs) ->
551 writeIORef errs_var (warns `snocBag` warn, errs) >>
554 warn = addShortWarnLocLine loc msg
556 addErrRn :: Message -> RnM d ()
557 addErrRn err = failWithRn () err
559 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
560 checkRn False err = addErrRn err
561 checkRn True err = returnRn ()
563 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
564 warnCheckRn False err = addWarnRn err
565 warnCheckRn True err = returnRn ()
567 addWarnRn :: Message -> RnM d ()
568 addWarnRn warn = warnWithRn () warn
570 checkErrsRn :: RnM d Bool -- True <=> no errors so far
571 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
572 = readIORef errs_var >>= \ (warns,errs) ->
573 return (isEmptyBag errs)
577 ================ Source location =====================
580 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
581 pushSrcLocRn loc' m down l_down
582 = m (down {rn_loc = loc'}) l_down
584 getSrcLocRn :: RnM d SrcLoc
585 getSrcLocRn down l_down
586 = return (rn_loc down)
589 ================ Name supply =====================
592 getNameSupplyRn :: RnM d RnNameSupply
593 getNameSupplyRn rn_down l_down
594 = readIORef (rn_ns rn_down)
596 setNameSupplyRn :: RnNameSupply -> RnM d ()
597 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
598 = writeIORef names_var names'
600 -- See comments with RnNameSupply above.
601 newInstUniq :: (OccName, OccName) -> RnM d Int
602 newInstUniq key (RnDown {rn_ns = names_var}) l_down
603 = readIORef names_var >>= \ (us, mapInst, cache) ->
605 uniq = case lookupFM mapInst key of
608 mapInst' = addToFM mapInst key uniq
610 writeIORef names_var (us, mapInst', cache) >>
613 getUniqRn :: RnM d Unique
614 getUniqRn (RnDown {rn_ns = names_var}) l_down
615 = readIORef names_var >>= \ (us, mapInst, cache) ->
617 (us1,us') = splitUniqSupply us
619 writeIORef names_var (us', mapInst, cache) >>
620 return (uniqFromSupply us1)
623 ================ Module =====================
626 getModuleRn :: RnM d ModuleName
627 getModuleRn (RnDown {rn_mod = mod_name}) l_down
630 setModuleRn :: ModuleName -> RnM d a -> RnM d a
631 setModuleRn new_mod enclosed_thing rn_down l_down
632 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
636 setOmitQualFn :: (Name -> Bool) -> RnM d a -> RnM d a
637 setOmitQualFn fn m g_down l_down = m (g_down { rn_omit = fn }) l_down
639 getOmitQualFn :: RnM d (Name -> Bool)
640 getOmitQualFn (RnDown {rn_omit = omit_fn}) l_down
644 %************************************************************************
646 \subsection{Plumbing for rename-source part}
648 %************************************************************************
650 ================ RnEnv =====================
653 getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)
654 getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})
655 = return (global_env, local_env)
657 getLocalNameEnv :: RnMS LocalRdrEnv
658 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
661 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
662 setLocalNameEnv local_env' m rn_down l_down
663 = m rn_down (l_down {rn_lenv = local_env'})
665 getFixityEnv :: RnMS FixityEnv
666 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
669 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
670 extendFixityEnv fixes enclosed_scope
671 rn_down l_down@(SDown {rn_fixenv = fixity_env})
673 new_fixity_env = extendNameEnv fixity_env fixes
675 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
678 ================ Mode =====================
681 getModeRn :: RnMS RnMode
682 getModeRn rn_down (SDown {rn_mode = mode})
685 setModeRn :: RnMode -> RnMS a -> RnMS a
686 setModeRn new_mode thing_inside rn_down l_down
687 = thing_inside rn_down (l_down {rn_mode = new_mode})
691 %************************************************************************
693 \subsection{Plumbing for rename-globals part}
695 %************************************************************************
698 getIfacesRn :: RnM d Ifaces
699 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
700 = readIORef iface_var
702 setIfacesRn :: Ifaces -> RnM d ()
703 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
704 = writeIORef iface_var ifaces
706 getHiMaps :: RnM d (ModuleHiMap, ModuleHiMap)
707 getHiMaps (RnDown {rn_hi_maps = himaps}) _