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 %===================================================
93 \subsubsection{ MONAD TYPES}
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_ns :: IORef RnNameSupply,
106 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
107 rn_ifaces :: IORef Ifaces,
108 rn_hi_maps :: (ModuleHiMap, -- for .hi files
109 ModuleHiMap) -- for .hi-boot files
112 -- For renaming source code
116 rn_genv :: GlobalRdrEnv,
117 -- Global envt; the fixity component gets extended
118 -- with local fixity decls
120 rn_lenv :: LocalRdrEnv, -- Local name envt
121 -- Does *not* include 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 %===================================================
138 \subsubsection{ ENVIRONMENTS}
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,
218 -- Used to figure out "module M" export specifiers
219 -- Includes avails only from *unqualified* imports
220 -- (see 1.4 Report Section 5.1.1)
222 NameEnv AvailInfo) -- Used to figure out all other export specifiers.
223 -- Maps a Name to the AvailInfo that contains it
226 data GenAvailInfo name = Avail name -- An ordinary identifier
227 | AvailTC name -- The name of the type or class
228 [name] -- The available pieces of type/class.
229 -- NB: If the type or class is itself
230 -- to be in scope, it must be in this list.
231 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
233 type AvailInfo = GenAvailInfo Name
234 type RdrAvailInfo = GenAvailInfo OccName
237 %===================================================
238 \subsubsection{ INTERFACE FILE STUFF}
239 %===================================================
242 type ExportItem = (ModuleName, [RdrAvailInfo])
243 type VersionInfo name = [ImportVersion name]
245 type ImportVersion name = (ModuleName, Version, WhetherHasOrphans, WhatsImported name)
247 type WhetherHasOrphans = Bool
249 -- * an instance decl in a module other than the defn module for
250 -- one of the tycons or classes in the instance head
251 -- * a transformation rule in a module other than the one defining
252 -- the function in the head of the rule.
254 data WhatsImported name = Everything
255 | Specifically [LocalVersion name] -- List guaranteed non-empty
257 -- ("M", hif, ver, Everything) means there was a "module M" in
258 -- this module's export list, so we just have to go by M's version, "ver",
259 -- not the list of LocalVersions.
262 type LocalVersion name = (name, Version)
266 pi_mod :: Version, -- Module version number
267 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
268 pi_usages :: [ImportVersion OccName], -- Usages
269 pi_exports :: [ExportItem], -- Exports
270 pi_decls :: [(Version, RdrNameHsDecl)], -- Local definitions
271 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
272 pi_rules :: [RdrNameRuleDecl] -- Rules
275 type InterfaceDetails = (WhetherHasOrphans,
276 VersionInfo Name, -- Version information for what this module imports
277 ExportEnv) -- What modules this one depends on
280 -- needed by Main to fish out the fixities assoc list.
281 getIfaceFixities :: InterfaceDetails -> Fixities
282 getIfaceFixities (_, _, ExportEnv _ fs) = fs
285 type RdrNamePragma = () -- Fudge for now
288 data Ifaces = Ifaces {
289 iImpModInfo :: ImportedModuleInfo,
290 -- Modules this one depends on: that is, the union
291 -- of the modules its direct imports depend on.
293 iDecls :: DeclsMap, -- A single, global map of Names to decls
295 iFixes :: FixityEnv, -- A single, global map of Names to fixities
298 -- All the names (whether "big" or "small", whether wired-in or not,
299 -- whether locally defined or not) that have been slurped in so far.
301 iVSlurp :: [(Name,Version)],
302 -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
303 -- names that have been slurped in so far, with their versions.
304 -- This is used to generate the "usage" information for this module.
305 -- Subset of the previous field.
307 iInsts :: Bag GatedDecl,
308 -- The as-yet un-slurped instance decls; this bag is depleted when we
309 -- slurp an instance decl so that we don't slurp the same one twice.
310 -- Each is 'gated' by the names that must be available before
311 -- this instance decl is needed.
313 iRules :: Bag GatedDecl
314 -- Ditto transformation rules
317 type GatedDecl = (NameSet, (Module, RdrNameHsDecl))
319 type ImportedModuleInfo
320 = FiniteMap ModuleName (Version, Bool, Maybe (Module, Bool, Avails))
321 -- Suppose the domain element is module 'A'
323 -- The first Bool is True if A contains
324 -- 'orphan' rules or instance decls
326 -- The second Bool is true if the interface file actually
327 -- read was an .hi-boot file
329 -- Nothing => A's interface not yet read, but this module has
330 -- imported a module, B, that itself depends on A
332 -- Just xx => A's interface has been read. The Module in
333 -- the Just has the correct Dll flag
335 -- This set is used to decide whether to look for
336 -- A.hi or A.hi-boot when importing A.f.
337 -- Basically, we look for A.hi if A is in the map, and A.hi-boot
340 type DeclsMap = NameEnv (Version, AvailInfo, Bool, (Module, RdrNameHsDecl))
341 -- A DeclsMap contains a binding for each Name in the declaration
342 -- including the constructors of a type decl etc.
343 -- The Bool is True just for the 'main' Name.
347 %************************************************************************
349 \subsection{Main monad code}
351 %************************************************************************
354 initRn :: ModuleName -> UniqSupply -> SearchPath -> SrcLoc
356 -> IO (r, Bag ErrMsg, Bag WarnMsg)
358 initRn mod us dirs loc do_rn = do
359 himaps <- mkModuleHiMaps dirs
360 names_var <- newIORef (us, emptyFM, builtins)
361 errs_var <- newIORef (emptyBag,emptyBag)
362 iface_var <- newIORef emptyIfaces
364 rn_down = RnDown { rn_loc = loc, rn_ns = names_var,
367 rn_ifaces = iface_var,
371 res <- do_rn rn_down ()
373 -- grab errors and return
374 (warns, errs) <- readIORef errs_var
376 return (res, errs, warns)
379 initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r
380 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
382 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
383 rn_fixenv = fixity_env, rn_mode = mode }
385 thing_inside rn_down s_down
387 initIfaceRnMS :: Module -> RnMS r -> RnM d r
388 initIfaceRnMS mod thing_inside
389 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
390 setModuleRn (moduleName mod) thing_inside
392 emptyIfaces :: Ifaces
393 emptyIfaces = Ifaces { iImpModInfo = emptyFM,
394 iDecls = emptyNameEnv,
395 iFixes = emptyNameEnv,
396 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
397 -- Pretend that the dummy unbound name has already been
398 -- slurped. This is what's returned for an out-of-scope name,
399 -- and we don't want thereby to try to suck it in!
405 -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
406 -- during compiler debugging.
407 mkUnboundName :: RdrName -> Name
408 mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc
410 isUnboundName :: Name -> Bool
411 isUnboundName name = getUnique name == unboundKey
413 builtins :: FiniteMap (ModuleName,OccName) Name
416 mapBag (\ name -> ((moduleName (nameModule name), nameOccName name), name))
420 @renameSourceCode@ is used to rename stuff ``out-of-line'';
421 that is, not as part of the main renamer.
422 Sole examples: derived definitions,
423 which are only generated in the type checker.
425 The @RnNameSupply@ includes a @UniqueSupply@, so if you call it more than
426 once you must either split it, or install a fresh unique supply.
429 renameSourceCode :: ModuleName
434 renameSourceCode mod_name name_supply m
436 -- It's not really unsafe! When renaming source code we
437 -- only do any I/O if we need to read in a fixity declaration;
438 -- and that doesn't happen in pragmas etc
440 newIORef name_supply >>= \ names_var ->
441 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
443 rn_down = RnDown { rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,
446 s_down = SDown { rn_mode = InterfaceMode,
447 -- So that we can refer to PrelBase.True etc
448 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
449 rn_fixenv = emptyNameEnv }
451 m rn_down s_down >>= \ result ->
453 readIORef errs_var >>= \ (warns,errs) ->
455 (if not (isEmptyBag errs) then
456 pprTrace "Urk! renameSourceCode found errors" (display errs)
458 else if not (isEmptyBag warns) then
459 pprTrace "Note: renameSourceCode found warnings" (display warns)
467 display errs = pprBagOfErrors errs
469 {-# INLINE thenRn #-}
470 {-# INLINE thenRn_ #-}
471 {-# INLINE returnRn #-}
474 returnRn :: a -> RnM d a
475 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
476 thenRn_ :: RnM d a -> RnM d b -> RnM d b
477 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
478 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
479 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
480 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
481 sequenceRn :: [RnM d a] -> RnM d [a]
482 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
483 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
484 fixRn :: (a -> RnM d a) -> RnM d a
486 returnRn v gdown ldown = return v
487 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
488 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
489 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
490 andRn combiner m1 m2 gdown ldown
491 = m1 gdown ldown >>= \ res1 ->
492 m2 gdown ldown >>= \ res2 ->
493 return (combiner res1 res2)
495 sequenceRn [] = returnRn []
496 sequenceRn (m:ms) = m `thenRn` \ r ->
497 sequenceRn ms `thenRn` \ rs ->
500 mapRn f [] = returnRn []
502 = f x `thenRn` \ r ->
503 mapRn f xs `thenRn` \ rs ->
506 mapRn_ f [] = returnRn ()
511 foldlRn k z [] = returnRn z
512 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
515 mapAndUnzipRn f [] = returnRn ([],[])
516 mapAndUnzipRn f (x:xs)
517 = f x `thenRn` \ (r1, r2) ->
518 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
519 returnRn (r1:rs1, r2:rs2)
521 mapAndUnzip3Rn f [] = returnRn ([],[],[])
522 mapAndUnzip3Rn f (x:xs)
523 = f x `thenRn` \ (r1, r2, r3) ->
524 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
525 returnRn (r1:rs1, r2:rs2, r3:rs3)
527 mapMaybeRn f [] = returnRn []
528 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
529 mapMaybeRn f xs `thenRn` \ rs ->
531 Nothing -> returnRn rs
532 Just r -> returnRn (r:rs)
537 %************************************************************************
539 \subsection{Boring plumbing for common part}
541 %************************************************************************
545 \subsubsection{ Errors and warnings}
546 %=====================
549 failWithRn :: a -> Message -> RnM d a
550 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
551 = readIORef errs_var >>= \ (warns,errs) ->
552 writeIORef errs_var (warns, errs `snocBag` err) >>
555 err = addShortErrLocLine loc msg
557 warnWithRn :: a -> Message -> RnM d a
558 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
559 = readIORef errs_var >>= \ (warns,errs) ->
560 writeIORef errs_var (warns `snocBag` warn, errs) >>
563 warn = addShortWarnLocLine loc msg
565 addErrRn :: Message -> RnM d ()
566 addErrRn err = failWithRn () err
568 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
569 checkRn False err = addErrRn err
570 checkRn True err = returnRn ()
572 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
573 warnCheckRn False err = addWarnRn err
574 warnCheckRn True err = returnRn ()
576 addWarnRn :: Message -> RnM d ()
577 addWarnRn warn = warnWithRn () warn
579 checkErrsRn :: RnM d Bool -- True <=> no errors so far
580 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
581 = readIORef errs_var >>= \ (warns,errs) ->
582 return (isEmptyBag errs)
587 \subsubsection{ Source location}
588 %=====================
591 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
592 pushSrcLocRn loc' m down l_down
593 = m (down {rn_loc = loc'}) l_down
595 getSrcLocRn :: RnM d SrcLoc
596 getSrcLocRn down l_down
597 = return (rn_loc down)
601 \subsubsection{ Name supply}
602 %=====================
605 getNameSupplyRn :: RnM d RnNameSupply
606 getNameSupplyRn rn_down l_down
607 = readIORef (rn_ns rn_down)
609 setNameSupplyRn :: RnNameSupply -> RnM d ()
610 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
611 = writeIORef names_var names'
613 -- See comments with RnNameSupply above.
614 newInstUniq :: (OccName, OccName) -> RnM d Int
615 newInstUniq key (RnDown {rn_ns = names_var}) l_down
616 = readIORef names_var >>= \ (us, mapInst, cache) ->
618 uniq = case lookupFM mapInst key of
621 mapInst' = addToFM mapInst key uniq
623 writeIORef names_var (us, mapInst', cache) >>
626 getUniqRn :: RnM d Unique
627 getUniqRn (RnDown {rn_ns = names_var}) l_down
628 = readIORef names_var >>= \ (us, mapInst, cache) ->
630 (us1,us') = splitUniqSupply us
632 writeIORef names_var (us', mapInst, cache) >>
633 return (uniqFromSupply us1)
637 \subsubsection{ Module}
638 %=====================
641 getModuleRn :: RnM d ModuleName
642 getModuleRn (RnDown {rn_mod = mod_name}) l_down
645 setModuleRn :: ModuleName -> RnM d a -> RnM d a
646 setModuleRn new_mod enclosed_thing rn_down l_down
647 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
651 %************************************************************************
653 \subsection{Plumbing for rename-source part}
655 %************************************************************************
658 \subsubsection{ RnEnv}
659 %=====================
662 getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)
663 getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})
664 = return (global_env, local_env)
666 getLocalNameEnv :: RnMS LocalRdrEnv
667 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
670 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
671 setLocalNameEnv local_env' m rn_down l_down
672 = m rn_down (l_down {rn_lenv = local_env'})
674 getFixityEnv :: RnMS FixityEnv
675 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
678 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
679 extendFixityEnv fixes enclosed_scope
680 rn_down l_down@(SDown {rn_fixenv = fixity_env})
682 new_fixity_env = extendNameEnv fixity_env fixes
684 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
688 \subsubsection{ Mode}
689 %=====================
692 getModeRn :: RnMS RnMode
693 getModeRn rn_down (SDown {rn_mode = mode})
696 setModeRn :: RnMode -> RnMS a -> RnMS a
697 setModeRn new_mode thing_inside rn_down l_down
698 = thing_inside rn_down (l_down {rn_mode = new_mode})
702 %************************************************************************
704 \subsection{Plumbing for rename-globals part}
706 %************************************************************************
709 getIfacesRn :: RnM d Ifaces
710 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
711 = readIORef iface_var
713 setIfacesRn :: Ifaces -> RnM d ()
714 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
715 = writeIORef iface_var ifaces
717 getHiMaps :: RnM d (ModuleHiMap, ModuleHiMap)
718 getHiMaps (RnDown {rn_hi_maps = himaps}) _