2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnMonad]{The monad used by the renamer}
21 #include "HsVersions.h"
23 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 405
24 import IOExts ( fixIO )
25 #elif defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 302
26 import PrelIOBase ( fixIO ) -- Should be in GlaExts
28 import IOBase ( fixIO )
30 import IOExts ( IORef, newIORef, readIORef, writeIORef, unsafePerformIO )
34 import RnHsSyn ( RenamedFixitySig )
35 import BasicTypes ( Version )
36 import SrcLoc ( noSrcLoc )
37 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
38 pprBagOfErrors, ErrMsg, WarnMsg, Message
40 import Name ( Name, OccName, NamedThing(..),
41 isLocallyDefinedName, nameModule, nameOccName,
44 import Module ( Module, ModuleName, ModuleHiMap, SearchPath, WhereFrom,
45 mkModuleHiMaps, moduleName, mkVanillaModule, mkSearchPath
48 import RdrName ( RdrName, dummyRdrVarName, rdrNameOcc )
49 import CmdLineOpts ( opt_D_dump_rn_trace, opt_HiMap )
50 import PrelInfo ( builtinNames )
51 import TysWiredIn ( boolTyCon )
52 import SrcLoc ( SrcLoc, mkGeneratedSrcLoc )
53 import Unique ( Unique, getUnique, unboundKey )
54 import UniqFM ( UniqFM )
55 import FiniteMap ( FiniteMap, emptyFM, bagToFM, lookupFM, addToFM, addListToFM,
56 addListToFM_C, addToFM_C, eltsFM, fmToList
58 import Bag ( Bag, mapBag, emptyBag, isEmptyBag, snocBag )
59 import Maybes ( mapMaybe )
66 infixr 9 `thenRn`, `thenRn_`
70 %************************************************************************
72 \subsection{Somewhat magical interface to other monads}
74 %************************************************************************
77 ioToRnM :: IO r -> RnM d (Either IOError r)
78 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
80 (\ err -> return (Left err))
82 traceRn :: SDoc -> RnM d ()
83 traceRn msg | opt_D_dump_rn_trace = putDocRn msg
84 | otherwise = returnRn ()
86 putDocRn :: SDoc -> RnM d ()
87 putDocRn msg = ioToRnM (printErrs msg) `thenRn_`
92 %************************************************************************
94 \subsection{Data types}
96 %************************************************************************
98 %===================================================
99 \subsubsection{ MONAD TYPES}
100 %===================================================
103 type RnM d r = RnDown -> d -> IO r
104 type RnMS r = RnM SDown r -- Renaming source
105 type RnMG r = RnM () r -- Getting global names etc
108 data RnDown = RnDown {
109 rn_mod :: ModuleName,
111 rn_ns :: IORef RnNameSupply,
112 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
113 rn_ifaces :: IORef Ifaces,
114 rn_hi_maps :: (ModuleHiMap, -- for .hi files
115 ModuleHiMap) -- for .hi-boot files
118 -- For renaming source code
122 rn_genv :: GlobalRdrEnv,
123 -- Global envt; the fixity component gets extended
124 -- with local fixity decls
126 rn_lenv :: LocalRdrEnv, -- Local name envt
127 -- Does *not* include global name envt; may shadow it
128 -- Includes both ordinary variables and type variables;
129 -- they are kept distinct because tyvar have a different
130 -- occurrence contructor (Name.TvOcc)
131 -- We still need the unsullied global name env so that
132 -- we can look up record field names
134 rn_fixenv :: FixityEnv -- Local fixities
135 -- The global ones are held in the
139 data RnMode = SourceMode -- Renaming source code
140 | InterfaceMode -- Renaming interface declarations.
143 %===================================================
144 \subsubsection{ ENVIRONMENTS}
145 %===================================================
148 --------------------------------
149 type RdrNameEnv a = FiniteMap RdrName a
150 type GlobalRdrEnv = RdrNameEnv [Name] -- The list is because there may be name clashes
151 -- These only get reported on lookup,
152 -- not on construction
153 type LocalRdrEnv = RdrNameEnv Name
155 emptyRdrEnv :: RdrNameEnv a
156 lookupRdrEnv :: RdrNameEnv a -> RdrName -> Maybe a
157 addListToRdrEnv :: RdrNameEnv a -> [(RdrName,a)] -> RdrNameEnv a
158 extendRdrEnv :: RdrNameEnv a -> RdrName -> a -> RdrNameEnv a
160 emptyRdrEnv = emptyFM
161 lookupRdrEnv = lookupFM
162 addListToRdrEnv = addListToFM
164 extendRdrEnv = addToFM
165 rdrEnvToList = fmToList
167 --------------------------------
168 type NameEnv a = UniqFM a -- Domain is Name
170 emptyNameEnv :: NameEnv a
171 nameEnvElts :: NameEnv a -> [a]
172 addToNameEnv_C :: (a->a->a) -> NameEnv a -> Name -> a -> NameEnv a
173 addToNameEnv :: NameEnv a -> Name -> a -> NameEnv a
174 plusNameEnv :: NameEnv a -> NameEnv a -> NameEnv a
175 extendNameEnv :: NameEnv a -> [(Name,a)] -> NameEnv a
176 lookupNameEnv :: NameEnv a -> Name -> Maybe a
177 delFromNameEnv :: NameEnv a -> Name -> NameEnv a
178 elemNameEnv :: Name -> NameEnv a -> Bool
180 emptyNameEnv = emptyUFM
181 nameEnvElts = eltsUFM
182 addToNameEnv_C = addToUFM_C
183 addToNameEnv = addToUFM
184 plusNameEnv = plusUFM
185 extendNameEnv = addListToUFM
186 lookupNameEnv = lookupUFM
187 delFromNameEnv = delFromUFM
188 elemNameEnv = elemUFM
190 --------------------------------
191 type FixityEnv = NameEnv RenamedFixitySig
192 -- We keep the whole fixity sig so that we
193 -- can report line-number info when there is a duplicate
194 -- fixity declaration
198 --------------------------------
202 , FiniteMap String Int
203 -- This is used as a name supply for dictionary functions
204 -- From the inst decl we derive a string, usually by glomming together
205 -- the class and tycon name -- but it doesn't matter exactly how;
206 -- this map then gives a unique int for each inst decl with that
207 -- string. (In Haskell 98 there can only be one,
208 -- but not so in more extended versions; also class CC type T
209 -- and class C type TT might both give the string CCT
211 -- We could just use one Int for all the instance decls, but this
212 -- way the uniques change less when you add an instance decl,
213 -- hence less recompilation
215 , FiniteMap (ModuleName, OccName) Name
216 -- Ensures that one (module,occname) pair gets one unique
220 --------------------------------
221 data ExportEnv = ExportEnv Avails Fixities
222 type Avails = [AvailInfo]
223 type Fixities = [(Name, Fixity)]
225 type ExportAvails = (FiniteMap ModuleName Avails,
226 -- Used to figure out "module M" export specifiers
227 -- Includes avails only from *unqualified* imports
228 -- (see 1.4 Report Section 5.1.1)
230 NameEnv AvailInfo) -- Used to figure out all other export specifiers.
231 -- Maps a Name to the AvailInfo that contains it
234 data GenAvailInfo name = Avail name -- An ordinary identifier
235 | AvailTC name -- The name of the type or class
236 [name] -- The available pieces of type/class.
237 -- NB: If the type or class is itself
238 -- to be in scope, it must be in this list.
239 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
241 type AvailInfo = GenAvailInfo Name
242 type RdrAvailInfo = GenAvailInfo OccName
245 %===================================================
246 \subsubsection{ INTERFACE FILE STUFF}
247 %===================================================
250 type ExportItem = (ModuleName, [RdrAvailInfo])
251 type VersionInfo name = [ImportVersion name]
253 type ImportVersion name = (ModuleName, Version, WhetherHasOrphans, WhatsImported name)
255 type WhetherHasOrphans = Bool
257 -- * an instance decl in a module other than the defn module for
258 -- one of the tycons or classes in the instance head
259 -- * a transformation rule in a module other than the one defining
260 -- the function in the head of the rule.
262 data WhatsImported name = Everything
263 | Specifically [LocalVersion name] -- List guaranteed non-empty
265 -- ("M", hif, ver, Everything) means there was a "module M" in
266 -- this module's export list, so we just have to go by M's version, "ver",
267 -- not the list of LocalVersions.
270 type LocalVersion name = (name, Version)
274 pi_mod :: Version, -- Module version number
275 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
276 pi_usages :: [ImportVersion OccName], -- Usages
277 pi_exports :: [ExportItem], -- Exports
278 pi_decls :: [(Version, RdrNameHsDecl)], -- Local definitions
279 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
280 pi_rules :: [RdrNameRuleDecl] -- Rules
283 type InterfaceDetails = (WhetherHasOrphans,
284 VersionInfo Name, -- Version information for what this module imports
285 ExportEnv) -- What modules this one depends on
288 -- needed by Main to fish out the fixities assoc list.
289 getIfaceFixities :: InterfaceDetails -> Fixities
290 getIfaceFixities (_, _, ExportEnv _ fs) = fs
293 type RdrNamePragma = () -- Fudge for now
296 data Ifaces = Ifaces {
297 iImpModInfo :: ImportedModuleInfo,
298 -- Modules this one depends on: that is, the union
299 -- of the modules its *direct* imports depend on.
300 -- NB: The direct imports have .hi files that enumerate *all* the
301 -- dependencies (direct or not) of the imported module.
303 iDecls :: DeclsMap, -- A single, global map of Names to decls
305 iFixes :: FixityEnv, -- A single, global map of Names to fixities
308 -- All the names (whether "big" or "small", whether wired-in or not,
309 -- whether locally defined or not) that have been slurped in so far.
311 iVSlurp :: [(Name,Version)],
312 -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
313 -- names that have been slurped in so far, with their versions.
314 -- This is used to generate the "usage" information for this module.
315 -- Subset of the previous field.
317 iInsts :: Bag GatedDecl,
318 -- The as-yet un-slurped instance decls; this bag is depleted when we
319 -- slurp an instance decl so that we don't slurp the same one twice.
320 -- Each is 'gated' by the names that must be available before
321 -- this instance decl is needed.
323 iRules :: Bag GatedDecl
324 -- Ditto transformation rules
327 type GatedDecl = (NameSet, (Module, RdrNameHsDecl))
329 type ImportedModuleInfo
330 = FiniteMap ModuleName (Version, Bool, Maybe (Module, Bool, Avails))
331 -- Suppose the domain element is module 'A'
333 -- The first Bool is True if A contains
334 -- 'orphan' rules or instance decls
336 -- The second Bool is true if the interface file actually
337 -- read was an .hi-boot file
339 -- Nothing => A's interface not yet read, but this module has
340 -- imported a module, B, that itself depends on A
342 -- Just xx => A's interface has been read. The Module in
343 -- the Just has the correct Dll flag
345 -- This set is used to decide whether to look for
346 -- A.hi or A.hi-boot when importing A.f.
347 -- Basically, we look for A.hi if A is in the map, and A.hi-boot
350 type DeclsMap = NameEnv (Version, AvailInfo, Bool, (Module, RdrNameHsDecl))
351 -- A DeclsMap contains a binding for each Name in the declaration
352 -- including the constructors of a type decl etc.
353 -- The Bool is True just for the 'main' Name.
357 %************************************************************************
359 \subsection{Main monad code}
361 %************************************************************************
364 initRn :: ModuleName -> UniqSupply -> SearchPath -> SrcLoc
366 -> IO (r, Bag ErrMsg, Bag WarnMsg)
368 initRn mod us dirs loc do_rn = do
369 himaps <- mkModuleHiMaps dirs
370 names_var <- newIORef (us, emptyFM, builtins)
371 errs_var <- newIORef (emptyBag,emptyBag)
372 iface_var <- newIORef emptyIfaces
374 rn_down = RnDown { rn_loc = loc, rn_ns = names_var,
377 rn_ifaces = iface_var,
381 res <- do_rn rn_down ()
383 -- grab errors and return
384 (warns, errs) <- readIORef errs_var
386 return (res, errs, warns)
389 initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r
390 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
392 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
393 rn_fixenv = fixity_env, rn_mode = mode }
395 thing_inside rn_down s_down
397 initIfaceRnMS :: Module -> RnMS r -> RnM d r
398 initIfaceRnMS mod thing_inside
399 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
400 setModuleRn (moduleName mod) thing_inside
402 emptyIfaces :: Ifaces
403 emptyIfaces = Ifaces { iImpModInfo = emptyFM,
404 iDecls = emptyNameEnv,
405 iFixes = emptyNameEnv,
406 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
407 -- Pretend that the dummy unbound name has already been
408 -- slurped. This is what's returned for an out-of-scope name,
409 -- and we don't want thereby to try to suck it in!
415 -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
416 -- during compiler debugging.
417 mkUnboundName :: RdrName -> Name
418 mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc
420 isUnboundName :: Name -> Bool
421 isUnboundName name = getUnique name == unboundKey
423 builtins :: FiniteMap (ModuleName,OccName) Name
426 mapBag (\ name -> ((moduleName (nameModule name), nameOccName name), name))
430 @renameSourceCode@ is used to rename stuff ``out-of-line'';
431 that is, not as part of the main renamer.
432 Sole examples: derived definitions,
433 which are only generated in the type checker.
435 The @RnNameSupply@ includes a @UniqueSupply@, so if you call it more than
436 once you must either split it, or install a fresh unique supply.
439 renameSourceCode :: ModuleName
444 renameSourceCode mod_name name_supply m
446 -- It's not really unsafe! When renaming source code we
447 -- only do any I/O if we need to read in a fixity declaration;
448 -- and that doesn't happen in pragmas etc
450 mkModuleHiMaps (mkSearchPath opt_HiMap) >>= \ himaps ->
451 newIORef name_supply >>= \ names_var ->
452 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
454 rn_down = RnDown { rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,
455 rn_errs = errs_var, rn_hi_maps = himaps,
457 s_down = SDown { rn_mode = InterfaceMode,
458 -- So that we can refer to PrelBase.True etc
459 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
460 rn_fixenv = emptyNameEnv }
462 m rn_down s_down >>= \ result ->
464 readIORef errs_var >>= \ (warns,errs) ->
466 (if not (isEmptyBag errs) then
467 pprTrace "Urk! renameSourceCode found errors" (display errs)
469 else if not (isEmptyBag warns) then
470 pprTrace "Note: renameSourceCode found warnings" (display warns)
478 display errs = pprBagOfErrors errs
480 {-# INLINE thenRn #-}
481 {-# INLINE thenRn_ #-}
482 {-# INLINE returnRn #-}
485 returnRn :: a -> RnM d a
486 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
487 thenRn_ :: RnM d a -> RnM d b -> RnM d b
488 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
489 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
490 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
491 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
492 sequenceRn :: [RnM d a] -> RnM d [a]
493 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
494 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
495 fixRn :: (a -> RnM d a) -> RnM d a
497 returnRn v gdown ldown = return v
498 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
499 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
500 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
501 andRn combiner m1 m2 gdown ldown
502 = m1 gdown ldown >>= \ res1 ->
503 m2 gdown ldown >>= \ res2 ->
504 return (combiner res1 res2)
506 sequenceRn [] = returnRn []
507 sequenceRn (m:ms) = m `thenRn` \ r ->
508 sequenceRn ms `thenRn` \ rs ->
511 mapRn f [] = returnRn []
513 = f x `thenRn` \ r ->
514 mapRn f xs `thenRn` \ rs ->
517 mapRn_ f [] = returnRn ()
522 foldlRn k z [] = returnRn z
523 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
526 mapAndUnzipRn f [] = returnRn ([],[])
527 mapAndUnzipRn f (x:xs)
528 = f x `thenRn` \ (r1, r2) ->
529 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
530 returnRn (r1:rs1, r2:rs2)
532 mapAndUnzip3Rn f [] = returnRn ([],[],[])
533 mapAndUnzip3Rn f (x:xs)
534 = f x `thenRn` \ (r1, r2, r3) ->
535 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
536 returnRn (r1:rs1, r2:rs2, r3:rs3)
538 mapMaybeRn f [] = returnRn []
539 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
540 mapMaybeRn f xs `thenRn` \ rs ->
542 Nothing -> returnRn rs
543 Just r -> returnRn (r:rs)
548 %************************************************************************
550 \subsection{Boring plumbing for common part}
552 %************************************************************************
556 \subsubsection{ Errors and warnings}
557 %=====================
560 failWithRn :: a -> Message -> RnM d a
561 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
562 = readIORef errs_var >>= \ (warns,errs) ->
563 writeIORef errs_var (warns, errs `snocBag` err) >>
566 err = addShortErrLocLine loc msg
568 warnWithRn :: a -> Message -> RnM d a
569 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
570 = readIORef errs_var >>= \ (warns,errs) ->
571 writeIORef errs_var (warns `snocBag` warn, errs) >>
574 warn = addShortWarnLocLine loc msg
576 addErrRn :: Message -> RnM d ()
577 addErrRn err = failWithRn () err
579 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
580 checkRn False err = addErrRn err
581 checkRn True err = returnRn ()
583 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
584 warnCheckRn False err = addWarnRn err
585 warnCheckRn True err = returnRn ()
587 addWarnRn :: Message -> RnM d ()
588 addWarnRn warn = warnWithRn () warn
590 checkErrsRn :: RnM d Bool -- True <=> no errors so far
591 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
592 = readIORef errs_var >>= \ (warns,errs) ->
593 return (isEmptyBag errs)
598 \subsubsection{ Source location}
599 %=====================
602 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
603 pushSrcLocRn loc' m down l_down
604 = m (down {rn_loc = loc'}) l_down
606 getSrcLocRn :: RnM d SrcLoc
607 getSrcLocRn down l_down
608 = return (rn_loc down)
612 \subsubsection{ Name supply}
613 %=====================
616 getNameSupplyRn :: RnM d RnNameSupply
617 getNameSupplyRn rn_down l_down
618 = readIORef (rn_ns rn_down)
620 setNameSupplyRn :: RnNameSupply -> RnM d ()
621 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
622 = writeIORef names_var names'
624 -- See comments with RnNameSupply above.
625 newInstUniq :: String -> RnM d Int
626 newInstUniq key (RnDown {rn_ns = names_var}) l_down
627 = readIORef names_var >>= \ (us, mapInst, cache) ->
629 uniq = case lookupFM mapInst key of
632 mapInst' = addToFM mapInst key uniq
634 writeIORef names_var (us, mapInst', cache) >>
637 getUniqRn :: RnM d Unique
638 getUniqRn (RnDown {rn_ns = names_var}) l_down
639 = readIORef names_var >>= \ (us, mapInst, cache) ->
641 (us1,us') = splitUniqSupply us
643 writeIORef names_var (us', mapInst, cache) >>
644 return (uniqFromSupply us1)
648 \subsubsection{ Module}
649 %=====================
652 getModuleRn :: RnM d ModuleName
653 getModuleRn (RnDown {rn_mod = mod_name}) l_down
656 setModuleRn :: ModuleName -> RnM d a -> RnM d a
657 setModuleRn new_mod enclosed_thing rn_down l_down
658 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
662 %************************************************************************
664 \subsection{Plumbing for rename-source part}
666 %************************************************************************
669 \subsubsection{ RnEnv}
670 %=====================
673 getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)
674 getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})
675 = return (global_env, local_env)
677 getLocalNameEnv :: RnMS LocalRdrEnv
678 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
681 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
682 setLocalNameEnv local_env' m rn_down l_down
683 = m rn_down (l_down {rn_lenv = local_env'})
685 getFixityEnv :: RnMS FixityEnv
686 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
689 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
690 extendFixityEnv fixes enclosed_scope
691 rn_down l_down@(SDown {rn_fixenv = fixity_env})
693 new_fixity_env = extendNameEnv fixity_env fixes
695 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
699 \subsubsection{ Mode}
700 %=====================
703 getModeRn :: RnMS RnMode
704 getModeRn rn_down (SDown {rn_mode = mode})
707 setModeRn :: RnMode -> RnMS a -> RnMS a
708 setModeRn new_mode thing_inside rn_down l_down
709 = thing_inside rn_down (l_down {rn_mode = new_mode})
713 %************************************************************************
715 \subsection{Plumbing for rename-globals part}
717 %************************************************************************
720 getIfacesRn :: RnM d Ifaces
721 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
722 = readIORef iface_var
724 setIfacesRn :: Ifaces -> RnM d ()
725 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
726 = writeIORef iface_var ifaces
728 getHiMaps :: RnM d (ModuleHiMap, ModuleHiMap)
729 getHiMaps (RnDown {rn_hi_maps = himaps}) _
734 lookupModuleRn :: ModuleName -> RnM d Module
736 getHiMaps `thenRn` \ (himap, _) ->
737 case lookupFM himap x of
738 Nothing -> returnRn (mkVanillaModule x)
739 Just (_,x) -> returnRn x