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"
26 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 405
27 import IOExts ( fixIO )
28 #elif defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 302
29 import PrelIOBase ( fixIO ) -- Should be in GlaExts
31 import IOBase ( fixIO )
33 import IOExts ( IORef, newIORef, readIORef, writeIORef, unsafePerformIO )
37 import RnHsSyn ( RenamedFixitySig )
38 import BasicTypes ( Version, defaultFixity )
39 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
40 pprBagOfErrors, ErrMsg, WarnMsg, Message
42 import RdrName ( RdrName, dummyRdrVarName, rdrNameModule, rdrNameOcc,
43 RdrNameEnv, emptyRdrEnv, extendRdrEnv,
44 lookupRdrEnv, addListToRdrEnv, rdrEnvToList, rdrEnvElts
46 import Name ( Name, OccName, NamedThing(..), getSrcLoc,
47 isLocallyDefinedName, nameModule, nameOccName,
48 decode, mkLocalName, mkUnboundName, mkKnownKeyGlobal,
49 NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv, extendNameEnvList
51 import Module ( Module, ModuleName, ModuleHiMap, SearchPath, WhereFrom,
52 mkModuleHiMaps, moduleName, mkSearchPath
55 import CmdLineOpts ( opt_D_dump_rn_trace, opt_HiMap )
56 import PrelInfo ( wiredInNames, knownKeyRdrNames )
57 import SrcLoc ( SrcLoc, mkGeneratedSrcLoc )
58 import Unique ( Unique )
59 import FiniteMap ( FiniteMap, emptyFM, listToFM, plusFM )
60 import Bag ( Bag, mapBag, emptyBag, isEmptyBag, snocBag )
64 infixr 9 `thenRn`, `thenRn_`
68 %************************************************************************
70 \subsection{Somewhat magical interface to other monads}
72 %************************************************************************
75 ioToRnM :: IO r -> RnM d (Either IOError r)
76 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
78 (\ err -> return (Left err))
80 traceRn :: SDoc -> RnM d ()
81 traceRn msg | opt_D_dump_rn_trace = putDocRn msg
82 | otherwise = returnRn ()
84 putDocRn :: SDoc -> RnM d ()
85 putDocRn msg = ioToRnM (printErrs msg) `thenRn_`
90 %************************************************************************
92 \subsection{Data types}
94 %************************************************************************
96 %===================================================
97 \subsubsection{ MONAD TYPES}
98 %===================================================
101 type RnM d r = RnDown -> d -> IO r
102 type RnMS r = RnM SDown r -- Renaming source
103 type RnMG r = RnM () r -- Getting global names etc
106 data RnDown = RnDown {
109 rn_ns :: IORef RnNameSupply,
110 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
111 rn_ifaces :: IORef Ifaces,
112 rn_hi_maps :: (SearchPath, -- For error messages
113 ModuleHiMap, -- for .hi files
114 ModuleHiMap) -- for .hi-boot files
117 -- For renaming source code
121 rn_genv :: GlobalRdrEnv,
122 -- Global envt; the fixity component gets extended
123 -- with local fixity decls
125 rn_lenv :: LocalRdrEnv, -- Local name envt
126 -- Does *not* include global name envt; may shadow it
127 -- Includes both ordinary variables and type variables;
128 -- they are kept distinct because tyvar have a different
129 -- occurrence contructor (Name.TvOcc)
130 -- We still need the unsullied global name env so that
131 -- we can look up record field names
133 rn_fixenv :: FixityEnv -- Local fixities
134 -- The global fixities are held in the
135 -- rn_ifaces field. Why? See the comments
136 -- with RnIfaces.lookupFixity
139 data RnMode = SourceMode -- Renaming source code
140 | InterfaceMode -- Renaming interface declarations.
143 %===================================================
144 \subsubsection{ ENVIRONMENTS}
145 %===================================================
148 --------------------------------
149 type GlobalRdrEnv = RdrNameEnv [Name] -- The list is because there may be name clashes
150 -- These only get reported on lookup,
151 -- not on construction
152 type LocalRdrEnv = RdrNameEnv Name
154 --------------------------------
155 type FixityEnv = NameEnv RenamedFixitySig
156 -- We keep the whole fixity sig so that we
157 -- can report line-number info when there is a duplicate
158 -- fixity declaration
160 lookupFixity :: FixityEnv -> Name -> Fixity
161 lookupFixity env name
162 = case lookupNameEnv env name of
163 Just (FixitySig _ fix _) -> fix
164 Nothing -> defaultFixity
166 --------------------------------
167 type DeprecationEnv = NameEnv DeprecTxt
171 --------------------------------
175 , FiniteMap (ModuleName, OccName) Name
176 -- Ensures that one (module,occname) pair gets one unique
177 , FiniteMap OccName Name
178 -- Ensures that one implicit parameter name gets one unique
182 --------------------------------
183 type Avails = [AvailInfo]
185 type ExportAvails = (FiniteMap ModuleName Avails,
186 -- Used to figure out "module M" export specifiers
187 -- Includes avails only from *unqualified* imports
188 -- (see 1.4 Report Section 5.1.1)
190 AvailEnv) -- Used to figure out all other export specifiers.
193 data GenAvailInfo name = Avail name -- An ordinary identifier
194 | AvailTC name -- The name of the type or class
195 [name] -- The available pieces of type/class.
196 -- NB: If the type or class is itself
197 -- to be in scope, it must be in this list.
198 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
200 -- Equality used when deciding if the interface has changed
202 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
203 type AvailInfo = GenAvailInfo Name
204 type RdrAvailInfo = GenAvailInfo OccName
207 %===================================================
208 \subsubsection{ INTERFACE FILE STUFF}
209 %===================================================
212 type ExportItem = (ModuleName, [RdrAvailInfo])
214 type ImportVersion name = (ModuleName, WhetherHasOrphans, IsBootInterface, WhatsImported name)
216 type ModVersionInfo = (Version, -- Version of the whole module
217 Version, -- Version number for all fixity decls together
218 Version) -- ...ditto all rules together
220 type WhetherHasOrphans = Bool
222 -- * an instance decl in a module other than the defn module for
223 -- one of the tycons or classes in the instance head
224 -- * a transformation rule in a module other than the one defining
225 -- the function in the head of the rule.
227 type IsBootInterface = Bool
229 data WhatsImported name = NothingAtAll -- The module is below us in the
230 -- hierarchy, but we import nothing
232 | Everything Version -- The module version
234 | Specifically Version -- Module version
235 Version -- Fixity version
236 Version -- Rules version
237 [(name,Version)] -- List guaranteed non-empty
239 -- 'Specifically' doesn't let you say "I imported f but none of the fixities in
240 -- the module. If you use anything in the module you get its fixity and rule version
241 -- So if the fixities or rules change, you'll recompile, even if you don't use either.
242 -- This is easy to implement, and it's safer: you might not have used the rules last
243 -- time round, but if someone has added a new rule you might need it this time
245 -- 'Everything' means there was a "module M" in
246 -- this module's export list, so we just have to go by M's version,
247 -- not the list of (name,version) pairs
251 pi_mod :: Module, -- Complete with package info
252 pi_vers :: Version, -- Module version number
253 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
254 pi_usages :: [ImportVersion OccName], -- Usages
255 pi_exports :: [ExportItem], -- Exports
256 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
257 pi_decls :: [(Version, RdrNameHsDecl)], -- Local definitions
258 pi_fixity :: (Version, [RdrNameFixitySig]), -- Local fixity declarations, with their version
259 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
260 pi_deprecs :: [RdrNameDeprecation] -- Deprecations
264 type RdrNamePragma = () -- Fudge for now
267 data Ifaces = Ifaces {
268 iImpModInfo :: ImportedModuleInfo,
269 -- Modules this one depends on: that is, the union
270 -- of the modules its *direct* imports depend on.
271 -- NB: The direct imports have .hi files that enumerate *all* the
272 -- dependencies (direct or not) of the imported module.
274 iDecls :: DeclsMap, -- A single, global map of Names to decls
276 iDeferred :: NameSet, -- data (not newtype) TyCons that have been slurped,
277 -- but none of their constructors have.
278 -- If this is still the case right at the end
279 -- we can get away with importing them abstractly
282 -- A single, global map of Names to fixities
283 -- See comments with RnIfaces.lookupFixity
286 -- All the names (whether "big" or "small", whether wired-in or not,
287 -- whether locally defined or not) that have been slurped in so far.
289 iVSlurp :: [(Name,Version)],
290 -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
291 -- names that have been slurped in so far, with their versions.
292 -- This is used to generate the "usage" information for this module.
293 -- Subset of the previous field.
295 iInsts :: IfaceInsts,
296 -- The as-yet un-slurped instance decls; this bag is depleted when we
297 -- slurp an instance decl so that we don't slurp the same one twice.
298 -- Each is 'gated' by the names that must be available before
299 -- this instance decl is needed.
301 iRules :: IfaceRules,
302 -- Similar to instance decls, only for rules
304 iDeprecs :: DeprecationEnv
307 type IfaceInsts = Bag GatedDecl
308 type IfaceRules = Bag GatedDecl
310 type GatedDecl = (NameSet, (Module, RdrNameHsDecl))
312 type ImportedModuleInfo
313 = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface,
314 Maybe (Module, Version, Version, Version, WhereFrom, Avails))
315 -- The three Versions are module version, fixity version, rules version
317 -- Suppose the domain element is module 'A'
319 -- The first Bool is True if A contains
320 -- 'orphan' rules or instance decls
322 -- The second Bool is true if the interface file actually
323 -- read was an .hi-boot file
325 -- Nothing => A's interface not yet read, but this module has
326 -- imported a module, B, that itself depends on A
328 -- Just xx => A's interface has been read. The Module in
329 -- the Just has the correct Dll flag
331 -- This set is used to decide whether to look for
332 -- A.hi or A.hi-boot when importing A.f.
333 -- Basically, we look for A.hi if A is in the map, and A.hi-boot
336 type DeclsMap = NameEnv (Version, AvailInfo, Bool, (Module, RdrNameHsDecl))
337 -- A DeclsMap contains a binding for each Name in the declaration
338 -- including the constructors of a type decl etc.
339 -- The Bool is True just for the 'main' Name.
343 %************************************************************************
345 \subsection{Main monad code}
347 %************************************************************************
350 initRn :: Module -> UniqSupply -> SearchPath -> SrcLoc
352 -> IO (r, Bag ErrMsg, Bag WarnMsg)
354 initRn mod us dirs loc do_rn = do
355 himaps <- mkModuleHiMaps dirs
356 names_var <- newIORef (us, builtins, emptyFM)
357 errs_var <- newIORef (emptyBag,emptyBag)
358 iface_var <- newIORef emptyIfaces
360 rn_down = RnDown { rn_loc = loc, rn_ns = names_var,
363 rn_ifaces = iface_var,
367 res <- do_rn rn_down ()
369 -- grab errors and return
370 (warns, errs) <- readIORef errs_var
372 return (res, errs, warns)
375 initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r
376 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
378 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
379 rn_fixenv = fixity_env, rn_mode = mode }
381 thing_inside rn_down s_down
383 initIfaceRnMS :: Module -> RnMS r -> RnM d r
384 initIfaceRnMS mod thing_inside
385 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
386 setModuleRn mod thing_inside
388 emptyIfaces :: Ifaces
389 emptyIfaces = Ifaces { iImpModInfo = emptyFM,
390 iDecls = emptyNameEnv,
391 iDeferred = emptyNameSet,
392 iFixes = emptyNameEnv,
393 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
394 -- Pretend that the dummy unbound name has already been
395 -- slurped. This is what's returned for an out-of-scope name,
396 -- and we don't want thereby to try to suck it in!
400 iDeprecs = emptyNameEnv
403 builtins :: FiniteMap (ModuleName,OccName) Name
404 builtins = listToFM wired_in `plusFM` listToFM known_key
406 wired_in = [ ((moduleName (nameModule name), nameOccName name), name)
407 | name <- wiredInNames ]
409 known_key = [ ((rdrNameModule rdr_name, rdrNameOcc rdr_name), mkKnownKeyGlobal rdr_name uniq)
410 | (rdr_name, uniq) <- knownKeyRdrNames ]
413 @renameSourceCode@ is used to rename stuff ``out-of-line'';
414 that is, not as part of the main renamer.
415 Sole examples: derived definitions,
416 which are only generated in the type checker.
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 :: Module
427 renameSourceCode mod 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 mkModuleHiMaps (mkSearchPath opt_HiMap) >>= \ himaps ->
434 newIORef name_supply >>= \ names_var ->
435 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
437 rn_down = RnDown { rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,
438 rn_errs = errs_var, rn_hi_maps = himaps,
440 rn_ifaces = panic "rnameSourceCode: rn_ifaces" -- Not required
442 s_down = SDown { rn_mode = InterfaceMode,
443 -- So that we can refer to PrelBase.True etc
444 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
445 rn_fixenv = emptyNameEnv }
447 m rn_down s_down >>= \ result ->
449 readIORef errs_var >>= \ (warns,errs) ->
451 (if not (isEmptyBag errs) then
452 pprTrace "Urk! renameSourceCode found errors" (display errs)
454 else if not (isEmptyBag warns) then
455 pprTrace "Note: renameSourceCode found warnings" (display warns)
463 display errs = pprBagOfErrors errs
465 {-# INLINE thenRn #-}
466 {-# INLINE thenRn_ #-}
467 {-# INLINE returnRn #-}
470 returnRn :: a -> RnM d a
471 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
472 thenRn_ :: RnM d a -> RnM d b -> RnM d b
473 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
474 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
475 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
476 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
477 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
478 sequenceRn :: [RnM d a] -> RnM d [a]
479 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
480 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
481 fixRn :: (a -> RnM d a) -> RnM d a
483 returnRn v gdown ldown = return v
484 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
485 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
486 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
487 andRn combiner m1 m2 gdown ldown
488 = m1 gdown ldown >>= \ res1 ->
489 m2 gdown ldown >>= \ res2 ->
490 return (combiner res1 res2)
492 sequenceRn [] = returnRn []
493 sequenceRn (m:ms) = m `thenRn` \ r ->
494 sequenceRn ms `thenRn` \ rs ->
497 mapRn f [] = returnRn []
499 = f x `thenRn` \ r ->
500 mapRn f xs `thenRn` \ rs ->
503 mapRn_ f [] = returnRn ()
508 foldlRn k z [] = returnRn z
509 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
512 mapAndUnzipRn f [] = returnRn ([],[])
513 mapAndUnzipRn f (x:xs)
514 = f x `thenRn` \ (r1, r2) ->
515 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
516 returnRn (r1:rs1, r2:rs2)
518 mapAndUnzip3Rn f [] = returnRn ([],[],[])
519 mapAndUnzip3Rn f (x:xs)
520 = f x `thenRn` \ (r1, r2, r3) ->
521 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
522 returnRn (r1:rs1, r2:rs2, r3:rs3)
524 mapMaybeRn f [] = returnRn []
525 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
526 mapMaybeRn f xs `thenRn` \ rs ->
528 Nothing -> returnRn rs
529 Just r -> returnRn (r:rs)
531 flatMapRn f [] = returnRn []
532 flatMapRn f (x:xs) = f x `thenRn` \ r ->
533 flatMapRn f xs `thenRn` \ rs ->
539 %************************************************************************
541 \subsection{Boring plumbing for common part}
543 %************************************************************************
547 \subsubsection{ Errors and warnings}
548 %=====================
551 failWithRn :: a -> Message -> RnM d a
552 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
553 = readIORef errs_var >>= \ (warns,errs) ->
554 writeIORef errs_var (warns, errs `snocBag` err) >>
557 err = addShortErrLocLine loc msg
559 warnWithRn :: a -> Message -> RnM d a
560 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
561 = readIORef errs_var >>= \ (warns,errs) ->
562 writeIORef errs_var (warns `snocBag` warn, errs) >>
565 warn = addShortWarnLocLine loc msg
567 addErrRn :: Message -> RnM d ()
568 addErrRn err = failWithRn () err
570 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
571 checkRn False err = addErrRn err
572 checkRn True err = returnRn ()
574 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
575 warnCheckRn False err = addWarnRn err
576 warnCheckRn True err = returnRn ()
578 addWarnRn :: Message -> RnM d ()
579 addWarnRn warn = warnWithRn () warn
581 checkErrsRn :: RnM d Bool -- True <=> no errors so far
582 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
583 = readIORef errs_var >>= \ (warns,errs) ->
584 return (isEmptyBag errs)
589 \subsubsection{ Source location}
590 %=====================
593 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
594 pushSrcLocRn loc' m down l_down
595 = m (down {rn_loc = loc'}) l_down
597 getSrcLocRn :: RnM d SrcLoc
598 getSrcLocRn down l_down
599 = return (rn_loc down)
603 \subsubsection{ Name supply}
604 %=====================
607 getNameSupplyRn :: RnM d RnNameSupply
608 getNameSupplyRn rn_down l_down
609 = readIORef (rn_ns rn_down)
611 setNameSupplyRn :: RnNameSupply -> RnM d ()
612 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
613 = writeIORef names_var names'
615 getUniqRn :: RnM d Unique
616 getUniqRn (RnDown {rn_ns = names_var}) l_down
617 = readIORef names_var >>= \ (us, cache, ipcache) ->
619 (us1,us') = splitUniqSupply us
621 writeIORef names_var (us', cache, ipcache) >>
622 return (uniqFromSupply us1)
626 \subsubsection{ Module}
627 %=====================
630 getModuleRn :: RnM d Module
631 getModuleRn (RnDown {rn_mod = mod}) l_down
634 setModuleRn :: Module -> RnM d a -> RnM d a
635 setModuleRn new_mod enclosed_thing rn_down l_down
636 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
640 %************************************************************************
642 \subsection{Plumbing for rename-source part}
644 %************************************************************************
647 \subsubsection{ RnEnv}
648 %=====================
651 getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)
652 getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})
653 = return (global_env, local_env)
655 getLocalNameEnv :: RnMS LocalRdrEnv
656 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
659 getGlobalNameEnv :: RnMS GlobalRdrEnv
660 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
663 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
664 setLocalNameEnv local_env' m rn_down l_down
665 = m rn_down (l_down {rn_lenv = local_env'})
667 getFixityEnv :: RnMS FixityEnv
668 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
671 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
672 extendFixityEnv fixes enclosed_scope
673 rn_down l_down@(SDown {rn_fixenv = fixity_env})
675 new_fixity_env = extendNameEnvList fixity_env fixes
677 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
681 \subsubsection{ Mode}
682 %=====================
685 getModeRn :: RnMS RnMode
686 getModeRn rn_down (SDown {rn_mode = mode})
689 setModeRn :: RnMode -> RnMS a -> RnMS a
690 setModeRn new_mode thing_inside rn_down l_down
691 = thing_inside rn_down (l_down {rn_mode = new_mode})
695 %************************************************************************
697 \subsection{Plumbing for rename-globals part}
699 %************************************************************************
702 getIfacesRn :: RnM d Ifaces
703 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
704 = readIORef iface_var
706 setIfacesRn :: Ifaces -> RnM d ()
707 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
708 = writeIORef iface_var ifaces
710 getHiMaps :: RnM d (SearchPath, ModuleHiMap, ModuleHiMap)
711 getHiMaps (RnDown {rn_hi_maps = himaps}) _