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
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
160 --------------------------------
161 type NameEnv a = UniqFM a -- Domain is Name
163 emptyNameEnv :: NameEnv a
164 nameEnvElts :: NameEnv a -> [a]
165 addToNameEnv_C :: (a->a->a) -> NameEnv a -> Name -> a -> NameEnv a
166 addToNameEnv :: NameEnv a -> Name -> a -> NameEnv a
167 plusNameEnv :: NameEnv a -> NameEnv a -> NameEnv a
168 extendNameEnv :: NameEnv a -> [(Name,a)] -> NameEnv a
169 lookupNameEnv :: NameEnv a -> Name -> Maybe a
170 delFromNameEnv :: NameEnv a -> Name -> NameEnv a
171 elemNameEnv :: Name -> NameEnv a -> Bool
173 emptyNameEnv = emptyUFM
174 nameEnvElts = eltsUFM
175 addToNameEnv_C = addToUFM_C
176 addToNameEnv = addToUFM
177 plusNameEnv = plusUFM
178 extendNameEnv = addListToUFM
179 lookupNameEnv = lookupUFM
180 delFromNameEnv = delFromUFM
181 elemNameEnv = elemUFM
183 --------------------------------
184 type FixityEnv = NameEnv RenamedFixitySig
185 -- We keep the whole fixity sig so that we
186 -- can report line-number info when there is a duplicate
187 -- fixity declaration
191 --------------------------------
195 , FiniteMap (OccName, OccName) Int
196 -- This is used as a name supply for dictionary functions
197 -- From the inst decl we derive a (class, tycon) pair;
198 -- this map then gives a unique int for each inst decl with that
199 -- (class, tycon) pair. (In Haskell 98 there can only be one,
200 -- but not so in more extended versions.)
202 -- We could just use one Int for all the instance decls, but this
203 -- way the uniques change less when you add an instance decl,
204 -- hence less recompilation
206 , FiniteMap (ModuleName, OccName) Name
207 -- Ensures that one (module,occname) pair gets one unique
211 --------------------------------
212 data ExportEnv = ExportEnv Avails Fixities
213 type Avails = [AvailInfo]
214 type Fixities = [(Name, Fixity)]
216 type ExportAvails = (FiniteMap ModuleName Avails, -- Used to figure out "module M" export specifiers
217 -- Includes avails only from *unqualified* imports
218 -- (see 1.4 Report Section 5.1.1)
220 NameEnv AvailInfo) -- Used to figure out all other export specifiers.
221 -- Maps a Name to the AvailInfo that contains it
224 data GenAvailInfo name = Avail name -- An ordinary identifier
225 | AvailTC name -- The name of the type or class
226 [name] -- The available pieces of type/class. NB: If the type or
227 -- class is itself to be in scope, it must be in this list.
228 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
229 type AvailInfo = GenAvailInfo Name
230 type RdrAvailInfo = GenAvailInfo OccName
233 ===================================================
235 ===================================================
238 type ExportItem = (ModuleName, [RdrAvailInfo])
239 type VersionInfo name = [ImportVersion name]
241 type ImportVersion name = (ModuleName, Version, WhetherHasOrphans, WhatsImported name)
243 type WhetherHasOrphans = Bool
245 -- * an instance decl in a module other than the defn module for
246 -- one of the tycons or classes in the instance head
247 -- * a transformation rule in a module other than the one defining
248 -- the function in the head of the rule.
250 data WhatsImported name = Everything
251 | Specifically [LocalVersion name] -- List guaranteed non-empty
253 -- ("M", hif, ver, Everything) means there was a "module M" in
254 -- this module's export list, so we just have to go by M's version, "ver",
255 -- not the list of LocalVersions.
258 type LocalVersion name = (name, Version)
262 pi_mod :: Version, -- Module version number
263 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
264 pi_usages :: [ImportVersion OccName], -- Usages
265 pi_exports :: [ExportItem], -- Exports
266 pi_decls :: [(Version, RdrNameHsDecl)], -- Local definitions
267 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
268 pi_rules :: [RdrNameRuleDecl] -- Rules
271 type InterfaceDetails = (WhetherHasOrphans,
272 VersionInfo Name, -- Version information for what this module imports
273 ExportEnv) -- What modules this one depends on
276 -- needed by Main to fish out the fixities assoc list.
277 getIfaceFixities :: InterfaceDetails -> Fixities
278 getIfaceFixities (_, _, ExportEnv _ fs) = fs
281 type RdrNamePragma = () -- Fudge for now
284 data Ifaces = Ifaces {
285 iImpModInfo :: ImportedModuleInfo,
286 -- Modules this one depends on: that is, the union
287 -- of the modules its direct imports depend on.
289 iDecls :: DeclsMap, -- A single, global map of Names to decls
291 iFixes :: FixityEnv, -- A single, global map of Names to fixities
293 iSlurp :: NameSet, -- All the names (whether "big" or "small", whether wired-in or not,
294 -- whether locally defined or not) that have been slurped in so far.
296 iVSlurp :: [(Name,Version)], -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
297 -- names that have been slurped in so far, with their versions.
298 -- This is used to generate the "usage" information for this module.
299 -- Subset of the previous field.
301 iInsts :: Bag GatedDecl,
302 -- The as-yet un-slurped instance decls; this bag is depleted when we
303 -- slurp an instance decl so that we don't slurp the same one twice.
304 -- Each is 'gated' by the names that must be available before
305 -- this instance decl is needed.
307 iRules :: Bag GatedDecl
308 -- Ditto transformation rules
311 type GatedDecl = (NameSet, (Module, RdrNameHsDecl))
313 type ImportedModuleInfo
314 = FiniteMap ModuleName (Version, Bool, Maybe (Module, Bool, Avails))
315 -- Suppose the domain element is module 'A'
317 -- The first Bool is True if A contains
318 -- 'orphan' rules or instance decls
320 -- The second Bool is true if the interface file actually
321 -- read was an .hi-boot file
323 -- Nothing => A's interface not yet read, but this module has
324 -- imported a module, B, that itself depends on A
326 -- Just xx => A's interface has been read. The Module in
327 -- the Just has the correct Dll flag
329 -- This set is used to decide whether to look for
330 -- A.hi or A.hi-boot when importing A.f.
331 -- Basically, we look for A.hi if A is in the map, and A.hi-boot
334 type DeclsMap = NameEnv (Version, AvailInfo, Bool, (Module, RdrNameHsDecl))
335 -- A DeclsMap contains a binding for each Name in the declaration
336 -- including the constructors of a type decl etc.
337 -- The Bool is True just for the 'main' Name.
341 %************************************************************************
343 \subsection{Main monad code}
345 %************************************************************************
348 initRn :: ModuleName -> UniqSupply -> SearchPath -> SrcLoc
350 -> IO (r, Bag ErrMsg, Bag WarnMsg)
352 initRn mod us dirs loc do_rn = do
353 himaps <- mkModuleHiMaps dirs
354 names_var <- newIORef (us, emptyFM, builtins)
355 errs_var <- newIORef (emptyBag,emptyBag)
356 iface_var <- newIORef emptyIfaces
358 rn_down = RnDown { rn_loc = loc, rn_omit = \n -> False, rn_ns = names_var,
361 rn_ifaces = iface_var,
365 res <- do_rn rn_down ()
367 -- grab errors and return
368 (warns, errs) <- readIORef errs_var
370 return (res, errs, warns)
373 initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r
374 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
376 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
377 rn_fixenv = fixity_env, rn_mode = mode }
379 thing_inside rn_down s_down
381 initIfaceRnMS :: Module -> RnMS r -> RnM d r
382 initIfaceRnMS mod thing_inside
383 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
384 setModuleRn (moduleName mod) thing_inside
386 emptyIfaces :: Ifaces
387 emptyIfaces = Ifaces { iImpModInfo = emptyFM,
388 iDecls = emptyNameEnv,
389 iFixes = emptyNameEnv,
390 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
391 -- Pretend that the dummy unbound name has already been
392 -- slurped. This is what's returned for an out-of-scope name,
393 -- and we don't want thereby to try to suck it in!
399 -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
400 -- during compiler debugging.
401 mkUnboundName :: RdrName -> Name
402 mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc
404 isUnboundName :: Name -> Bool
405 isUnboundName name = getUnique name == unboundKey
407 builtins :: FiniteMap (ModuleName,OccName) Name
410 mapBag (\ name -> ((moduleName (nameModule name), nameOccName name), name))
414 @renameSourceCode@ is used to rename stuff "out-of-line"; that is, not as part of
415 the main renamer. Sole examples: derived definitions, which are only generated
418 The @RnNameSupply@ includes a @UniqueSupply@, so if you call it more than
419 once you must either split it, or install a fresh unique supply.
422 renameSourceCode :: ModuleName
427 renameSourceCode mod_name name_supply m
429 -- It's not really unsafe! When renaming source code we
430 -- only do any I/O if we need to read in a fixity declaration;
431 -- and that doesn't happen in pragmas etc
433 newIORef name_supply >>= \ names_var ->
434 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
436 rn_down = RnDown { rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,
439 s_down = SDown { rn_mode = InterfaceMode, -- So that we can refer to PrelBase.True etc
440 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
441 rn_fixenv = emptyNameEnv }
443 m rn_down s_down >>= \ result ->
445 readIORef errs_var >>= \ (warns,errs) ->
447 (if not (isEmptyBag errs) then
448 pprTrace "Urk! renameSourceCode found errors" (display errs)
450 else if not (isEmptyBag warns) then
451 pprTrace "Note: renameSourceCode found warnings" (display warns)
459 display errs = pprBagOfErrors errs
461 {-# INLINE thenRn #-}
462 {-# INLINE thenRn_ #-}
463 {-# INLINE returnRn #-}
466 returnRn :: a -> RnM d a
467 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
468 thenRn_ :: RnM d a -> RnM d b -> RnM d b
469 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
470 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
471 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
472 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
473 sequenceRn :: [RnM d a] -> RnM d [a]
474 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
475 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
476 fixRn :: (a -> RnM d a) -> RnM d a
478 returnRn v gdown ldown = return v
479 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
480 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
481 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
482 andRn combiner m1 m2 gdown ldown
483 = m1 gdown ldown >>= \ res1 ->
484 m2 gdown ldown >>= \ res2 ->
485 return (combiner res1 res2)
487 sequenceRn [] = returnRn []
488 sequenceRn (m:ms) = m `thenRn` \ r ->
489 sequenceRn ms `thenRn` \ rs ->
492 mapRn f [] = returnRn []
494 = f x `thenRn` \ r ->
495 mapRn f xs `thenRn` \ rs ->
498 mapRn_ f [] = returnRn ()
503 foldlRn k z [] = returnRn z
504 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
507 mapAndUnzipRn f [] = returnRn ([],[])
508 mapAndUnzipRn f (x:xs)
509 = f x `thenRn` \ (r1, r2) ->
510 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
511 returnRn (r1:rs1, r2:rs2)
513 mapAndUnzip3Rn f [] = returnRn ([],[],[])
514 mapAndUnzip3Rn f (x:xs)
515 = f x `thenRn` \ (r1, r2, r3) ->
516 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
517 returnRn (r1:rs1, r2:rs2, r3:rs3)
519 mapMaybeRn f [] = returnRn []
520 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
521 mapMaybeRn f xs `thenRn` \ rs ->
523 Nothing -> returnRn rs
524 Just r -> returnRn (r:rs)
529 %************************************************************************
531 \subsection{Boring plumbing for common part}
533 %************************************************************************
536 ================ Errors and warnings =====================
539 failWithRn :: a -> Message -> RnM d a
540 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
541 = readIORef errs_var >>= \ (warns,errs) ->
542 writeIORef errs_var (warns, errs `snocBag` err) >>
545 err = addShortErrLocLine loc msg
547 warnWithRn :: a -> Message -> RnM d a
548 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
549 = readIORef errs_var >>= \ (warns,errs) ->
550 writeIORef errs_var (warns `snocBag` warn, errs) >>
553 warn = addShortWarnLocLine loc msg
555 addErrRn :: Message -> RnM d ()
556 addErrRn err = failWithRn () err
558 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
559 checkRn False err = addErrRn err
560 checkRn True err = returnRn ()
562 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
563 warnCheckRn False err = addWarnRn err
564 warnCheckRn True err = returnRn ()
566 addWarnRn :: Message -> RnM d ()
567 addWarnRn warn = warnWithRn () warn
569 checkErrsRn :: RnM d Bool -- True <=> no errors so far
570 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
571 = readIORef errs_var >>= \ (warns,errs) ->
572 return (isEmptyBag errs)
576 ================ Source location =====================
579 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
580 pushSrcLocRn loc' m down l_down
581 = m (down {rn_loc = loc'}) l_down
583 getSrcLocRn :: RnM d SrcLoc
584 getSrcLocRn down l_down
585 = return (rn_loc down)
588 ================ Name supply =====================
591 getNameSupplyRn :: RnM d RnNameSupply
592 getNameSupplyRn rn_down l_down
593 = readIORef (rn_ns rn_down)
595 setNameSupplyRn :: RnNameSupply -> RnM d ()
596 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
597 = writeIORef names_var names'
599 -- See comments with RnNameSupply above.
600 newInstUniq :: (OccName, OccName) -> RnM d Int
601 newInstUniq key (RnDown {rn_ns = names_var}) l_down
602 = readIORef names_var >>= \ (us, mapInst, cache) ->
604 uniq = case lookupFM mapInst key of
607 mapInst' = addToFM mapInst key uniq
609 writeIORef names_var (us, mapInst', cache) >>
612 getUniqRn :: RnM d Unique
613 getUniqRn (RnDown {rn_ns = names_var}) l_down
614 = readIORef names_var >>= \ (us, mapInst, cache) ->
616 (us1,us') = splitUniqSupply us
618 writeIORef names_var (us', mapInst, cache) >>
619 return (uniqFromSupply us1)
622 ================ Module =====================
625 getModuleRn :: RnM d ModuleName
626 getModuleRn (RnDown {rn_mod = mod_name}) l_down
629 setModuleRn :: ModuleName -> RnM d a -> RnM d a
630 setModuleRn new_mod enclosed_thing rn_down l_down
631 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
635 setOmitQualFn :: (Name -> Bool) -> RnM d a -> RnM d a
636 setOmitQualFn fn m g_down l_down = m (g_down { rn_omit = fn }) l_down
638 getOmitQualFn :: RnM d (Name -> Bool)
639 getOmitQualFn (RnDown {rn_omit = omit_fn}) l_down
643 %************************************************************************
645 \subsection{Plumbing for rename-source part}
647 %************************************************************************
649 ================ RnEnv =====================
652 getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)
653 getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})
654 = return (global_env, local_env)
656 getLocalNameEnv :: RnMS LocalRdrEnv
657 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
660 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
661 setLocalNameEnv local_env' m rn_down l_down
662 = m rn_down (l_down {rn_lenv = local_env'})
664 getFixityEnv :: RnMS FixityEnv
665 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
668 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
669 extendFixityEnv fixes enclosed_scope
670 rn_down l_down@(SDown {rn_fixenv = fixity_env})
672 new_fixity_env = extendNameEnv fixity_env fixes
674 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
677 ================ Mode =====================
680 getModeRn :: RnMS RnMode
681 getModeRn rn_down (SDown {rn_mode = mode})
684 setModeRn :: RnMode -> RnMS a -> RnMS a
685 setModeRn new_mode thing_inside rn_down l_down
686 = thing_inside rn_down (l_down {rn_mode = new_mode})
690 %************************************************************************
692 \subsection{Plumbing for rename-globals part}
694 %************************************************************************
697 getIfacesRn :: RnM d Ifaces
698 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
699 = readIORef iface_var
701 setIfacesRn :: Ifaces -> RnM d ()
702 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
703 = writeIORef iface_var ifaces
705 getHiMaps :: RnM d (ModuleHiMap, ModuleHiMap)
706 getHiMaps (RnDown {rn_hi_maps = himaps}) _