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, WhereFrom, moduleName )
53 import CmdLineOpts ( DynFlags, dopt_D_dump_rn_trace )
54 import PrelInfo ( wiredInNames, knownKeyRdrNames )
55 import SrcLoc ( SrcLoc, mkGeneratedSrcLoc )
56 import Unique ( Unique )
57 import FiniteMap ( FiniteMap, emptyFM, listToFM, plusFM )
58 import Bag ( Bag, mapBag, emptyBag, isEmptyBag, snocBag )
61 import CmFind ( Finder )
63 infixr 9 `thenRn`, `thenRn_`
67 %************************************************************************
69 \subsection{Somewhat magical interface to other monads}
71 %************************************************************************
74 ioToRnM :: IO r -> RnM d (Either IOError r)
75 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
77 (\ err -> return (Left err))
79 traceRn :: SDoc -> RnM d ()
81 = doptsRn dopt_D_dump_rn_trace `thenRn` \b ->
82 if b then putDocRn msg else 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
108 rn_mod :: Module, -- This module
109 rn_loc :: SrcLoc, -- Current locn
112 rn_dflags :: DynFlags,
113 rn_gst :: GlobalSymbolTable, -- Both home modules and packages,
114 -- at the moment we started compiling
117 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
118 rn_ns :: IORef NameSupply,
119 rn_ifaces :: IORef Ifaces
122 -- For renaming source code
126 rn_genv :: GlobalRdrEnv, -- Global envt
128 rn_lenv :: LocalRdrEnv, -- Local name envt
129 -- Does *not* include global name envt; may shadow it
130 -- Includes both ordinary variables and type variables;
131 -- they are kept distinct because tyvar have a different
132 -- occurrence contructor (Name.TvOcc)
133 -- We still need the unsullied global name env so that
134 -- we can look up record field names
136 rn_fixenv :: FixityEnv -- Local fixities
137 -- The global fixities are held in the
138 -- rn_ifaces field. Why? See the comments
139 -- with RnIfaces.lookupFixity
142 data RnMode = SourceMode -- Renaming source code
143 | InterfaceMode -- Renaming interface declarations.
146 %===================================================
147 \subsubsection{ ENVIRONMENTS}
148 %===================================================
151 --------------------------------
152 type GlobalRdrEnv = RdrNameEnv [Name] -- The list is because there may be name clashes
153 -- These only get reported on lookup,
154 -- not on construction
155 type LocalRdrEnv = RdrNameEnv Name
157 --------------------------------
158 type FixityEnv = NameEnv RenamedFixitySig
159 -- We keep the whole fixity sig so that we
160 -- can report line-number info when there is a duplicate
161 -- fixity declaration
163 lookupFixity :: FixityEnv -> Name -> Fixity
164 lookupFixity env name
165 = case lookupNameEnv env name of
166 Just (FixitySig _ fix _) -> fix
167 Nothing -> defaultFixity
171 type ExportAvails = (FiniteMap ModuleName Avails,
172 -- Used to figure out "module M" export specifiers
173 -- Includes avails only from *unqualified* imports
174 -- (see 1.4 Report Section 5.1.1)
176 AvailEnv) -- Used to figure out all other export specifiers.
179 %===================================================
180 \subsubsection{ INTERFACE FILE STUFF}
181 %===================================================
184 type ExportItem = (ModuleName, [RdrAvailInfo])
186 type ImportVersion name = (ModuleName, WhetherHasOrphans, IsBootInterface, WhatsImported name)
188 type ModVersionInfo = (Version, -- Version of the whole module
189 Version, -- Version number for all fixity decls together
190 Version) -- ...ditto all rules together
192 type WhetherHasOrphans = Bool
194 -- * an instance decl in a module other than the defn module for
195 -- one of the tycons or classes in the instance head
196 -- * a transformation rule in a module other than the one defining
197 -- the function in the head of the rule.
199 type IsBootInterface = Bool
201 data WhatsImported name = NothingAtAll -- The module is below us in the
202 -- hierarchy, but we import nothing
204 | Everything Version -- The module version
206 | Specifically Version -- Module version
207 Version -- Fixity version
208 Version -- Rules version
209 [(name,Version)] -- List guaranteed non-empty
211 -- 'Specifically' doesn't let you say "I imported f but none of the fixities in
212 -- the module". If you use anything in the module you get its fixity and rule version
213 -- So if the fixities or rules change, you'll recompile, even if you don't use either.
214 -- This is easy to implement, and it's safer: you might not have used the rules last
215 -- time round, but if someone has added a new rule you might need it this time
217 -- 'Everything' means there was a "module M" in
218 -- this module's export list, so we just have to go by M's version,
219 -- not the list of (name,version) pairs
223 pi_mod :: Module, -- Complete with package info
224 pi_vers :: Version, -- Module version number
225 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
226 pi_usages :: [ImportVersion OccName], -- Usages
227 pi_exports :: [ExportItem], -- Exports
228 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
229 pi_decls :: [(Version, RdrNameHsDecl)], -- Local definitions
230 pi_fixity :: (Version, [RdrNameFixitySig]), -- Local fixity declarations, with their version
231 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
232 pi_deprecs :: [RdrNameDeprecation] -- Deprecations
236 type RdrNamePragma = () -- Fudge for now
241 %************************************************************************
243 \subsection{The renamer state}
245 %************************************************************************
248 data Ifaces = Ifaces {
251 iImpModInfo :: ImportedModuleInfo,
252 -- Modules this one depends on: that is, the union
253 -- of the modules its *direct* imports depend on.
254 -- NB: The direct imports have .hi files that enumerate *all* the
255 -- dependencies (direct or not) of the imported module.
257 iDecls :: DeclsMap, -- A single, global map of Names to decls
258 -- we can get away with importing them abstractly
260 iInsts :: IfaceInsts,
261 -- The as-yet un-slurped instance decls; this bag is depleted when we
262 -- slurp an instance decl so that we don't slurp the same one twice.
263 -- Each is 'gated' by the names that must be available before
264 -- this instance decl is needed.
266 iRules :: IfaceRules,
267 -- Similar to instance decls, only for rules
269 -- SEMI-EPHEMERAL FIELDS
270 -- iFixes and iDeprecs are accumulated here while one module
271 -- is compiled, but are transferred to the package symbol table
272 -- at the end. We don't add them to the table as we encounter them
273 -- because doing so would require us to have a mutable symbol table
276 iFixes :: FixityEnv, -- A single, global map of Names to fixities
277 -- See comments with RnIfaces.lookupFixity
278 iDeprecs :: DeprecationEnv,
281 -- These fields persist during the compilation of a single module only
284 -- All the names (whether "big" or "small", whether wired-in or not,
285 -- whether locally defined or not) that have been slurped in so far.
287 iVSlurp :: [(Name,Version)]
288 -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
289 -- names that have been slurped in so far, with their versions.
290 -- This is used to generate the "usage" information for this module.
291 -- Subset of the previous field.
294 type ImportedModuleInfo
295 = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface,
296 Maybe (Module, Version, Version, Version, WhereFrom, Avails))
297 -- The three Versions are module version, fixity version, rules version
299 -- Suppose the domain element is module 'A'
301 -- The first Bool is True if A contains
302 -- 'orphan' rules or instance decls
304 -- The second Bool is true if the interface file actually
305 -- read was an .hi-boot file
307 -- Nothing => A's interface not yet read, but this module has
308 -- imported a module, B, that itself depends on A
310 -- Just xx => A's interface has been read. The Module in
311 -- the Just has the correct Dll flag
313 -- This set is used to decide whether to look for
314 -- A.hi or A.hi-boot when importing A.f.
315 -- Basically, we look for A.hi if A is in the map, and A.hi-boot
320 %************************************************************************
322 \subsection{Main monad code}
324 %************************************************************************
327 initRn :: DynFlags -> Finder -> GlobalSymbolTable
328 -> PersistentRenamerState
331 initRn dflags finder gst prs mod loc do_rn = do
332 names_var <- newIORef (prsNS pcs)
333 errs_var <- newIORef (emptyBag,emptyBag)
334 iface_var <- newIORef (initIfaces prs)
336 rn_down = RnDown { rn_mod = mod,
345 rn_ifaces = iface_var,
349 res <- do_rn rn_down ()
351 -- grab errors and return
352 (warns, errs) <- readIORef errs_var
354 return (res, errs, warns)
357 initIfaces :: PersistentRenamerState -> Ifaces
359 = Ifaces { iDecls = prsDecls prs,
360 iInsts = prsInsts prs,
361 iRules = prsRules rules,
363 iFixes = emptyNameEnv,
364 iDeprecs = emptyNameEnv,
366 iImpModInfo = emptyFM,
367 iDeferred = emptyNameSet,
368 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
369 -- Pretend that the dummy unbound name has already been
370 -- slurped. This is what's returned for an out-of-scope name,
371 -- and we don't want thereby to try to suck it in!
376 initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r
377 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
379 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
380 rn_fixenv = fixity_env, rn_mode = mode }
382 thing_inside rn_down s_down
384 initIfaceRnMS :: Module -> RnMS r -> RnM d r
385 initIfaceRnMS mod thing_inside
386 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
387 setModuleRn mod thing_inside
389 builtins :: FiniteMap (ModuleName,OccName) Name
390 builtins = listToFM wired_in `plusFM` listToFM known_key
392 wired_in = [ ((moduleName (nameModule name), nameOccName name), name)
393 | name <- wiredInNames ]
395 known_key = [ ((rdrNameModule rdr_name, rdrNameOcc rdr_name), mkKnownKeyGlobal rdr_name uniq)
396 | (rdr_name, uniq) <- knownKeyRdrNames ]
399 @renameSourceCode@ is used to rename stuff ``out-of-line'';
400 that is, not as part of the main renamer.
401 Sole examples: derived definitions,
402 which are only generated in the type checker.
404 The @NameSupply@ includes a @UniqueSupply@, so if you call it more than
405 once you must either split it, or install a fresh unique supply.
408 renameSourceCode :: DynFlags
410 -> PersistentRenamerState
414 renameSourceCode dflags mod prs m
416 -- It's not really unsafe! When renaming source code we
417 -- only do any I/O if we need to read in a fixity declaration;
418 -- and that doesn't happen in pragmas etc
420 newIORef name_supply >>= \ names_var ->
421 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
423 rn_down = RnDown { rn_dflags = dflags,
424 rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,
427 rn_ifaces = panic "rnameSourceCode: rn_ifaces" -- Not required
429 s_down = SDown { rn_mode = InterfaceMode,
430 -- So that we can refer to PrelBase.True etc
431 rn_genv = emptyRdrEnv, rn_lenv = emptyRdrEnv,
432 rn_fixenv = emptyNameEnv }
434 m rn_down s_down >>= \ result ->
436 readIORef errs_var >>= \ (warns,errs) ->
438 (if not (isEmptyBag errs) then
439 pprTrace "Urk! renameSourceCode found errors" (display errs)
441 else if not (isEmptyBag warns) then
442 pprTrace "Note: renameSourceCode found warnings" (display warns)
450 display errs = pprBagOfErrors errs
452 {-# INLINE thenRn #-}
453 {-# INLINE thenRn_ #-}
454 {-# INLINE returnRn #-}
457 returnRn :: a -> RnM d a
458 thenRn :: RnM d a -> (a -> RnM d b) -> RnM d b
459 thenRn_ :: RnM d a -> RnM d b -> RnM d b
460 andRn :: (a -> a -> a) -> RnM d a -> RnM d a -> RnM d a
461 mapRn :: (a -> RnM d b) -> [a] -> RnM d [b]
462 mapRn_ :: (a -> RnM d b) -> [a] -> RnM d ()
463 mapMaybeRn :: (a -> RnM d (Maybe b)) -> [a] -> RnM d [b]
464 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
465 sequenceRn :: [RnM d a] -> RnM d [a]
466 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
467 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
468 fixRn :: (a -> RnM d a) -> RnM d a
470 returnRn v gdown ldown = return v
471 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
472 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
473 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
474 andRn combiner m1 m2 gdown ldown
475 = m1 gdown ldown >>= \ res1 ->
476 m2 gdown ldown >>= \ res2 ->
477 return (combiner res1 res2)
479 sequenceRn [] = returnRn []
480 sequenceRn (m:ms) = m `thenRn` \ r ->
481 sequenceRn ms `thenRn` \ rs ->
484 mapRn f [] = returnRn []
486 = f x `thenRn` \ r ->
487 mapRn f xs `thenRn` \ rs ->
490 mapRn_ f [] = returnRn ()
495 foldlRn k z [] = returnRn z
496 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
499 mapAndUnzipRn f [] = returnRn ([],[])
500 mapAndUnzipRn f (x:xs)
501 = f x `thenRn` \ (r1, r2) ->
502 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
503 returnRn (r1:rs1, r2:rs2)
505 mapAndUnzip3Rn f [] = returnRn ([],[],[])
506 mapAndUnzip3Rn f (x:xs)
507 = f x `thenRn` \ (r1, r2, r3) ->
508 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
509 returnRn (r1:rs1, r2:rs2, r3:rs3)
511 mapMaybeRn f [] = returnRn []
512 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
513 mapMaybeRn f xs `thenRn` \ rs ->
515 Nothing -> returnRn rs
516 Just r -> returnRn (r:rs)
518 flatMapRn f [] = returnRn []
519 flatMapRn f (x:xs) = f x `thenRn` \ r ->
520 flatMapRn f xs `thenRn` \ rs ->
526 %************************************************************************
528 \subsection{Boring plumbing for common part}
530 %************************************************************************
534 \subsubsection{ Errors and warnings}
535 %=====================
538 failWithRn :: a -> Message -> RnM d a
539 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
540 = readIORef errs_var >>= \ (warns,errs) ->
541 writeIORef errs_var (warns, errs `snocBag` err) >>
544 err = addShortErrLocLine loc msg
546 warnWithRn :: a -> Message -> RnM d a
547 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
548 = readIORef errs_var >>= \ (warns,errs) ->
549 writeIORef errs_var (warns `snocBag` warn, errs) >>
552 warn = addShortWarnLocLine loc msg
554 addErrRn :: Message -> RnM d ()
555 addErrRn err = failWithRn () err
557 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
558 checkRn False err = addErrRn err
559 checkRn True err = returnRn ()
561 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
562 warnCheckRn False err = addWarnRn err
563 warnCheckRn True err = returnRn ()
565 addWarnRn :: Message -> RnM d ()
566 addWarnRn warn = warnWithRn () warn
568 checkErrsRn :: RnM d Bool -- True <=> no errors so far
569 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
570 = readIORef errs_var >>= \ (warns,errs) ->
571 return (isEmptyBag errs)
573 doptsRn :: (DynFlags -> Bool) -> RnM d Bool
574 doptsRn dopt (RnDown { rn_dflags = dflags}) l_down
575 = return (dopt dflags)
580 \subsubsection{ Source location}
581 %=====================
584 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
585 pushSrcLocRn loc' m down l_down
586 = m (down {rn_loc = loc'}) l_down
588 getSrcLocRn :: RnM d SrcLoc
589 getSrcLocRn down l_down
590 = return (rn_loc down)
594 \subsubsection{ Name supply}
595 %=====================
598 getNameSupplyRn :: RnM d NameSupply
599 getNameSupplyRn rn_down l_down
600 = readIORef (rn_ns rn_down)
602 setNameSupplyRn :: NameSupply -> RnM d ()
603 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
604 = writeIORef names_var names'
606 getUniqRn :: RnM d Unique
607 getUniqRn (RnDown {rn_ns = names_var}) l_down
608 = readIORef names_var >>= \ (us, cache, ipcache) ->
610 (us1,us') = splitUniqSupply us
612 writeIORef names_var (us', cache, ipcache) >>
613 return (uniqFromSupply us1)
617 \subsubsection{ Module}
618 %=====================
621 getModuleRn :: RnM d Module
622 getModuleRn (RnDown {rn_mod = mod}) l_down
625 setModuleRn :: Module -> RnM d a -> RnM d a
626 setModuleRn new_mod enclosed_thing rn_down l_down
627 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
631 %************************************************************************
633 \subsection{Plumbing for rename-source part}
635 %************************************************************************
638 \subsubsection{ RnEnv}
639 %=====================
642 getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)
643 getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})
644 = return (global_env, local_env)
646 getLocalNameEnv :: RnMS LocalRdrEnv
647 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
650 getGlobalNameEnv :: RnMS GlobalRdrEnv
651 getGlobalNameEnv rn_down (SDown {rn_genv = global_env})
654 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
655 setLocalNameEnv local_env' m rn_down l_down
656 = m rn_down (l_down {rn_lenv = local_env'})
658 getFixityEnv :: RnMS FixityEnv
659 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
662 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
663 extendFixityEnv fixes enclosed_scope
664 rn_down l_down@(SDown {rn_fixenv = fixity_env})
666 new_fixity_env = extendNameEnvList fixity_env fixes
668 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
672 \subsubsection{ Mode}
673 %=====================
676 getModeRn :: RnMS RnMode
677 getModeRn rn_down (SDown {rn_mode = mode})
680 setModeRn :: RnMode -> RnMS a -> RnMS a
681 setModeRn new_mode thing_inside rn_down l_down
682 = thing_inside rn_down (l_down {rn_mode = new_mode})
686 %************************************************************************
688 \subsection{Plumbing for rename-globals part}
690 %************************************************************************
693 getIfacesRn :: RnM d Ifaces
694 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
695 = readIORef iface_var
697 setIfacesRn :: Ifaces -> RnM d ()
698 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
699 = writeIORef iface_var ifaces