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
24 import GlaExts (trace) -- TEMP
29 import CmdLineOpts ( opt_PruneTyDecls, opt_PruneInstDecls,
30 opt_PprUserLength, opt_IgnoreIfacePragmas
32 import HsSyn ( HsDecl(..), TyDecl(..), ClassDecl(..), HsTyVar, HsExpr, Sig(..), HsType(..),
33 HsBinds(..), MonoBinds, DefaultDecl, ConDecl(..), ConDetails(..), BangType, IfaceSig(..),
34 FixityDecl(..), Fixity, Fake, InPat, InstDecl(..), HsIdInfo,
37 import HsPragmas ( noGenPragmas )
38 import BasicTypes ( SYN_IE(Version), NewOrData(..), IfaceFlavour(..) )
39 import RdrHsSyn ( SYN_IE(RdrNameHsDecl), SYN_IE(RdrNameInstDecl), SYN_IE(RdrNameTyDecl),
42 import RnEnv ( newGlobalName, addImplicitOccsRn, ifaceFlavour,
43 availName, availNames, addAvailToNameSet, pprAvail
45 import RnSource ( rnHsSigType )
47 import RnHsSyn ( SYN_IE(RenamedHsDecl) )
48 import ParseIface ( parseIface )
50 import ErrUtils ( SYN_IE(Error), SYN_IE(Warning) )
51 import FiniteMap ( FiniteMap, sizeFM, emptyFM, unitFM, delFromFM,
52 lookupFM, addToFM, addToFM_C, addListToFM,
55 import Name ( Name {-instance NamedThing-}, Provenance, OccName(..),
56 nameModule, occNameString, moduleString, pprModule, isLocallyDefined,
57 NameSet(..), emptyNameSet, unionNameSets, nameSetToList,
58 minusNameSet, mkNameSet, elemNameSet, nameUnique, addOneToNameSet,
59 isWiredInName, maybeWiredInTyConName, maybeWiredInIdName,
62 import Id ( GenId, Id(..), idType, dataConTyCon, isAlgCon )
63 import TyCon ( TyCon, tyConDataCons, isSynTyCon, getSynTyConDefn )
64 import Type ( namesOfType )
65 import TyVar ( GenTyVar )
66 import SrcLoc ( mkIfaceSrcLoc, SrcLoc )
67 import PrelMods ( gHC__ )
68 import PrelInfo ( cCallishTyKeys )
70 import Maybes ( MaybeErr(..), expectJust, maybeToBool )
71 import ListSetOps ( unionLists )
73 import Outputable ( PprStyle(..) )
74 import Unique ( Unique )
75 import Util ( pprPanic, pprTrace, Ord3(..) )
76 import StringBuffer ( StringBuffer, hGetStringBuffer, freeStringBuffer )
78 #if __GLASGOW_HASKELL__ >= 202
85 %*********************************************************
87 \subsection{Statistics}
89 %*********************************************************
92 getRnStats :: [RenamedHsDecl] -> RnMG Doc
94 = getIfacesRn `thenRn` \ ifaces ->
96 Ifaces this_mod mod_map decls_fm all_names imp_names (unslurped_insts,_) deferred_data_decls inst_mods = ifaces
97 n_mods = sizeFM mod_map
99 decls_imported = filter is_imported_decl all_decls
100 decls_read = [decl | (name, (_, avail, decl)) <- fmToList decls_fm,
101 name == availName avail,
102 -- Data, newtype, and class decls are in the decls_fm
103 -- under multiple names; the tycon/class, and each
104 -- constructor/class op too.
105 not (isLocallyDefined name)
108 (cd_rd, dd_rd, add_rd, nd_rd, and_rd, sd_rd, vd_rd, _) = count_decls decls_read
109 (cd_sp, dd_sp, add_sp, nd_sp, and_sp, sd_sp, vd_sp, id_sp) = count_decls decls_imported
111 inst_decls_unslurped = length (bagToList unslurped_insts)
112 inst_decls_read = id_sp + inst_decls_unslurped
115 [int n_mods <> text " interfaces read",
116 hsep [int cd_sp, text "class decls imported, out of",
117 int cd_rd, text "read"],
118 hsep [int dd_sp, text "data decls imported (of which", int add_sp, text "abstractly), out of",
119 int dd_rd, text "read"],
120 hsep [int nd_sp, text "newtype decls imported (of which", int and_sp, text "abstractly), out of",
121 int nd_rd, text "read"],
122 hsep [int sd_sp, text "type synonym decls imported, out of",
123 int sd_rd, text "read"],
124 hsep [int vd_sp, text "value signatures imported, out of",
125 int vd_rd, text "read"],
126 hsep [int id_sp, text "instance decls imported, out of",
127 int inst_decls_read, text "read"]
130 returnRn (hcat [text "Renamer stats: ", stats])
132 is_imported_decl (DefD _) = False
133 is_imported_decl (ValD _) = False
134 is_imported_decl decl = not (isLocallyDefined (hsDeclName decl))
137 = -- pprTrace "count_decls" (ppr PprDebug decls
142 -- ppr PprDebug imported_decls
145 data_decls, abstract_data_decls,
146 newtype_decls, abstract_newtype_decls,
151 class_decls = length [() | ClD _ <- decls]
152 data_decls = length [() | TyD (TyData DataType _ _ _ _ _ _ _) <- decls]
153 newtype_decls = length [() | TyD (TyData NewType _ _ _ _ _ _ _) <- decls]
154 abstract_data_decls = length [() | TyD (TyData DataType _ _ _ [] _ _ _) <- decls]
155 abstract_newtype_decls = length [() | TyD (TyData NewType _ _ _ [] _ _ _) <- decls]
156 syn_decls = length [() | TyD (TySynonym _ _ _ _) <- decls]
157 val_decls = length [() | SigD _ <- decls]
158 inst_decls = length [() | InstD _ <- decls]
162 %*********************************************************
164 \subsection{Loading a new interface file}
166 %*********************************************************
169 loadInterface :: Doc -> Module -> IfaceFlavour -> RnMG Ifaces
170 loadInterface doc_str load_mod as_source
171 = getIfacesRn `thenRn` \ ifaces ->
173 Ifaces this_mod mod_map decls
174 all_names imp_names (insts, tycls_names)
175 deferred_data_decls inst_mods = ifaces
177 -- CHECK WHETHER WE HAVE IT ALREADY
178 case lookupFM mod_map load_mod of {
179 Just (hif, _, _, _) | hif `as_good_as` as_source
180 -> -- Already in the cache; don't re-read it
184 -- READ THE MODULE IN
185 findAndReadIface doc_str load_mod as_source `thenRn` \ read_result ->
186 case read_result of {
187 -- Check for not found
188 Nothing -> -- Not found, so add an empty export env to the Ifaces map
189 -- so that we don't look again
191 new_mod_map = addToFM mod_map load_mod (HiFile, 0, [],[])
192 new_ifaces = Ifaces this_mod new_mod_map
193 decls all_names imp_names (insts, tycls_names)
194 deferred_data_decls inst_mods
196 setIfacesRn new_ifaces `thenRn_`
197 failWithRn new_ifaces (noIfaceErr load_mod) ;
200 Just (ParsedIface _ mod_vers usages exports rd_inst_mods fixs rd_decls rd_insts) ->
202 -- LOAD IT INTO Ifaces
203 mapRn (loadExport as_source) exports `thenRn` \ avails_s ->
204 foldlRn (loadDecl load_mod as_source) decls rd_decls `thenRn` \ new_decls ->
205 foldlRn (loadInstDecl load_mod) insts rd_insts `thenRn` \ new_insts ->
207 mod_details = (as_source, mod_vers, concat avails_s, fixs)
209 -- Exclude this module from the "special-inst" modules
210 new_inst_mods = inst_mods `unionLists` (filter (/= this_mod) rd_inst_mods)
212 new_ifaces = Ifaces this_mod
213 (addToFM mod_map load_mod mod_details)
216 (new_insts, tycls_names)
220 setIfacesRn new_ifaces `thenRn_`
224 as_good_as HiFile any = True
225 as_good_as any HiBootFile = True
226 as_good_as _ _ = False
229 loadExport :: IfaceFlavour -> ExportItem -> RnMG [AvailInfo]
230 loadExport as_source (mod, hif, entities)
231 = mapRn load_entity entities
233 new_name occ = newGlobalName mod occ hif
235 load_entity (Avail occ)
236 = new_name occ `thenRn` \ name ->
237 returnRn (Avail name)
238 load_entity (AvailTC occ occs)
239 = new_name occ `thenRn` \ name ->
240 mapRn new_name occs `thenRn` \ names ->
241 returnRn (AvailTC name names)
246 -> (Version, RdrNameHsDecl)
248 loadDecl mod as_source decls_map (version, decl)
249 = getDeclBinders new_implicit_name decl `thenRn` \ avail ->
250 returnRn (addListToFM decls_map
251 [(name,(version,avail,decl')) | name <- availNames avail]
255 If a signature decl is being loaded and we're ignoring interface pragmas,
256 toss away unfolding information.
258 Also, if the signature is loaded from a module we're importing from source,
259 we do the same. This is to avoid situations when compiling a pair of mutually
260 recursive modules, peering at unfolding info in the interface file of the other,
261 e.g., you compile A, it looks at B's interface file and may as a result change
262 it's interface file. Hence, B is recompiled, maybe changing it's interface file,
263 which will the ufolding info used in A to become invalid. Simple way out is to
264 just ignore unfolding info.
268 SigD (IfaceSig name tp ls loc) | from_hi_boot || opt_IgnoreIfacePragmas ->
269 SigD (IfaceSig name tp [] loc)
272 new_implicit_name rdr_name loc = newGlobalName mod (rdrNameOcc rdr_name) as_source
273 from_hi_boot = case as_source of
277 loadInstDecl :: Module
280 -> RnMG (Bag IfaceInst)
281 loadInstDecl mod_name insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
283 -- Find out what type constructors and classes are "gates" for the
284 -- instance declaration. If all these "gates" are slurped in then
285 -- we should slurp the instance decl too.
287 -- We *don't* want to count names in the context part as gates, though.
289 -- instance Foo a => Baz (T a) where ...
291 -- Here the gates are Baz and T, but *not* Foo.
293 munged_inst_ty = case inst_ty of
294 HsForAllTy tvs cxt ty -> HsForAllTy tvs [] ty
295 HsPreForAllTy cxt ty -> HsPreForAllTy [] ty
298 -- We find the gates by renaming the instance type with in a
299 -- and returning the occurrence pool.
300 initRnMS emptyRnEnv mod_name (InterfaceMode Compulsory) (
301 findOccurrencesRn (rnHsSigType (\sty -> text "an instance decl") munged_inst_ty)
302 ) `thenRn` \ gate_names ->
303 returnRn (((mod_name, decl), gate_names) `consBag` insts)
307 %********************************************************
309 \subsection{Loading usage information}
311 %********************************************************
314 checkUpToDate :: Module -> RnMG Bool -- True <=> no need to recompile
315 checkUpToDate mod_name
316 = findAndReadIface doc_str mod_name HiFile `thenRn` \ read_result ->
318 -- CHECK WHETHER WE HAVE IT ALREADY
320 Nothing -> -- Old interface file not found, so we'd better bail out
321 traceRn (sep [ptext SLIT("Didnt find old iface"),
322 pprModule PprDebug mod_name]) `thenRn_`
325 Just (ParsedIface _ _ usages _ _ _ _ _)
326 -> -- Found it, so now check it
329 -- Only look in current directory, with suffix .hi
330 doc_str = sep [ptext SLIT("Need usage info from"), pprModule PprDebug mod_name]
332 checkModUsage [] = returnRn True -- Yes! Everything is up to date!
334 checkModUsage ((mod, hif, old_mod_vers, old_local_vers) : rest)
335 = loadInterface doc_str mod hif `thenRn` \ ifaces ->
337 Ifaces _ mod_map decls _ _ _ _ _ = ifaces
338 maybe_new_mod_vers = lookupFM mod_map mod
339 Just (_, new_mod_vers, _, _) = maybe_new_mod_vers
341 -- If we can't find a version number for the old module then
342 -- bail out saying things aren't up to date
343 if not (maybeToBool maybe_new_mod_vers) then
344 traceRn (sep [ptext SLIT("Can't find version number for module"), pprModule PprDebug mod]) `thenRn_`
348 -- If the module version hasn't changed, just move on
349 if new_mod_vers == old_mod_vers then
350 traceRn (sep [ptext SLIT("Module version unchanged:"), pprModule PprDebug mod]) `thenRn_`
353 traceRn (sep [ptext SLIT("Module version has changed:"), pprModule PprDebug mod]) `thenRn_`
355 -- New module version, so check entities inside
356 checkEntityUsage mod decls old_local_vers `thenRn` \ up_to_date ->
358 traceRn (ptext SLIT("...but the bits I use haven't.")) `thenRn_`
359 checkModUsage rest -- This one's ok, so check the rest
361 returnRn False -- This one failed, so just bail out now
363 doc_str = sep [ptext SLIT("need version info for"), pprModule PprDebug mod]
366 checkEntityUsage mod decls []
367 = returnRn True -- Yes! All up to date!
369 checkEntityUsage mod decls ((occ_name,old_vers) : rest)
370 = newGlobalName mod occ_name HiFile {- ?? -} `thenRn` \ name ->
371 case lookupFM decls name of
373 Nothing -> -- We used it before, but it ain't there now
374 traceRn (sep [ptext SLIT("...and this no longer exported:"), ppr PprDebug name]) `thenRn_`
377 Just (new_vers,_,_) -- It's there, but is it up to date?
378 | new_vers == old_vers
379 -- Up to date, so check the rest
380 -> checkEntityUsage mod decls rest
383 -- Out of date, so bale out
384 -> traceRn (sep [ptext SLIT("...and this is out of date:"), ppr PprDebug name]) `thenRn_`
389 %*********************************************************
391 \subsection{Getting in a declaration}
393 %*********************************************************
396 importDecl :: Name -> Necessity -> RnMG (Maybe RdrNameHsDecl)
397 -- Returns Nothing for a wired-in or already-slurped decl
399 importDecl name necessity
400 = checkSlurped name `thenRn` \ already_slurped ->
401 if already_slurped then
402 -- traceRn (sep [text "Already slurped:", ppr PprDebug name]) `thenRn_`
403 returnRn Nothing -- Already dealt with
405 if isWiredInName name then
406 getWiredInDecl name necessity
408 getIfacesRn `thenRn` \ ifaces ->
410 Ifaces this_mod _ _ _ _ _ _ _ = ifaces
411 mod = nameModule name
413 if mod == this_mod then -- Don't bring in decls from
414 pprTrace "importDecl wierdness:" (ppr PprDebug name) $
415 returnRn Nothing -- the renamed module's own interface file
418 getNonWiredInDecl name necessity
422 getNonWiredInDecl :: Name -> Necessity -> RnMG (Maybe RdrNameHsDecl)
423 getNonWiredInDecl needed_name necessity
424 = traceRn doc_str `thenRn_`
425 loadInterface doc_str mod (ifaceFlavour needed_name) `thenRn` \ (Ifaces _ _ decls _ _ _ _ _) ->
426 case lookupFM decls needed_name of
428 -- Special case for data/newtype type declarations
429 Just (version, avail, TyD ty_decl) | is_data_or_newtype ty_decl
430 -> getNonWiredDataDecl needed_name version avail ty_decl `thenRn` \ (avail', maybe_decl) ->
431 recordSlurp (Just version) necessity avail' `thenRn_`
434 Just (version,avail,decl)
435 -> recordSlurp (Just version) necessity avail `thenRn_`
438 Nothing -> -- Can happen legitimately for "Optional" occurrences
440 Optional -> addWarnRn (getDeclWarn needed_name);
441 other -> addErrRn (getDeclErr needed_name)
445 doc_str = sep [ptext SLIT("Need decl for"), ppr PprDebug needed_name]
446 mod = nameModule needed_name
448 is_data_or_newtype (TyData _ _ _ _ _ _ _ _) = True
449 is_data_or_newtype other = False
453 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
454 It behaves exactly as if the wired in decl were actually in an interface file.
457 * if the wired-in name is a data type constructor or a data constructor,
458 it brings in the type constructor and all the data constructors; and
459 marks as "occurrences" any free vars of the data con.
461 * similarly for synonum type constructor
463 * if the wired-in name is another wired-in Id, it marks as "occurrences"
464 the free vars of the Id's type.
466 * it loads the interface file for the wired-in thing for the
467 sole purpose of making sure that its instance declarations are available
469 All this is necessary so that we know all types that are "in play", so
470 that we know just what instances to bring into scope.
473 getWiredInDecl name necessity
474 = initRnMS emptyRnEnv mod_name (InterfaceMode necessity)
475 get_wired `thenRn` \ avail ->
476 recordSlurp Nothing necessity avail `thenRn_`
478 -- Force in the home module in case it has instance decls for
479 -- the thing we are interested in.
481 -- Mini hack 1: no point for non-tycons/class; and if we
482 -- do this we find PrelNum trying to import PackedString,
483 -- because PrelBase's .hi file mentions PackedString.unpackString
484 -- But PackedString.hi isn't built by that point!
486 -- Mini hack 2; GHC is guaranteed not to have
487 -- instance decls, so it's a waste of time to read it
489 -- NB: We *must* look at the availName of the slurped avail,
490 -- not the name passed to getWiredInDecl! Why? Because if a data constructor
491 -- or class op is passed to getWiredInDecl we'll pull in the whole data/class
492 -- decl, and recordSlurp will record that fact. But since the data constructor
493 -- isn't a tycon/class we won't force in the home module. And even if the
494 -- type constructor/class comes along later, loadDecl will say that it's already
495 -- been slurped, so getWiredInDecl won't even be called. Pretty obscure bug, this was.
497 main_name = availName avail
498 main_is_tc = case avail of { AvailTC _ _ -> True; Avail _ -> False }
499 mod = nameModule main_name
500 doc_str = sep [ptext SLIT("Need home module for wired in thing"), ppr PprDebug name]
502 (if not main_is_tc || mod == gHC__ then
505 loadInterface doc_str mod (ifaceFlavour main_name) `thenRn_`
509 returnRn Nothing -- No declaration to process further
512 get_wired | is_tycon -- ... a type constructor
513 = get_wired_tycon the_tycon
515 | (isAlgCon the_id) -- ... a wired-in data constructor
516 = get_wired_tycon (dataConTyCon the_id)
518 | otherwise -- ... a wired-in non data-constructor
519 = get_wired_id the_id
521 mod_name = nameModule name
522 maybe_wired_in_tycon = maybeWiredInTyConName name
523 is_tycon = maybeToBool maybe_wired_in_tycon
524 maybe_wired_in_id = maybeWiredInIdName name
525 Just the_tycon = maybe_wired_in_tycon
526 Just the_id = maybe_wired_in_id
530 = addImplicitOccsRn id_mentions `thenRn_`
531 returnRn (Avail (getName id))
533 id_mentions = nameSetToList (namesOfType ty)
536 get_wired_tycon tycon
538 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
539 returnRn (AvailTC tc_name [tc_name])
541 tc_name = getName tycon
542 (tyvars,ty) = getSynTyConDefn tycon
543 mentioned = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
545 get_wired_tycon tycon
546 | otherwise -- data or newtype
547 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
548 returnRn (AvailTC tycon_name (tycon_name : map getName data_cons))
550 tycon_name = getName tycon
551 data_cons = tyConDataCons tycon
552 mentioned = foldr (unionNameSets . namesOfType . idType) emptyNameSet data_cons
557 %*********************************************************
559 \subsection{Getting what a module exports}
561 %*********************************************************
564 getInterfaceExports :: Module -> IfaceFlavour -> RnMG (Avails, [(OccName,Fixity)])
565 getInterfaceExports mod as_source
566 = loadInterface doc_str mod as_source `thenRn` \ (Ifaces _ mod_map _ _ _ _ _ _) ->
567 case lookupFM mod_map mod of
568 Nothing -> -- Not there; it must be that the interface file wasn't found;
569 -- the error will have been reported already.
570 -- (Actually loadInterface should put the empty export env in there
571 -- anyway, but this does no harm.)
574 Just (_, _, avails, fixities) -> returnRn (avails, fixities)
576 doc_str = sep [pprModule PprDebug mod, ptext SLIT("is directly imported")]
580 %*********************************************************
582 \subsection{Data type declarations are handled specially}
584 %*********************************************************
586 Data type declarations get special treatment. If we import a data type decl
587 with all its constructors, we end up importing all the types mentioned in
588 the constructors' signatures, and hence {\em their} data type decls, and so on.
589 In effect, we get the transitive closure of data type decls. Worse, this drags
590 in tons on instance decls, and their unfoldings, and so on.
592 If only the type constructor is mentioned, then all this is a waste of time.
593 If any of the data constructors are mentioned then we really have to
594 drag in the whole declaration.
596 So when we import the type constructor for a @data@ or @newtype@ decl, we
597 put it in the "deferred data/newtype decl" pile in Ifaces. Right at the end
598 we slurp these decls, if they havn't already been dragged in by an occurrence
602 getNonWiredDataDecl needed_name
604 avail@(AvailTC tycon_name _)
605 ty_decl@(TyData new_or_data context tycon tyvars condecls derivings pragmas src_loc)
606 | needed_name == tycon_name
608 && not (nameUnique needed_name `elem` cCallishTyKeys) -- Hack! Don't prune these tycons whose constructors
609 -- the desugarer must be able to see when desugaring
611 = -- Need the type constructor; so put it in the deferred set for now
612 getIfacesRn `thenRn` \ ifaces ->
614 Ifaces this_mod mod_map decls_fm slurped_names imp_names unslurped_insts deferred_data_decls inst_mods = ifaces
615 new_ifaces = Ifaces this_mod mod_map decls_fm slurped_names imp_names unslurped_insts new_deferred_data_decls inst_mods
617 no_constr_ty_decl = TyData new_or_data [] tycon tyvars [] derivings pragmas src_loc
618 new_deferred_data_decls = addToFM deferred_data_decls tycon_name no_constr_ty_decl
619 -- Nota bene: we nuke both the constructors and the context in the deferred decl.
620 -- If we don't nuke the context then renaming the deferred data decls can give
621 -- new unresolved names (for the classes). This could be handled, but there's
622 -- no point. If the data type is completely abstract then we aren't interested
625 setIfacesRn new_ifaces `thenRn_`
626 returnRn (AvailTC tycon_name [tycon_name], Nothing)
629 = -- Need a data constructor, so delete the data decl from the deferred set if it's there
630 getIfacesRn `thenRn` \ ifaces ->
632 Ifaces this_mod mod_map decls_fm slurped_names imp_names unslurped_insts deferred_data_decls inst_mods = ifaces
633 new_ifaces = Ifaces this_mod mod_map decls_fm slurped_names imp_names unslurped_insts new_deferred_data_decls inst_mods
635 new_deferred_data_decls = delFromFM deferred_data_decls tycon_name
637 setIfacesRn new_ifaces `thenRn_`
638 returnRn (avail, Just (TyD ty_decl))
642 getDeferredDataDecls :: RnMG [(Name, RdrNameTyDecl)]
644 = getIfacesRn `thenRn` \ (Ifaces _ _ _ _ _ _ deferred_data_decls _) ->
646 deferred_list = fmToList deferred_data_decls
647 trace_msg = hang (text "Slurping abstract data/newtype decls for: ")
648 4 (ppr PprDebug (map fst deferred_list))
650 traceRn trace_msg `thenRn_`
651 returnRn deferred_list
655 %*********************************************************
657 \subsection{Instance declarations are handled specially}
659 %*********************************************************
662 getImportedInstDecls :: RnMG [(Module,RdrNameInstDecl)]
664 = -- First load any special-instance modules that aren't aready loaded
665 getSpecialInstModules `thenRn` \ inst_mods ->
666 mapRn load_it inst_mods `thenRn_`
668 -- Now we're ready to grab the instance declarations
669 -- Find the un-gated ones and return them,
670 -- removing them from the bag kept in Ifaces
671 getIfacesRn `thenRn` \ ifaces ->
673 Ifaces this_mod mod_map decls slurped_names imp_names (insts, tycls_names) deferred_data_decls inst_mods = ifaces
675 -- An instance decl is ungated if all its gates have been slurped
676 select_ungated :: IfaceInst -- A gated inst decl
678 -> ([(Module, RdrNameInstDecl)], [IfaceInst]) -- Accumulator
680 -> ([(Module, RdrNameInstDecl)], -- The ungated ones
681 [IfaceInst]) -- Still gated, but with
683 select_ungated (decl,gates) (ungated_decls, gated_decls)
684 | null remaining_gates
685 = (decl : ungated_decls, gated_decls)
687 = (ungated_decls, (decl, remaining_gates) : gated_decls)
689 remaining_gates = filter (not . (`elemNameSet` tycls_names)) gates
691 (un_gated_insts, still_gated_insts) = foldrBag select_ungated ([], []) insts
693 new_ifaces = Ifaces this_mod mod_map decls slurped_names imp_names
694 ((listToBag still_gated_insts), tycls_names)
695 -- NB: don't throw away tycls_names; we may comre across more instance decls
699 traceRn (sep [text "getInstDecls:", fsep (map (ppr PprDebug) (nameSetToList tycls_names))]) `thenRn_`
700 setIfacesRn new_ifaces `thenRn_`
701 returnRn un_gated_insts
703 load_it mod = loadInterface (doc_str mod) mod HiFile
704 doc_str mod = sep [pprModule PprDebug mod, ptext SLIT("is a special-instance module")]
707 getSpecialInstModules :: RnMG [Module]
708 getSpecialInstModules
709 = getIfacesRn `thenRn` \ ifaces ->
711 Ifaces _ _ _ _ _ _ _ inst_mods = ifaces
717 %*********************************************************
719 \subsection{Keeping track of what we've slurped, and version numbers}
721 %*********************************************************
723 getImportVersions figures out what the "usage information" for this moudule is;
724 that is, what it must record in its interface file as the things it uses.
726 - anything reachable from its body code
727 - any module exported with a "module Foo".
729 Why the latter? Because if Foo changes then this module's export list
730 will change, so we must recompile this module at least as far as
731 making a new interface file --- but in practice that means complete
735 module A( f, g ) where module B( f ) where
736 import B( f ) f = h 3
739 Should we record B.f in A's usages? In fact we don't. Certainly, if
740 anything about B.f changes than anyone who imports A should be recompiled;
741 they'll get an early exit if they don't use B.f. However, even if B.f
742 doesn't change at all, B.h may do so, and this change may not be reflected
743 in f's version number. So there are two things going on when compiling module A:
745 1. Are A.o and A.hi correct? Then we can bale out early.
746 2. Should modules that import A be recompiled?
748 For (1) it is slightly harmful to record B.f in A's usages, because a change in
749 B.f's version will provoke full recompilation of A, producing an identical A.o,
750 and A.hi differing only in its usage-version of B.f (which isn't used by any importer).
752 For (2), because of the tricky B.h question above, we ensure that A.hi is touched
753 (even if identical to its previous version) if A's recompilation was triggered by
754 an imported .hi file date change. Given that, there's no need to record B.f in
757 On the other hand, if A exports "module B" then we *do* count module B among
758 A's usages, because we must recompile A to ensure that A.hi changes appropriately.
761 getImportVersions :: Module -- Name of this module
762 -> Maybe [IE any] -- Export list for this module
763 -> RnMG (VersionInfo Name) -- Version info for these names
765 getImportVersions this_mod exports
766 = getIfacesRn `thenRn` \ ifaces ->
768 Ifaces _ mod_map _ _ imp_names _ _ _ = ifaces
770 -- mv_map groups together all the things imported from a particular module.
771 mv_map, mv_map_mod :: FiniteMap Module [LocalVersion Name]
773 mv_map_mod = foldl add_mod emptyFM export_mods
774 -- mv_map_mod records all the modules that have a "module M"
775 -- in this module's export list
777 mv_map = foldl add_mv mv_map_mod imp_names
778 -- mv_map adds the version numbers of things exported individually
780 mk_version_info (mod, local_versions)
781 = case lookupFM mod_map mod of
782 Just (hif, version, _, _) -> (mod, hif, version, local_versions)
784 returnRn (map mk_version_info (fmToList mv_map))
786 export_mods = case exports of
788 Just es -> [mod | IEModuleContents mod <- es, mod /= this_mod]
790 add_mv mv_map v@(name, version)
791 = addToFM_C (\ ls _ -> (v:ls)) mv_map mod [v]
793 mod = nameModule name
795 add_mod mv_map mod = addToFM mv_map mod []
800 = getIfacesRn `thenRn` \ (Ifaces _ _ _ slurped_names _ _ _ _) ->
801 returnRn (name `elemNameSet` slurped_names)
803 getSlurpedNames :: RnMG NameSet
805 = getIfacesRn `thenRn` \ ifaces ->
807 Ifaces _ _ _ slurped_names _ _ _ _ = ifaces
809 returnRn slurped_names
811 recordSlurp maybe_version necessity avail
812 = {- traceRn (hsep [text "Record slurp:", pprAvail (PprForUser opt_PprUserLength) avail,
813 -- NB PprForDebug prints export flag, which is too
814 -- strict; it's a knot-tied thing in RnNames
815 case necessity of {Compulsory -> text "comp"; Optional -> text "opt" } ]) `thenRn_`
817 getIfacesRn `thenRn` \ ifaces ->
819 Ifaces this_mod mod_map decls slurped_names imp_names (insts, tycls_names) deferred_data_decls inst_mods = ifaces
820 new_slurped_names = addAvailToNameSet slurped_names avail
822 new_imp_names = case maybe_version of
823 Just version -> (availName avail, version) : imp_names
826 -- Add to the names that will let in instance declarations;
827 -- but only (a) if it's a type/class
828 -- (b) if it's compulsory (unless the test flag opt_PruneInstDecls is off)
829 new_tycls_names = case avail of
830 AvailTC tc _ | not opt_PruneInstDecls ||
831 case necessity of {Optional -> False; Compulsory -> True }
832 -> tycls_names `addOneToNameSet` tc
833 otherwise -> tycls_names
835 new_ifaces = Ifaces this_mod mod_map decls
838 (insts, new_tycls_names)
842 setIfacesRn new_ifaces
846 %*********************************************************
848 \subsection{Getting binders out of a declaration}
850 %*********************************************************
852 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
853 It's used for both source code (from @availsFromDecl@) and interface files
856 It doesn't deal with source-code specific things: ValD, DefD. They
857 are handled by the sourc-code specific stuff in RnNames.
860 getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
864 getDeclBinders new_name (TyD (TyData _ _ tycon _ condecls _ _ src_loc))
865 = new_name tycon src_loc `thenRn` \ tycon_name ->
866 getConFieldNames new_name condecls `thenRn` \ sub_names ->
867 returnRn (AvailTC tycon_name (tycon_name : nub sub_names))
868 -- The "nub" is because getConFieldNames can legitimately return duplicates,
869 -- when a record declaration has the same field in multiple constructors
871 getDeclBinders new_name (TyD (TySynonym tycon _ _ src_loc))
872 = new_name tycon src_loc `thenRn` \ tycon_name ->
873 returnRn (AvailTC tycon_name [tycon_name])
875 getDeclBinders new_name (ClD (ClassDecl _ cname _ sigs _ _ src_loc))
876 = new_name cname src_loc `thenRn` \ class_name ->
877 mapRn (getClassOpNames new_name) sigs `thenRn` \ sub_names ->
878 returnRn (AvailTC class_name (class_name : sub_names))
880 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
881 = new_name var src_loc `thenRn` \ var_name ->
882 returnRn (Avail var_name)
884 getDeclBinders new_name (DefD _) = returnRn NotAvailable
885 getDeclBinders new_name (InstD _) = returnRn NotAvailable
888 getConFieldNames new_name (ConDecl con _ (RecCon fielddecls) src_loc : rest)
889 = mapRn (\n -> new_name n src_loc) (con:fields) `thenRn` \ cfs ->
890 getConFieldNames new_name rest `thenRn` \ ns ->
893 fields = concat (map fst fielddecls)
895 getConFieldNames new_name (ConDecl con _ _ src_loc : rest)
896 = new_name con src_loc `thenRn` \ n ->
897 getConFieldNames new_name rest `thenRn` \ ns ->
900 getConFieldNames new_name [] = returnRn []
902 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
906 %*********************************************************
908 \subsection{Reading an interface file}
910 %*********************************************************
913 findAndReadIface :: Doc -> Module
915 -> RnMG (Maybe ParsedIface)
916 -- Nothing <=> file not found, or unreadable, or illegible
917 -- Just x <=> successfully found and parsed
918 findAndReadIface doc_str mod_name as_source
919 = traceRn trace_msg `thenRn_`
920 getSearchPathRn `thenRn` \ dirs ->
923 trace_msg = sep [hsep [ptext SLIT("Reading"),
924 case as_source of { HiBootFile -> ptext SLIT("[boot]"); other -> empty},
925 ptext SLIT("interface for"),
928 nest 4 (ptext SLIT("reason:") <> doc_str)]
930 -- For import {-# SOURCE #-} Foo, "as_source" will be True
931 -- and we read Foo.hi-boot, not Foo.hi. This is used to break
932 -- loops among modules.
933 boot_suffix = case as_source of
934 HiBootFile -> "-boot"
937 try all_dirs [] = traceRn (ptext SLIT("...failed")) `thenRn_`
940 try all_dirs ((dir,hisuf):dirs)
941 = readIface file_path `thenRn` \ read_result ->
943 Nothing -> try all_dirs dirs
944 Just iface -> traceRn (ptext SLIT("...done")) `thenRn_`
945 returnRn (Just iface)
947 file_path = dir ++ '/' : moduleString mod_name ++ hisuf ++ boot_suffix
950 @readIface@ trys just one file.
953 readIface :: String -> RnMG (Maybe ParsedIface)
954 -- Nothing <=> file not found, or unreadable, or illegible
955 -- Just x <=> successfully found and parsed
957 = ioToRnMG (hGetStringBuffer file_path) `thenRn` \ read_result ->
958 --traceRn (hcat[ptext SLIT("Opening...."), text file_path]) `thenRn_`
961 case parseIface contents of
963 --traceRn (ptext SLIT("parse err")) `thenRn_`
964 failWithRn Nothing err
966 --traceRn (ptext SLIT("parse cool")) `thenRn_`
967 returnRn (Just iface)
969 #if __GLASGOW_HASKELL__ >= 202
971 if isDoesNotExistError err then
972 --traceRn (ptext SLIT("no file")) `thenRn_`
975 --traceRn (ptext SLIT("uh-oh..")) `thenRn_`
976 failWithRn Nothing (cannaeReadFile file_path err)
977 #else /* 2.01 and 0.2x */
978 Left (NoSuchThing _) -> returnRn Nothing
980 Left err -> failWithRn Nothing
981 (cannaeReadFile file_path err)
986 mkSearchPath takes a string consisting of a colon-separated list
987 of directories and corresponding suffixes, and turns it into a list
988 of (directory, suffix) pairs. For example:
991 mkSearchPath "foo%.hi:.%.p_hi:baz%.mc_hi"
992 = [("foo",".hi"),( ".", ".p_hi"), ("baz",".mc_hi")]
996 mkSearchPath :: Maybe String -> SearchPath
997 mkSearchPath Nothing = [(".",".hi")]
998 mkSearchPath (Just s)
1003 case span (/= '%') s of
1005 case span (/= ':') rs of
1006 (hisuf,_:rest) -> (dir,hisuf):go rest
1007 (hisuf,[]) -> [(dir,hisuf)]
1010 %*********************************************************
1014 %*********************************************************
1017 noIfaceErr filename sty
1018 = hcat [ptext SLIT("Could not find valid interface file "),
1019 quotes (pprModule sty filename)]
1020 -- , text " in"]) 4 (vcat (map text dirs))
1022 cannaeReadFile file err sty
1023 = hcat [ptext SLIT("Failed in reading file: "),
1025 ptext SLIT("; error="),
1029 = sep [ptext SLIT("Failed to find interface decl for"),
1032 getDeclWarn name sty
1033 = sep [ptext SLIT("Warning: failed to find (optional) interface decl for"),