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, RenamedDeprecation )
38 import BasicTypes ( Version, defaultFixity )
39 import SrcLoc ( noSrcLoc )
40 import ErrUtils ( addShortErrLocLine, addShortWarnLocLine,
41 pprBagOfErrors, ErrMsg, WarnMsg, Message
43 import RdrName ( RdrName, dummyRdrVarName, rdrNameOcc,
44 RdrNameEnv, emptyRdrEnv, extendRdrEnv,
45 lookupRdrEnv, addListToRdrEnv, rdrEnvToList, rdrEnvElts
47 import Name ( Name, OccName, NamedThing(..), getSrcLoc,
48 isLocallyDefinedName, nameModule, nameOccName,
49 decode, mkLocalName, mkUnboundName,
50 NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv, extendNameEnv,
51 addToNameEnv_C, plusNameEnv_C, nameEnvElts,
52 elemNameEnv, addToNameEnv, addListToNameEnv
54 import Module ( Module, ModuleName, ModuleHiMap, SearchPath, WhereFrom,
55 mkModuleHiMaps, moduleName, mkSearchPath
58 import CmdLineOpts ( opt_D_dump_rn_trace, opt_HiMap )
59 import PrelInfo ( builtinNames )
60 import SrcLoc ( SrcLoc, mkGeneratedSrcLoc )
61 import Unique ( Unique, getUnique, unboundKey )
62 import FiniteMap ( FiniteMap, emptyFM, bagToFM, lookupFM, addToFM, addListToFM,
63 addListToFM_C, addToFM_C, eltsFM, fmToList
65 import Bag ( Bag, mapBag, emptyBag, isEmptyBag, snocBag )
69 infixr 9 `thenRn`, `thenRn_`
73 %************************************************************************
75 \subsection{Somewhat magical interface to other monads}
77 %************************************************************************
80 ioToRnM :: IO r -> RnM d (Either IOError r)
81 ioToRnM io rn_down g_down = (io >>= \ ok -> return (Right ok))
83 (\ err -> return (Left err))
85 traceRn :: SDoc -> RnM d ()
86 traceRn msg | opt_D_dump_rn_trace = putDocRn msg
87 | otherwise = returnRn ()
89 putDocRn :: SDoc -> RnM d ()
90 putDocRn msg = ioToRnM (printErrs msg) `thenRn_`
95 %************************************************************************
97 \subsection{Data types}
99 %************************************************************************
101 %===================================================
102 \subsubsection{ MONAD TYPES}
103 %===================================================
106 type RnM d r = RnDown -> d -> IO r
107 type RnMS r = RnM SDown r -- Renaming source
108 type RnMG r = RnM () r -- Getting global names etc
111 data RnDown = RnDown {
112 rn_mod :: ModuleName,
114 rn_ns :: IORef RnNameSupply,
115 rn_errs :: IORef (Bag WarnMsg, Bag ErrMsg),
116 rn_ifaces :: IORef Ifaces,
117 rn_hi_maps :: (SearchPath, -- For error messages
118 ModuleHiMap, -- for .hi files
119 ModuleHiMap) -- for .hi-boot files
122 -- For renaming source code
126 rn_genv :: GlobalRdrEnv,
127 -- Global envt; the fixity component gets extended
128 -- with local fixity decls
130 rn_lenv :: LocalRdrEnv, -- Local name envt
131 -- Does *not* include global name envt; may shadow it
132 -- Includes both ordinary variables and type variables;
133 -- they are kept distinct because tyvar have a different
134 -- occurrence contructor (Name.TvOcc)
135 -- We still need the unsullied global name env so that
136 -- we can look up record field names
138 rn_fixenv :: FixityEnv -- Local fixities
139 -- The global fixities are held in the
140 -- rn_ifaces field. Why? See the comments
141 -- with RnIfaces.lookupFixity
144 data RnMode = SourceMode -- Renaming source code
145 | InterfaceMode -- Renaming interface declarations.
148 %===================================================
149 \subsubsection{ ENVIRONMENTS}
150 %===================================================
153 --------------------------------
154 type GlobalRdrEnv = RdrNameEnv [Name] -- The list is because there may be name clashes
155 -- These only get reported on lookup,
156 -- not on construction
157 type LocalRdrEnv = RdrNameEnv Name
159 --------------------------------
160 type FixityEnv = NameEnv RenamedFixitySig
161 -- We keep the whole fixity sig so that we
162 -- can report line-number info when there is a duplicate
163 -- fixity declaration
165 lookupFixity :: FixityEnv -> Name -> Fixity
166 lookupFixity env name
167 = case lookupNameEnv env name of
168 Just (FixitySig _ fix _) -> fix
169 Nothing -> defaultFixity
171 --------------------------------
172 type DeprecationEnv = NameEnv DeprecTxt
176 --------------------------------
180 , FiniteMap String Int
181 -- This is used as a name supply for dictionary functions
182 -- From the inst decl we derive a string, usually by glomming together
183 -- the class and tycon name -- but it doesn't matter exactly how;
184 -- this map then gives a unique int for each inst decl with that
185 -- string. (In Haskell 98 there can only be one,
186 -- but not so in more extended versions; also class CC type T
187 -- and class C type TT might both give the string CCT
189 -- We could just use one Int for all the instance decls, but this
190 -- way the uniques change less when you add an instance decl,
191 -- hence less recompilation
193 , FiniteMap (ModuleName, OccName) Name
194 -- Ensures that one (module,occname) pair gets one unique
195 , FiniteMap OccName Name
196 -- Ensures that one implicit parameter name gets one unique
200 --------------------------------
201 type Avails = [AvailInfo]
203 type ExportAvails = (FiniteMap ModuleName Avails,
204 -- Used to figure out "module M" export specifiers
205 -- Includes avails only from *unqualified* imports
206 -- (see 1.4 Report Section 5.1.1)
208 AvailEnv) -- Used to figure out all other export specifiers.
211 data GenAvailInfo name = Avail name -- An ordinary identifier
212 | AvailTC name -- The name of the type or class
213 [name] -- The available pieces of type/class.
214 -- NB: If the type or class is itself
215 -- to be in scope, it must be in this list.
216 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
218 -- Equality used when deciding if the interface has changed
220 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
221 type AvailInfo = GenAvailInfo Name
222 type RdrAvailInfo = GenAvailInfo OccName
225 %===================================================
226 \subsubsection{ INTERFACE FILE STUFF}
227 %===================================================
230 type ExportItem = (ModuleName, [RdrAvailInfo])
232 type ImportVersion name = (ModuleName, WhetherHasOrphans, IsBootInterface, WhatsImported name)
234 type ModVersionInfo = (Version, -- Version of the whole module
235 Version, -- Version number for all fixity decls together
236 Version) -- ...ditto all rules together
238 type WhetherHasOrphans = Bool
240 -- * an instance decl in a module other than the defn module for
241 -- one of the tycons or classes in the instance head
242 -- * a transformation rule in a module other than the one defining
243 -- the function in the head of the rule.
245 type IsBootInterface = Bool
247 data WhatsImported name = NothingAtAll -- The module is below us in the
248 -- hierarchy, but we import nothing
250 | Everything Version -- The module version
252 | Specifically Version -- Module version
253 Version -- Fixity version
254 Version -- Rules version
255 [(name,Version)] -- List guaranteed non-empty
257 -- 'Specifically' doesn't let you say "I imported f but none of the fixities in
258 -- the module. If you use anything in the module you get its fixity and rule version
259 -- So if the fixities or rules change, you'll recompile, even if you don't use either.
260 -- This is easy to implement, and it's safer: you might not have used the rules last
261 -- time round, but if someone has added a new rule you might need it this time
263 -- 'Everything' means there was a "module M" in
264 -- this module's export list, so we just have to go by M's version,
265 -- not the list of (name,version) pairs
269 pi_mod :: Module, -- Complete with package info
270 pi_vers :: Version, -- Module version number
271 pi_orphan :: WhetherHasOrphans, -- Whether this module has orphans
272 pi_usages :: [ImportVersion OccName], -- Usages
273 pi_exports :: [ExportItem], -- Exports
274 pi_insts :: [RdrNameInstDecl], -- Local instance declarations
275 pi_decls :: [(Version, RdrNameHsDecl)], -- Local definitions
276 pi_fixity :: (Version, [RdrNameFixitySig]), -- Local fixity declarations, with their version
277 pi_rules :: (Version, [RdrNameRuleDecl]), -- Rules, with their version
278 pi_deprecs :: [RdrNameDeprecation] -- Deprecations
282 type RdrNamePragma = () -- Fudge for now
285 data Ifaces = Ifaces {
286 iImpModInfo :: ImportedModuleInfo,
287 -- Modules this one depends on: that is, the union
288 -- of the modules its *direct* imports depend on.
289 -- NB: The direct imports have .hi files that enumerate *all* the
290 -- dependencies (direct or not) of the imported module.
292 iDecls :: DeclsMap, -- A single, global map of Names to decls
294 iDeferred :: NameSet, -- data (not newtype) TyCons that have been slurped,
295 -- but none of their constructors have.
296 -- If this is still the case right at the end
297 -- we can get away with importing them abstractly
300 -- A single, global map of Names to fixities
301 -- See comments with RnIfaces.lookupFixity
304 -- All the names (whether "big" or "small", whether wired-in or not,
305 -- whether locally defined or not) that have been slurped in so far.
307 iVSlurp :: [(Name,Version)],
308 -- All the (a) non-wired-in (b) "big" (c) non-locally-defined
309 -- names that have been slurped in so far, with their versions.
310 -- This is used to generate the "usage" information for this module.
311 -- Subset of the previous field.
313 iInsts :: IfaceInsts,
314 -- The as-yet un-slurped instance decls; this bag is depleted when we
315 -- slurp an instance decl so that we don't slurp the same one twice.
316 -- Each is 'gated' by the names that must be available before
317 -- this instance decl is needed.
319 iRules :: IfaceRules,
320 -- Similar to instance decls, only for rules
322 iDeprecs :: DeprecationEnv
325 type IfaceInsts = Bag GatedDecl
326 type IfaceRules = Bag GatedDecl
328 type GatedDecl = (NameSet, (Module, RdrNameHsDecl))
330 type ImportedModuleInfo
331 = FiniteMap ModuleName (WhetherHasOrphans, IsBootInterface,
332 Maybe (Module, Version, Version, Version, WhereFrom, Avails))
333 -- The three Versions are module version, fixity version, rules version
335 -- Suppose the domain element is module 'A'
337 -- The first Bool is True if A contains
338 -- 'orphan' rules or instance decls
340 -- The second Bool is true if the interface file actually
341 -- read was an .hi-boot file
343 -- Nothing => A's interface not yet read, but this module has
344 -- imported a module, B, that itself depends on A
346 -- Just xx => A's interface has been read. The Module in
347 -- the Just has the correct Dll flag
349 -- This set is used to decide whether to look for
350 -- A.hi or A.hi-boot when importing A.f.
351 -- Basically, we look for A.hi if A is in the map, and A.hi-boot
354 type DeclsMap = NameEnv (Version, AvailInfo, Bool, (Module, RdrNameHsDecl))
355 -- A DeclsMap contains a binding for each Name in the declaration
356 -- including the constructors of a type decl etc.
357 -- The Bool is True just for the 'main' Name.
361 %************************************************************************
363 \subsection{Main monad code}
365 %************************************************************************
368 initRn :: ModuleName -> UniqSupply -> SearchPath -> SrcLoc
370 -> IO (r, Bag ErrMsg, Bag WarnMsg)
372 initRn mod us dirs loc do_rn = do
373 himaps <- mkModuleHiMaps dirs
374 names_var <- newIORef (us, emptyFM, builtins, emptyFM)
375 errs_var <- newIORef (emptyBag,emptyBag)
376 iface_var <- newIORef emptyIfaces
378 rn_down = RnDown { rn_loc = loc, rn_ns = names_var,
381 rn_ifaces = iface_var,
385 res <- do_rn rn_down ()
387 -- grab errors and return
388 (warns, errs) <- readIORef errs_var
390 return (res, errs, warns)
393 initRnMS :: GlobalRdrEnv -> FixityEnv -> RnMode -> RnMS r -> RnM d r
394 initRnMS rn_env fixity_env mode thing_inside rn_down g_down
396 s_down = SDown { rn_genv = rn_env, rn_lenv = emptyRdrEnv,
397 rn_fixenv = fixity_env, rn_mode = mode }
399 thing_inside rn_down s_down
401 initIfaceRnMS :: Module -> RnMS r -> RnM d r
402 initIfaceRnMS mod thing_inside
403 = initRnMS emptyRdrEnv emptyNameEnv InterfaceMode $
404 setModuleRn (moduleName mod) thing_inside
406 emptyIfaces :: Ifaces
407 emptyIfaces = Ifaces { iImpModInfo = emptyFM,
408 iDecls = emptyNameEnv,
409 iDeferred = emptyNameSet,
410 iFixes = emptyNameEnv,
411 iSlurp = unitNameSet (mkUnboundName dummyRdrVarName),
412 -- Pretend that the dummy unbound name has already been
413 -- slurped. This is what's returned for an out-of-scope name,
414 -- and we don't want thereby to try to suck it in!
418 iDeprecs = emptyNameEnv
421 builtins :: FiniteMap (ModuleName,OccName) Name
424 mapBag (\ name -> ((moduleName (nameModule name), nameOccName name), name))
428 @renameSourceCode@ is used to rename stuff ``out-of-line'';
429 that is, not as part of the main renamer.
430 Sole examples: derived definitions,
431 which are only generated in the type checker.
433 The @RnNameSupply@ includes a @UniqueSupply@, so if you call it more than
434 once you must either split it, or install a fresh unique supply.
437 renameSourceCode :: ModuleName
442 renameSourceCode mod_name name_supply m
444 -- It's not really unsafe! When renaming source code we
445 -- only do any I/O if we need to read in a fixity declaration;
446 -- and that doesn't happen in pragmas etc
448 mkModuleHiMaps (mkSearchPath opt_HiMap) >>= \ himaps ->
449 newIORef name_supply >>= \ names_var ->
450 newIORef (emptyBag,emptyBag) >>= \ errs_var ->
452 rn_down = RnDown { rn_loc = mkGeneratedSrcLoc, rn_ns = names_var,
453 rn_errs = errs_var, rn_hi_maps = himaps,
455 rn_ifaces = panic "rnameSourceCode: rn_ifaces" -- Not required
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 flatMapRn :: (a -> RnM d [b]) -> [a] -> RnM d [b]
493 sequenceRn :: [RnM d a] -> RnM d [a]
494 foldlRn :: (b -> a -> RnM d b) -> b -> [a] -> RnM d b
495 mapAndUnzipRn :: (a -> RnM d (b,c)) -> [a] -> RnM d ([b],[c])
496 fixRn :: (a -> RnM d a) -> RnM d a
498 returnRn v gdown ldown = return v
499 thenRn m k gdown ldown = m gdown ldown >>= \ r -> k r gdown ldown
500 thenRn_ m k gdown ldown = m gdown ldown >> k gdown ldown
501 fixRn m gdown ldown = fixIO (\r -> m r gdown ldown)
502 andRn combiner m1 m2 gdown ldown
503 = m1 gdown ldown >>= \ res1 ->
504 m2 gdown ldown >>= \ res2 ->
505 return (combiner res1 res2)
507 sequenceRn [] = returnRn []
508 sequenceRn (m:ms) = m `thenRn` \ r ->
509 sequenceRn ms `thenRn` \ rs ->
512 mapRn f [] = returnRn []
514 = f x `thenRn` \ r ->
515 mapRn f xs `thenRn` \ rs ->
518 mapRn_ f [] = returnRn ()
523 foldlRn k z [] = returnRn z
524 foldlRn k z (x:xs) = k z x `thenRn` \ z' ->
527 mapAndUnzipRn f [] = returnRn ([],[])
528 mapAndUnzipRn f (x:xs)
529 = f x `thenRn` \ (r1, r2) ->
530 mapAndUnzipRn f xs `thenRn` \ (rs1, rs2) ->
531 returnRn (r1:rs1, r2:rs2)
533 mapAndUnzip3Rn f [] = returnRn ([],[],[])
534 mapAndUnzip3Rn f (x:xs)
535 = f x `thenRn` \ (r1, r2, r3) ->
536 mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
537 returnRn (r1:rs1, r2:rs2, r3:rs3)
539 mapMaybeRn f [] = returnRn []
540 mapMaybeRn f (x:xs) = f x `thenRn` \ maybe_r ->
541 mapMaybeRn f xs `thenRn` \ rs ->
543 Nothing -> returnRn rs
544 Just r -> returnRn (r:rs)
546 flatMapRn f [] = returnRn []
547 flatMapRn f (x:xs) = f x `thenRn` \ r ->
548 flatMapRn f xs `thenRn` \ rs ->
554 %************************************************************************
556 \subsection{Boring plumbing for common part}
558 %************************************************************************
562 \subsubsection{ Errors and warnings}
563 %=====================
566 failWithRn :: a -> Message -> RnM d a
567 failWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
568 = readIORef errs_var >>= \ (warns,errs) ->
569 writeIORef errs_var (warns, errs `snocBag` err) >>
572 err = addShortErrLocLine loc msg
574 warnWithRn :: a -> Message -> RnM d a
575 warnWithRn res msg (RnDown {rn_errs = errs_var, rn_loc = loc}) l_down
576 = readIORef errs_var >>= \ (warns,errs) ->
577 writeIORef errs_var (warns `snocBag` warn, errs) >>
580 warn = addShortWarnLocLine loc msg
582 addErrRn :: Message -> RnM d ()
583 addErrRn err = failWithRn () err
585 checkRn :: Bool -> Message -> RnM d () -- Check that a condition is true
586 checkRn False err = addErrRn err
587 checkRn True err = returnRn ()
589 warnCheckRn :: Bool -> Message -> RnM d () -- Check that a condition is true
590 warnCheckRn False err = addWarnRn err
591 warnCheckRn True err = returnRn ()
593 addWarnRn :: Message -> RnM d ()
594 addWarnRn warn = warnWithRn () warn
596 checkErrsRn :: RnM d Bool -- True <=> no errors so far
597 checkErrsRn (RnDown {rn_errs = errs_var}) l_down
598 = readIORef errs_var >>= \ (warns,errs) ->
599 return (isEmptyBag errs)
604 \subsubsection{ Source location}
605 %=====================
608 pushSrcLocRn :: SrcLoc -> RnM d a -> RnM d a
609 pushSrcLocRn loc' m down l_down
610 = m (down {rn_loc = loc'}) l_down
612 getSrcLocRn :: RnM d SrcLoc
613 getSrcLocRn down l_down
614 = return (rn_loc down)
618 \subsubsection{ Name supply}
619 %=====================
622 getNameSupplyRn :: RnM d RnNameSupply
623 getNameSupplyRn rn_down l_down
624 = readIORef (rn_ns rn_down)
626 setNameSupplyRn :: RnNameSupply -> RnM d ()
627 setNameSupplyRn names' (RnDown {rn_ns = names_var}) l_down
628 = writeIORef names_var names'
630 -- See comments with RnNameSupply above.
631 newInstUniq :: String -> RnM d Int
632 newInstUniq key (RnDown {rn_ns = names_var}) l_down
633 = readIORef names_var >>= \ (us, mapInst, cache, ipcache) ->
635 uniq = case lookupFM mapInst key of
638 mapInst' = addToFM mapInst key uniq
640 writeIORef names_var (us, mapInst', cache, ipcache) >>
643 getUniqRn :: RnM d Unique
644 getUniqRn (RnDown {rn_ns = names_var}) l_down
645 = readIORef names_var >>= \ (us, mapInst, cache, ipcache) ->
647 (us1,us') = splitUniqSupply us
649 writeIORef names_var (us', mapInst, cache, ipcache) >>
650 return (uniqFromSupply us1)
654 \subsubsection{ Module}
655 %=====================
658 getModuleRn :: RnM d ModuleName
659 getModuleRn (RnDown {rn_mod = mod_name}) l_down
662 setModuleRn :: ModuleName -> RnM d a -> RnM d a
663 setModuleRn new_mod enclosed_thing rn_down l_down
664 = enclosed_thing (rn_down {rn_mod = new_mod}) l_down
668 %************************************************************************
670 \subsection{Plumbing for rename-source part}
672 %************************************************************************
675 \subsubsection{ RnEnv}
676 %=====================
679 getNameEnvs :: RnMS (GlobalRdrEnv, LocalRdrEnv)
680 getNameEnvs rn_down (SDown {rn_genv = global_env, rn_lenv = local_env})
681 = return (global_env, local_env)
683 getLocalNameEnv :: RnMS LocalRdrEnv
684 getLocalNameEnv rn_down (SDown {rn_lenv = local_env})
687 setLocalNameEnv :: LocalRdrEnv -> RnMS a -> RnMS a
688 setLocalNameEnv local_env' m rn_down l_down
689 = m rn_down (l_down {rn_lenv = local_env'})
691 getFixityEnv :: RnMS FixityEnv
692 getFixityEnv rn_down (SDown {rn_fixenv = fixity_env})
695 extendFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
696 extendFixityEnv fixes enclosed_scope
697 rn_down l_down@(SDown {rn_fixenv = fixity_env})
699 new_fixity_env = extendNameEnv fixity_env fixes
701 enclosed_scope rn_down (l_down {rn_fixenv = new_fixity_env})
705 \subsubsection{ Mode}
706 %=====================
709 getModeRn :: RnMS RnMode
710 getModeRn rn_down (SDown {rn_mode = mode})
713 setModeRn :: RnMode -> RnMS a -> RnMS a
714 setModeRn new_mode thing_inside rn_down l_down
715 = thing_inside rn_down (l_down {rn_mode = new_mode})
719 %************************************************************************
721 \subsection{Plumbing for rename-globals part}
723 %************************************************************************
726 getIfacesRn :: RnM d Ifaces
727 getIfacesRn (RnDown {rn_ifaces = iface_var}) _
728 = readIORef iface_var
730 setIfacesRn :: Ifaces -> RnM d ()
731 setIfacesRn ifaces (RnDown {rn_ifaces = iface_var}) _
732 = writeIORef iface_var ifaces
734 getHiMaps :: RnM d (SearchPath, ModuleHiMap, ModuleHiMap)
735 getHiMaps (RnDown {rn_hi_maps = himaps}) _