2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[RnIfaces]{Cacheing and Renaming of Interfaces}
7 #include "HsVersions.h"
12 getSpecialInstModules, getDeferredDataDecls,
13 importDecl, recordSlurp,
14 getImportVersions, getSlurpedNames, getRnStats,
23 #if __GLASGOW_HASKELL__ >= 202
28 import CmdLineOpts ( opt_PruneTyDecls, opt_PruneInstDecls, opt_PprUserLength )
29 import HsSyn ( HsDecl(..), TyDecl(..), ClassDecl(..), HsTyVar, HsExpr, Sig(..), HsType(..),
30 HsBinds(..), MonoBinds, DefaultDecl, ConDecl(..), ConDetails(..), BangType, IfaceSig(..),
31 FixityDecl(..), Fixity, Fake, InPat, InstDecl(..), HsIdInfo,
34 import HsPragmas ( noGenPragmas )
35 import BasicTypes ( SYN_IE(Version), NewOrData(..) )
36 import RdrHsSyn ( SYN_IE(RdrNameHsDecl), SYN_IE(RdrNameInstDecl), SYN_IE(RdrNameTyDecl),
39 import RnEnv ( newGlobalName, lookupRn, addImplicitOccsRn,
40 availName, availNames, addAvailToNameSet, pprAvail
42 import RnSource ( rnHsSigType )
44 import RnHsSyn ( SYN_IE(RenamedHsDecl) )
45 import ParseIface ( parseIface )
47 import ErrUtils ( SYN_IE(Error), SYN_IE(Warning) )
48 import FiniteMap ( FiniteMap, sizeFM, emptyFM, unitFM, delFromFM,
49 lookupFM, addToFM, addToFM_C, addListToFM,
52 import Name ( Name {-instance NamedThing-}, Provenance, OccName(..),
53 nameModule, occNameString, moduleString, pprModule, isLocallyDefined,
54 NameSet(..), emptyNameSet, unionNameSets, nameSetToList,
55 minusNameSet, mkNameSet, elemNameSet, nameUnique, addOneToNameSet,
56 isWiredInName, maybeWiredInTyConName, maybeWiredInIdName,
59 import Id ( GenId, Id(..), idType, dataConTyCon, isAlgCon )
60 import TyCon ( TyCon, tyConDataCons, isSynTyCon, getSynTyConDefn )
61 import Type ( namesOfType )
62 import TyVar ( GenTyVar )
63 import SrcLoc ( mkIfaceSrcLoc, SrcLoc )
64 import PrelMods ( gHC__ )
65 import PrelInfo ( cCallishTyKeys )
67 import Maybes ( MaybeErr(..), expectJust, maybeToBool )
68 import ListSetOps ( unionLists )
70 import Outputable ( PprStyle(..) )
71 import Unique ( Unique )
72 import Util ( pprPanic, pprTrace, Ord3(..) )
73 import StringBuffer ( StringBuffer, hGetStringBuffer, freeStringBuffer )
75 #if __GLASGOW_HASKELL__ >= 202
82 %*********************************************************
84 \subsection{Statistics}
86 %*********************************************************
89 getRnStats :: [RenamedHsDecl] -> RnMG Doc
91 = getIfacesRn `thenRn` \ ifaces ->
93 Ifaces this_mod mod_vers_map export_envs decls_fm all_names imp_names (unslurped_insts,_) deferred_data_decls inst_mods = ifaces
94 n_mods = sizeFM mod_vers_map
96 decls_imported = filter is_imported_decl all_decls
97 decls_read = [decl | (name, (_, avail, decl)) <- fmToList decls_fm,
98 name == availName avail,
99 -- Data, newtype, and class decls are in the decls_fm
100 -- under multiple names; the tycon/class, and each
101 -- constructor/class op too.
102 not (isLocallyDefined name)
105 (cd_rd, dd_rd, add_rd, nd_rd, and_rd, sd_rd, vd_rd, _) = count_decls decls_read
106 (cd_sp, dd_sp, add_sp, nd_sp, and_sp, sd_sp, vd_sp, id_sp) = count_decls decls_imported
108 inst_decls_unslurped = length (bagToList unslurped_insts)
109 inst_decls_read = id_sp + inst_decls_unslurped
112 [int n_mods <> text " interfaces read",
113 hsep [int cd_sp, text "class decls imported, out of",
114 int cd_rd, text "read"],
115 hsep [int dd_sp, text "data decls imported (of which", int add_sp, text "abstractly), out of",
116 int dd_rd, text "read"],
117 hsep [int nd_sp, text "newtype decls imported (of which", int and_sp, text "abstractly), out of",
118 int nd_rd, text "read"],
119 hsep [int sd_sp, text "type synonym decls imported, out of",
120 int sd_rd, text "read"],
121 hsep [int vd_sp, text "value signatures imported, out of",
122 int vd_rd, text "read"],
123 hsep [int id_sp, text "instance decls imported, out of",
124 int inst_decls_read, text "read"]
127 returnRn (hcat [text "Renamer stats: ", stats])
129 is_imported_decl (DefD _) = False
130 is_imported_decl (ValD _) = False
131 is_imported_decl decl = not (isLocallyDefined (hsDeclName decl))
134 = -- pprTrace "count_decls" (ppr PprDebug decls
139 -- ppr PprDebug imported_decls
142 data_decls, abstract_data_decls,
143 newtype_decls, abstract_newtype_decls,
148 class_decls = length [() | ClD _ <- decls]
149 data_decls = length [() | TyD (TyData DataType _ _ _ _ _ _ _) <- decls]
150 newtype_decls = length [() | TyD (TyData NewType _ _ _ _ _ _ _) <- decls]
151 abstract_data_decls = length [() | TyD (TyData DataType _ _ _ [] _ _ _) <- decls]
152 abstract_newtype_decls = length [() | TyD (TyData NewType _ _ _ [] _ _ _) <- decls]
153 syn_decls = length [() | TyD (TySynonym _ _ _ _) <- decls]
154 val_decls = length [() | SigD _ <- decls]
155 inst_decls = length [() | InstD _ <- decls]
159 %*********************************************************
161 \subsection{Loading a new interface file}
163 %*********************************************************
166 loadInterface :: Doc -> Module -> RnMG Ifaces
167 loadInterface doc_str load_mod
168 = getIfacesRn `thenRn` \ ifaces ->
170 Ifaces this_mod mod_vers_map export_envs decls all_names imp_names (insts, tycls_names) deferred_data_decls inst_mods = ifaces
172 -- CHECK WHETHER WE HAVE IT ALREADY
173 if maybeToBool (lookupFM export_envs load_mod)
175 returnRn ifaces -- Already in the cache; don't re-read it
178 -- READ THE MODULE IN
179 findAndReadIface doc_str load_mod `thenRn` \ read_result ->
180 case read_result of {
181 -- Check for not found
182 Nothing -> -- Not found, so add an empty export env to the Ifaces map
183 -- so that we don't look again
185 new_export_envs = addToFM export_envs load_mod ([],[])
186 new_ifaces = Ifaces this_mod mod_vers_map
188 decls all_names imp_names (insts, tycls_names) deferred_data_decls inst_mods
190 setIfacesRn new_ifaces `thenRn_`
191 failWithRn new_ifaces (noIfaceErr load_mod) ;
194 Just (ParsedIface _ mod_vers usages exports rd_inst_mods fixs rd_decls rd_insts) ->
196 -- LOAD IT INTO Ifaces
197 mapRn loadExport exports `thenRn` \ avails_s ->
198 foldlRn (loadDecl load_mod) decls rd_decls `thenRn` \ new_decls ->
199 foldlRn (loadInstDecl load_mod) insts rd_insts `thenRn` \ new_insts ->
201 export_env = (concat avails_s, fixs)
203 -- Exclude this module from the "special-inst" modules
204 new_inst_mods = inst_mods `unionLists` (filter (/= this_mod) rd_inst_mods)
206 new_ifaces = Ifaces this_mod
207 (addToFM mod_vers_map load_mod mod_vers)
208 (addToFM export_envs load_mod export_env)
211 (new_insts, tycls_names)
215 setIfacesRn new_ifaces `thenRn_`
219 loadExport :: ExportItem -> RnMG [AvailInfo]
220 loadExport (mod, entities)
221 = mapRn load_entity entities
223 new_name occ = newGlobalName mod occ
225 -- The communcation between this little code fragment and the "entity" rule
226 -- in ParseIface.y is a bit gruesome. The idea is that things which are
227 -- destined to be AvailTCs show up as (occ, [non-empty-list]), whereas
228 -- things destined to be Avails show up as (occ, [])
230 load_entity (occ, occs)
231 = new_name occ `thenRn` \ name ->
233 returnRn (Avail name)
235 mapRn new_name occs `thenRn` \ names ->
236 returnRn (AvailTC name names)
238 loadDecl :: Module -> DeclsMap
239 -> (Version, RdrNameHsDecl)
241 loadDecl mod decls_map (version, decl)
242 = getDeclBinders new_implicit_name decl `thenRn` \ avail ->
243 returnRn (addListToFM decls_map
244 [(name,(version,avail,decl)) | name <- availNames avail]
247 new_implicit_name rdr_name loc = newGlobalName mod (rdrNameOcc rdr_name)
249 loadInstDecl :: Module
252 -> RnMG (Bag IfaceInst)
253 loadInstDecl mod_name insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
255 -- Find out what type constructors and classes are "gates" for the
256 -- instance declaration. If all these "gates" are slurped in then
257 -- we should slurp the instance decl too.
259 -- We *don't* want to count names in the context part as gates, though.
261 -- instance Foo a => Baz (T a) where ...
263 -- Here the gates are Baz and T, but *not* Foo.
265 munged_inst_ty = case inst_ty of
266 HsForAllTy tvs cxt ty -> HsForAllTy tvs [] ty
267 HsPreForAllTy cxt ty -> HsPreForAllTy [] ty
270 -- We find the gates by renaming the instance type with in a
271 -- and returning the occurrence pool.
272 initRnMS emptyRnEnv mod_name (InterfaceMode Compulsory) (
273 findOccurrencesRn (rnHsSigType (\sty -> text "an instance decl") munged_inst_ty)
274 ) `thenRn` \ gate_names ->
275 returnRn (((mod_name, decl), gate_names) `consBag` insts)
279 %********************************************************
281 \subsection{Loading usage information}
283 %********************************************************
286 checkUpToDate :: Module -> RnMG Bool -- True <=> no need to recompile
287 checkUpToDate mod_name
288 = findAndReadIface doc_str mod_name `thenRn` \ read_result ->
290 Nothing -> -- Old interface file not found, so we'd better bail out
291 traceRn (sep [ptext SLIT("Didnt find old iface"),
292 pprModule PprDebug mod_name]) `thenRn_`
295 Just (ParsedIface _ _ usages _ _ _ _ _)
296 -> -- Found it, so now check it
299 -- Only look in current directory, with suffix .hi
300 doc_str = sep [ptext SLIT("Need usage info from"), pprModule PprDebug mod_name]
302 checkModUsage [] = returnRn True -- Yes! Everything is up to date!
304 checkModUsage ((mod, old_mod_vers, old_local_vers) : rest)
305 = loadInterface doc_str mod `thenRn` \ ifaces ->
307 Ifaces _ mod_vers _ decls _ _ _ _ _ = ifaces
308 maybe_new_mod_vers = lookupFM mod_vers mod
309 Just new_mod_vers = maybe_new_mod_vers
311 -- If we can't find a version number for the old module then
312 -- bail out saying things aren't up to date
313 if not (maybeToBool maybe_new_mod_vers) then
317 -- If the module version hasn't changed, just move on
318 if new_mod_vers == old_mod_vers then
319 traceRn (sep [ptext SLIT("Module version unchanged:"), pprModule PprDebug mod]) `thenRn_`
322 traceRn (sep [ptext SLIT("Module version has changed:"), pprModule PprDebug mod]) `thenRn_`
324 -- New module version, so check entities inside
325 checkEntityUsage mod decls old_local_vers `thenRn` \ up_to_date ->
327 traceRn (ptext SLIT("...but the bits I use haven't.")) `thenRn_`
328 checkModUsage rest -- This one's ok, so check the rest
330 returnRn False -- This one failed, so just bail out now
332 doc_str = sep [ptext SLIT("need version info for"), pprModule PprDebug mod]
335 checkEntityUsage mod decls []
336 = returnRn True -- Yes! All up to date!
338 checkEntityUsage mod decls ((occ_name,old_vers) : rest)
339 = newGlobalName mod occ_name `thenRn` \ name ->
340 case lookupFM decls name of
342 Nothing -> -- We used it before, but it ain't there now
343 traceRn (sep [ptext SLIT("...and this no longer exported:"), ppr PprDebug name]) `thenRn_`
346 Just (new_vers,_,_) -- It's there, but is it up to date?
347 | new_vers == old_vers
348 -- Up to date, so check the rest
349 -> checkEntityUsage mod decls rest
352 -- Out of date, so bale out
353 -> traceRn (sep [ptext SLIT("...and this is out of date:"), ppr PprDebug name]) `thenRn_`
358 %*********************************************************
360 \subsection{Getting in a declaration}
362 %*********************************************************
365 importDecl :: Name -> Necessity -> RnMG (Maybe RdrNameHsDecl)
366 -- Returns Nothing for a wired-in or already-slurped decl
368 importDecl name necessity
369 = checkSlurped name `thenRn` \ already_slurped ->
370 if already_slurped then
371 traceRn (sep [text "Already slurped:", ppr PprDebug name]) `thenRn_`
372 returnRn Nothing -- Already dealt with
374 if isWiredInName name then
375 getWiredInDecl name necessity
377 getIfacesRn `thenRn` \ ifaces ->
379 Ifaces this_mod _ _ _ _ _ _ _ _ = ifaces
380 mod = nameModule name
382 if mod == this_mod then -- Don't bring in decls from
383 pprTrace "importDecl wierdness:" (ppr PprDebug name) $
384 returnRn Nothing -- the renamed module's own interface file
387 getNonWiredInDecl name necessity
391 getNonWiredInDecl :: Name -> Necessity -> RnMG (Maybe RdrNameHsDecl)
392 getNonWiredInDecl needed_name necessity
393 = traceRn doc_str `thenRn_`
394 loadInterface doc_str mod `thenRn` \ (Ifaces _ _ _ decls _ _ _ _ _) ->
395 case lookupFM decls needed_name of
397 -- Special case for data/newtype type declarations
398 Just (version, avail, TyD ty_decl) | is_data_or_newtype ty_decl
399 -> getNonWiredDataDecl needed_name version avail ty_decl `thenRn` \ (avail', maybe_decl) ->
400 recordSlurp (Just version) necessity avail' `thenRn_`
403 Just (version,avail,decl)
404 -> recordSlurp (Just version) necessity avail `thenRn_`
407 Nothing -> -- Can happen legitimately for "Optional" occurrences
409 Optional -> addWarnRn (getDeclWarn needed_name);
410 other -> addErrRn (getDeclErr needed_name)
414 doc_str = sep [ptext SLIT("Need decl for"), ppr PprDebug needed_name]
415 mod = nameModule needed_name
417 is_data_or_newtype (TyData _ _ _ _ _ _ _ _) = True
418 is_data_or_newtype other = False
421 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
422 It behaves exactly as if the wired in decl were actually in an interface file.
425 * if the wired-in name is a data type constructor or a data constructor,
426 it brings in the type constructor and all the data constructors; and
427 marks as "occurrences" any free vars of the data con.
429 * similarly for synonum type constructor
431 * if the wired-in name is another wired-in Id, it marks as "occurrences"
432 the free vars of the Id's type.
434 * it loads the interface file for the wired-in thing for the
435 sole purpose of making sure that its instance declarations are available
437 All this is necessary so that we know all types that are "in play", so
438 that we know just what instances to bring into scope.
441 getWiredInDecl name necessity
442 = initRnMS emptyRnEnv mod_name (InterfaceMode necessity)
443 get_wired `thenRn` \ avail ->
444 recordSlurp Nothing necessity avail `thenRn_`
446 -- Force in the home module in case it has instance decls for
447 -- the thing we are interested in.
449 -- Mini hack 1: no point for non-tycons/class; and if we
450 -- do this we find PrelNum trying to import PackedString,
451 -- because PrelBase's .hi file mentions PackedString.unpackString
452 -- But PackedString.hi isn't built by that point!
454 -- Mini hack 2; GHC is guaranteed not to have
455 -- instance decls, so it's a waste of time to read it
457 -- NB: We *must* look at the availName of the slurped avail,
458 -- not the name passed to getWiredInDecl! Why? Because if a data constructor
459 -- or class op is passed to getWiredInDecl we'll pull in the whole data/class
460 -- decl, and recordSlurp will record that fact. But since the data constructor
461 -- isn't a tycon/class we won't force in the home module. And even if the
462 -- type constructor/class comes along later, loadDecl will say that it's already
463 -- been slurped, so getWiredInDecl won't even be called. Pretty obscure bug, this was.
465 main_name = availName avail
466 main_is_tc = case avail of { AvailTC _ _ -> True; Avail _ -> False }
467 mod = nameModule main_name
468 doc_str = sep [ptext SLIT("Need home module for wired in thing"), ppr PprDebug name]
470 (if not main_is_tc || mod == gHC__ then
473 loadInterface doc_str mod `thenRn_`
477 returnRn Nothing -- No declaration to process further
480 get_wired | is_tycon -- ... a type constructor
481 = get_wired_tycon the_tycon
483 | (isAlgCon the_id) -- ... a wired-in data constructor
484 = get_wired_tycon (dataConTyCon the_id)
486 | otherwise -- ... a wired-in non data-constructor
487 = get_wired_id the_id
489 mod_name = nameModule name
490 maybe_wired_in_tycon = maybeWiredInTyConName name
491 is_tycon = maybeToBool maybe_wired_in_tycon
492 maybe_wired_in_id = maybeWiredInIdName name
493 Just the_tycon = maybe_wired_in_tycon
494 Just the_id = maybe_wired_in_id
498 = addImplicitOccsRn (nameSetToList id_mentioned) `thenRn_`
499 returnRn (Avail (getName id))
501 id_mentioned = namesOfType (idType id)
503 get_wired_tycon tycon
505 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
506 returnRn (AvailTC tc_name [tc_name])
508 tc_name = getName tycon
509 (tyvars,ty) = getSynTyConDefn tycon
510 mentioned = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
512 get_wired_tycon tycon
513 | otherwise -- data or newtype
514 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
515 returnRn (AvailTC tycon_name (tycon_name : map getName data_cons))
517 tycon_name = getName tycon
518 data_cons = tyConDataCons tycon
519 mentioned = foldr (unionNameSets . namesOfType . idType) emptyNameSet data_cons
524 %*********************************************************
526 \subsection{Getting what a module exports}
528 %*********************************************************
531 getInterfaceExports :: Module -> RnMG (Avails, [(OccName,Fixity)])
532 getInterfaceExports mod
533 = loadInterface doc_str mod `thenRn` \ (Ifaces _ _ export_envs _ _ _ _ _ _) ->
534 case lookupFM export_envs mod of
535 Nothing -> -- Not there; it must be that the interface file wasn't found;
536 -- the error will have been reported already.
537 -- (Actually loadInterface should put the empty export env in there
538 -- anyway, but this does no harm.)
541 Just stuff -> returnRn stuff
543 doc_str = sep [pprModule PprDebug mod, ptext SLIT("is directly imported")]
547 %*********************************************************
549 \subsection{Data type declarations are handled specially}
551 %*********************************************************
553 Data type declarations get special treatment. If we import a data type decl
554 with all its constructors, we end up importing all the types mentioned in
555 the constructors' signatures, and hence {\em their} data type decls, and so on.
556 In effect, we get the transitive closure of data type decls. Worse, this drags
557 in tons on instance decls, and their unfoldings, and so on.
559 If only the type constructor is mentioned, then all this is a waste of time.
560 If any of the data constructors are mentioned then we really have to
561 drag in the whole declaration.
563 So when we import the type constructor for a @data@ or @newtype@ decl, we
564 put it in the "deferred data/newtype decl" pile in Ifaces. Right at the end
565 we slurp these decls, if they havn't already been dragged in by an occurrence
569 getNonWiredDataDecl needed_name
571 avail@(AvailTC tycon_name _)
572 ty_decl@(TyData new_or_data context tycon tyvars condecls derivings pragmas src_loc)
573 | needed_name == tycon_name
575 && not (nameUnique needed_name `elem` cCallishTyKeys) -- Hack! Don't prune these tycons whose constructors
576 -- the desugarer must be able to see when desugaring
578 = -- Need the type constructor; so put it in the deferred set for now
579 getIfacesRn `thenRn` \ ifaces ->
581 Ifaces this_mod mod_vers_map export_envs decls_fm slurped_names imp_names unslurped_insts deferred_data_decls inst_mods = ifaces
582 new_ifaces = Ifaces this_mod mod_vers_map export_envs decls_fm slurped_names imp_names unslurped_insts new_deferred_data_decls inst_mods
584 no_constr_ty_decl = TyData new_or_data [] tycon tyvars [] derivings pragmas src_loc
585 new_deferred_data_decls = addToFM deferred_data_decls tycon_name no_constr_ty_decl
586 -- Nota bene: we nuke both the constructors and the context in the deferred decl.
587 -- If we don't nuke the context then renaming the deferred data decls can give
588 -- new unresolved names (for the classes). This could be handled, but there's
589 -- no point. If the data type is completely abstract then we aren't interested
592 setIfacesRn new_ifaces `thenRn_`
593 returnRn (AvailTC tycon_name [tycon_name], Nothing)
596 = -- Need a data constructor, so delete the data decl from the deferred set if it's there
597 getIfacesRn `thenRn` \ ifaces ->
599 Ifaces this_mod mod_vers_map export_envs decls_fm slurped_names imp_names unslurped_insts deferred_data_decls inst_mods = ifaces
600 new_ifaces = Ifaces this_mod mod_vers_map export_envs decls_fm slurped_names imp_names unslurped_insts new_deferred_data_decls inst_mods
602 new_deferred_data_decls = delFromFM deferred_data_decls tycon_name
604 setIfacesRn new_ifaces `thenRn_`
605 returnRn (avail, Just (TyD ty_decl))
609 getDeferredDataDecls :: RnMG [(Name, RdrNameTyDecl)]
611 = getIfacesRn `thenRn` \ (Ifaces _ _ _ _ _ _ _ deferred_data_decls _) ->
613 deferred_list = fmToList deferred_data_decls
614 trace_msg = hang (text "Slurping abstract data/newtype decls for: ")
615 4 (ppr PprDebug (map fst deferred_list))
617 traceRn trace_msg `thenRn_`
618 returnRn deferred_list
622 %*********************************************************
624 \subsection{Instance declarations are handled specially}
626 %*********************************************************
629 getImportedInstDecls :: RnMG [(Module,RdrNameInstDecl)]
631 = -- First load any special-instance modules that aren't aready loaded
632 getSpecialInstModules `thenRn` \ inst_mods ->
633 mapRn load_it inst_mods `thenRn_`
635 -- Now we're ready to grab the instance declarations
636 -- Find the un-gated ones and return them,
637 -- removing them from the bag kept in Ifaces
638 getIfacesRn `thenRn` \ ifaces ->
640 Ifaces this_mod mod_vers export_envs decls slurped_names imp_names (insts, tycls_names) deferred_data_decls inst_mods = ifaces
642 -- An instance decl is ungated if all its gates have been slurped
643 select_ungated :: IfaceInst -- A gated inst decl
645 -> ([(Module, RdrNameInstDecl)], [IfaceInst]) -- Accumulator
647 -> ([(Module, RdrNameInstDecl)], -- The ungated ones
648 [IfaceInst]) -- Still gated, but with
650 select_ungated (decl,gates) (ungated_decls, gated_decls)
651 | null remaining_gates
652 = (decl : ungated_decls, gated_decls)
654 = (ungated_decls, (decl, remaining_gates) : gated_decls)
656 remaining_gates = filter (not . (`elemNameSet` tycls_names)) gates
658 (un_gated_insts, still_gated_insts) = foldrBag select_ungated ([], []) insts
660 new_ifaces = Ifaces this_mod mod_vers export_envs decls slurped_names imp_names
661 ((listToBag still_gated_insts), tycls_names)
662 -- NB: don't throw away tycls_names; we may comre across more instance decls
666 traceRn (sep [text "getInstDecls:", fsep (map (ppr PprDebug) (nameSetToList tycls_names))]) `thenRn_`
667 setIfacesRn new_ifaces `thenRn_`
668 returnRn un_gated_insts
670 load_it mod = loadInterface (doc_str mod) mod
671 doc_str mod = sep [pprModule PprDebug mod, ptext SLIT("is a special-instance module")]
674 getSpecialInstModules :: RnMG [Module]
675 getSpecialInstModules
676 = getIfacesRn `thenRn` \ ifaces ->
678 Ifaces _ _ _ _ _ _ _ _ inst_mods = ifaces
684 %*********************************************************
686 \subsection{Keeping track of what we've slurped, and version numbers}
688 %*********************************************************
690 getImportVersions figures out what the "usage information" for this moudule is;
691 that is, what it must record in its interface file as the things it uses.
693 - anything reachable from its body code
694 - any module exported with a "module Foo".
696 Why the latter? Because if Foo changes then this module's export list
697 will change, so we must recompile this module at least as far as
698 making a new interface file --- but in practice that means complete
702 module A( f, g ) where module B( f ) where
703 import B( f ) f = h 3
706 Should we record B.f in A's usages? In fact we don't. Certainly, if
707 anything about B.f changes than anyone who imports A should be recompiled;
708 they'll get an early exit if they don't use B.f. However, even if B.f
709 doesn't change at all, B.h may do so, and this change may not be reflected
710 in f's version number. So there are two things going on when compiling module A:
712 1. Are A.o and A.hi correct? Then we can bale out early.
713 2. Should modules that import A be recompiled?
715 For (1) it is slightly harmful to record B.f in A's usages, because a change in
716 B.f's version will provoke full recompilation of A, producing an identical A.o,
717 and A.hi differing only in its usage-version of B.f (which isn't used by any importer).
719 For (2), because of the tricky B.h question above, we ensure that A.hi is touched
720 (even if identical to its previous version) if A's recompilation was triggered by
721 an imported .hi file date change. Given that, there's no need to record B.f in
724 On the other hand, if A exports "module B" then we *do* count module B among
725 A's usages, because we must recompile A to ensure that A.hi changes appropriately.
728 getImportVersions :: Module -- Name of this module
729 -> Maybe [IE any] -- Export list for this module
730 -> RnMG (VersionInfo Name) -- Version info for these names
732 getImportVersions this_mod exports
733 = getIfacesRn `thenRn` \ ifaces ->
735 Ifaces _ mod_versions_map _ _ _ imp_names _ _ _ = ifaces
736 mod_version mod = expectJust "import_versions" (lookupFM mod_versions_map mod)
738 -- mv_map groups together all the things imported from a particular module.
739 mv_map, mv_map_mod :: FiniteMap Module [LocalVersion Name]
741 mv_map_mod = foldl add_mod emptyFM export_mods
742 -- mv_map_mod records all the modules that have a "module M"
743 -- in this module's export list
745 mv_map = foldl add_mv mv_map_mod imp_names
746 -- mv_map adds the version numbers of things exported individually
748 returnRn [ (mod, mod_version mod, local_versions)
749 | (mod, local_versions) <- fmToList mv_map
753 export_mods = case exports of
755 Just es -> [mod | IEModuleContents mod <- es, mod /= this_mod]
757 add_mv mv_map v@(name, version)
758 = addToFM_C (\ ls _ -> (v:ls)) mv_map mod [v]
760 mod = nameModule name
762 add_mod mv_map mod = addToFM mv_map mod []
767 = getIfacesRn `thenRn` \ (Ifaces _ _ _ _ slurped_names _ _ _ _) ->
768 returnRn (name `elemNameSet` slurped_names)
770 getSlurpedNames :: RnMG NameSet
772 = getIfacesRn `thenRn` \ ifaces ->
774 Ifaces _ _ _ _ slurped_names _ _ _ _ = ifaces
776 returnRn slurped_names
778 recordSlurp maybe_version necessity avail
779 = traceRn (hsep [text "Record slurp:", pprAvail (PprForUser opt_PprUserLength) avail,
780 -- NB PprForDebug prints export flag, which is too
781 -- strict; it's a knot-tied thing in RnNames
782 case necessity of {Compulsory -> text "comp"; Optional -> text "opt"}]) `thenRn_`
783 getIfacesRn `thenRn` \ ifaces ->
785 Ifaces this_mod mod_vers export_envs decls slurped_names imp_names (insts, tycls_names) deferred_data_decls inst_mods = ifaces
786 new_slurped_names = addAvailToNameSet slurped_names avail
788 new_imp_names = case maybe_version of
789 Just version -> (availName avail, version) : imp_names
792 -- Add to the names that will let in instance declarations;
793 -- but only (a) if it's a type/class
794 -- (b) if it's compulsory (unless the test flag opt_PruneInstDecls is off)
795 new_tycls_names = case avail of
796 AvailTC tc _ | not opt_PruneInstDecls ||
797 case necessity of {Optional -> False; Compulsory -> True }
798 -> tycls_names `addOneToNameSet` tc
799 otherwise -> tycls_names
801 new_ifaces = Ifaces this_mod mod_vers export_envs decls
804 (insts, new_tycls_names)
808 setIfacesRn new_ifaces
812 %*********************************************************
814 \subsection{Getting binders out of a declaration}
816 %*********************************************************
818 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
819 It's used for both source code (from @availsFromDecl@) and interface files
822 It doesn't deal with source-code specific things: ValD, DefD. They
823 are handled by the sourc-code specific stuff in RnNames.
826 getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
830 getDeclBinders new_name (TyD (TyData _ _ tycon _ condecls _ _ src_loc))
831 = new_name tycon src_loc `thenRn` \ tycon_name ->
832 getConFieldNames new_name condecls `thenRn` \ sub_names ->
833 returnRn (AvailTC tycon_name (tycon_name : nub sub_names))
834 -- The "nub" is because getConFieldNames can legitimately return duplicates,
835 -- when a record declaration has the same field in multiple constructors
837 getDeclBinders new_name (TyD (TySynonym tycon _ _ src_loc))
838 = new_name tycon src_loc `thenRn` \ tycon_name ->
839 returnRn (AvailTC tycon_name [tycon_name])
841 getDeclBinders new_name (ClD (ClassDecl _ cname _ sigs _ _ src_loc))
842 = new_name cname src_loc `thenRn` \ class_name ->
843 mapRn (getClassOpNames new_name) sigs `thenRn` \ sub_names ->
844 returnRn (AvailTC class_name (class_name : sub_names))
846 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
847 = new_name var src_loc `thenRn` \ var_name ->
848 returnRn (Avail var_name)
850 getDeclBinders new_name (DefD _) = returnRn NotAvailable
851 getDeclBinders new_name (InstD _) = returnRn NotAvailable
854 getConFieldNames new_name (ConDecl con _ (RecCon fielddecls) src_loc : rest)
855 = mapRn (\n -> new_name n src_loc) (con:fields) `thenRn` \ cfs ->
856 getConFieldNames new_name rest `thenRn` \ ns ->
859 fields = concat (map fst fielddecls)
861 getConFieldNames new_name (ConDecl con _ _ src_loc : rest)
862 = new_name con src_loc `thenRn` \ n ->
863 getConFieldNames new_name rest `thenRn` \ ns ->
866 getConFieldNames new_name [] = returnRn []
868 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
872 %*********************************************************
874 \subsection{Reading an interface file}
876 %*********************************************************
879 findAndReadIface :: Doc -> Module -> RnMG (Maybe ParsedIface)
880 -- Nothing <=> file not found, or unreadable, or illegible
881 -- Just x <=> successfully found and parsed
882 findAndReadIface doc_str filename
883 = traceRn trace_msg `thenRn_`
884 getSearchPathRn `thenRn` \ dirs ->
887 trace_msg = hang (hcat [ptext SLIT("Reading interface for "),
888 ptext filename, semi])
889 4 (hcat [ptext SLIT("reason: "), doc_str])
891 try all_dirs [] = traceRn (ptext SLIT("...failed")) `thenRn_`
894 try all_dirs ((dir,hisuf):dirs)
895 = readIface file_path `thenRn` \ read_result ->
897 Nothing -> try all_dirs dirs
898 Just iface -> traceRn (ptext SLIT("...done")) `thenRn_`
899 returnRn (Just iface)
901 file_path = dir ++ "/" ++ moduleString filename ++ hisuf
904 @readIface@ trys just one file.
907 readIface :: String -> RnMG (Maybe ParsedIface)
908 -- Nothing <=> file not found, or unreadable, or illegible
909 -- Just x <=> successfully found and parsed
911 = ioToRnMG (hGetStringBuffer file_path) `thenRn` \ read_result ->
912 --OLD: = ioToRnMG (readFile file_path) `thenRn` \ read_result ->
914 Right contents -> case parseIface contents of
915 Failed err -> --ioToRnMG (freeStringBuffer contents) `thenRn` \ _ ->
916 failWithRn Nothing err
917 Succeeded iface -> --ioToRnMG (freeStringBuffer contents) `thenRn` \ _ ->
918 returnRn (Just iface)
920 #if __GLASGOW_HASKELL__ >= 202
922 if isDoesNotExistError err then
925 failWithRn Nothing (cannaeReadFile file_path err)
926 #else /* 2.01 and 0.2x */
927 Left (NoSuchThing _) -> returnRn Nothing
929 Left err -> failWithRn Nothing
930 (cannaeReadFile file_path err)
935 mkSearchPath takes a string consisting of a colon-separated list of directories and corresponding
936 suffixes, and turns it into a list of (directory, suffix) pairs. For example:
939 mkSearchPath "foo%.hi:.%.p_hi:baz%.mc_hi" = [("foo",".hi"),( ".", ".p_hi"), ("baz",".mc_hi")]
943 mkSearchPath :: Maybe String -> SearchPath
944 mkSearchPath Nothing = [(".",".hi")]
945 mkSearchPath (Just s)
950 case span (/= '%') s of
952 case span (/= ':') rs of
953 (hisuf,_:rest) -> (dir,hisuf):go rest
954 (hisuf,[]) -> [(dir,hisuf)]
957 %*********************************************************
961 %*********************************************************
964 noIfaceErr filename sty
965 = hcat [ptext SLIT("Could not find valid interface file "), quotes (pprModule sty filename)]
966 -- , text " in"]) 4 (vcat (map text dirs))
968 cannaeReadFile file err sty
969 = hcat [ptext SLIT("Failed in reading file: "), text file, ptext SLIT("; error="), text (show err)]
972 = sep [ptext SLIT("Failed to find interface decl for"), ppr sty name]
975 = sep [ptext SLIT("Warning: failed to find (optional) interface decl for"), ppr sty name]