2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnIfaces]{Cacheing and Renaming of Interfaces}
10 getSpecialInstModules, getDeferredDataDecls,
11 importDecl, recordSlurp,
12 getImportVersions, getSlurpedNames, getRnStats, getImportedFixities,
14 checkUpToDate, loadHomeInterface,
20 #include "HsVersions.h"
22 import CmdLineOpts ( opt_PruneTyDecls, opt_PruneInstDecls,
23 opt_D_show_rn_imports, opt_IgnoreIfacePragmas
25 import HsSyn ( HsDecl(..), TyClDecl(..), InstDecl(..), IfaceSig(..),
26 HsType(..), ConDecl(..), IE(..), ConDetails(..), Sig(..),
28 hsDeclName, countTyClDecls, isDataDecl, nonFixitySigs
30 import BasicTypes ( Version, NewOrData(..) )
31 import RdrHsSyn ( RdrNameHsDecl, RdrNameInstDecl, RdrNameTyClDecl,
33 import RnEnv ( newImportedGlobalName, newImportedGlobalFromRdrName,
34 addImplicitOccsRn, pprAvail,
35 availName, availNames, addAvailToNameSet
37 import RnSource ( rnHsSigType )
39 import RnHsSyn ( RenamedHsDecl )
40 import ParseIface ( parseIface, IfaceStuff(..) )
42 import FiniteMap ( FiniteMap, sizeFM, emptyFM, delFromFM,
43 lookupFM, addToFM, addToFM_C, addListToFM,
46 import Name ( Name {-instance NamedThing-},
47 nameModule, moduleString, pprModule, isLocallyDefined,
48 isWiredInName, maybeWiredInTyConName, pprModule,
49 maybeWiredInIdName, nameUnique, NamedThing(..)
51 import OccName ( Module, mkBootModule,
52 moduleIfaceFlavour, bootFlavour, hiFile
54 import RdrName ( RdrName, rdrNameOcc )
56 import Id ( idType, isDataConId_maybe )
57 import DataCon ( dataConTyCon, dataConType )
58 import TyCon ( TyCon, tyConDataCons, isSynTyCon, getSynTyConDefn )
59 import Type ( namesOfType )
61 import SrcLoc ( mkSrcLoc, SrcLoc )
62 import PrelMods ( pREL_GHC )
63 import PrelInfo ( cCallishTyKeys, thinAirModules )
65 import Maybes ( MaybeErr(..), maybeToBool )
66 import ListSetOps ( unionLists )
68 import Unique ( Unique )
69 import StringBuffer ( StringBuffer, hGetStringBuffer )
70 import FastString ( mkFastString )
73 import IO ( isDoesNotExistError )
80 %*********************************************************
82 \subsection{Statistics}
84 %*********************************************************
87 getRnStats :: [RenamedHsDecl] -> RnMG SDoc
89 = getIfacesRn `thenRn` \ ifaces ->
91 n_mods = sizeFM (iModMap ifaces)
93 decls_imported = filter is_imported_decl all_decls
95 decls_read = [decl | (_, avail, decl, True) <- nameEnvElts (iDecls ifaces),
96 -- Data, newtype, and class decls are in the decls_fm
97 -- under multiple names; the tycon/class, and each
98 -- constructor/class op too.
99 -- The 'True' selects just the 'main' decl
100 not (isLocallyDefined (availName avail))
103 (cd_rd, dd_rd, add_rd, nd_rd, and_rd, sd_rd, vd_rd, _) = count_decls decls_read
104 (cd_sp, dd_sp, add_sp, nd_sp, and_sp, sd_sp, vd_sp, id_sp) = count_decls decls_imported
106 (unslurped_insts, _) = iDefInsts ifaces
107 inst_decls_unslurped = length (bagToList unslurped_insts)
108 inst_decls_read = id_sp + inst_decls_unslurped
111 [int n_mods <> text " interfaces read",
112 hsep [ int cd_sp, text "class decls imported, out of",
113 int cd_rd, text "read"],
114 hsep [ int dd_sp, text "data decls imported (of which", int add_sp,
115 text "abstractly), out of",
116 int dd_rd, text "read"],
117 hsep [ int nd_sp, text "newtype decls imported (of which", int and_sp,
118 text "abstractly), out of",
119 int nd_rd, text "read"],
120 hsep [int sd_sp, text "type synonym decls imported, out of",
121 int sd_rd, text "read"],
122 hsep [int vd_sp, text "value signatures imported, out of",
123 int vd_rd, text "read"],
124 hsep [int id_sp, text "instance decls imported, out of",
125 int inst_decls_read, text "read"]
128 returnRn (hcat [text "Renamer stats: ", stats])
130 is_imported_decl (DefD _) = False
131 is_imported_decl (ValD _) = False
132 is_imported_decl decl = not (isLocallyDefined (hsDeclName decl))
135 = -- pprTrace "count_decls" (ppr decls
140 -- ppr imported_decls
143 data_decls, abstract_data_decls,
144 newtype_decls, abstract_newtype_decls,
149 tycl_decls = [d | TyClD d <- decls]
150 (class_decls, data_decls, newtype_decls, syn_decls) = countTyClDecls tycl_decls
151 abstract_data_decls = length [() | TyData DataType _ _ _ [] _ _ _ <- tycl_decls]
152 abstract_newtype_decls = length [() | TyData NewType _ _ _ [] _ _ _ <- tycl_decls]
154 val_decls = length [() | SigD _ <- decls]
155 inst_decls = length [() | InstD _ <- decls]
159 %*********************************************************
161 \subsection{Loading a new interface file}
163 %*********************************************************
166 loadHomeInterface :: SDoc -> Name -> RnMG Ifaces
167 loadHomeInterface doc_str name
168 = loadInterface doc_str (nameModule name)
170 loadInterface :: SDoc -> Module -> RnMG Ifaces
171 loadInterface doc_str load_mod
172 = getIfacesRn `thenRn` \ ifaces ->
174 new_hif = moduleIfaceFlavour load_mod
175 this_mod = iMod ifaces
176 mod_map = iModMap ifaces
177 (insts, tycls_names) = iDefInsts ifaces
179 -- CHECK WHETHER WE HAVE IT ALREADY
180 case lookupFM mod_map load_mod of {
181 Just (existing_hif, _, _)
182 | bootFlavour new_hif || not (bootFlavour existing_hif)
183 -> -- Already in the cache, and new version is no better than old,
184 -- so don't re-read it
188 -- READ THE MODULE IN
189 findAndReadIface doc_str load_mod `thenRn` \ read_result ->
190 case read_result of {
191 -- Check for not found
192 Nothing -> -- Not found, so add an empty export env to the Ifaces map
193 -- so that we don't look again
195 new_mod_map = addToFM mod_map load_mod (hiFile, 0, [])
196 new_ifaces = ifaces { iModMap = new_mod_map }
198 setIfacesRn new_ifaces `thenRn_`
199 failWithRn new_ifaces (noIfaceErr load_mod) ;
202 Just (ParsedIface _ mod_vers usages exports rd_inst_mods rd_decls rd_insts) ->
204 -- LOAD IT INTO Ifaces
205 -- First set the module
206 setModuleRn load_mod $
208 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
209 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
210 -- If we do loadExport first the wrong info gets into the cache (unless we
211 -- explicitly tag each export which seems a bit of a bore)
212 foldlRn loadDecl (iDecls ifaces) rd_decls `thenRn` \ new_decls ->
213 foldlRn loadFixDecl (iFixes ifaces) rd_decls `thenRn` \ new_fixities ->
214 mapRn loadExport exports `thenRn` \ avails_s ->
215 foldlRn loadInstDecl insts rd_insts `thenRn` \ new_insts ->
217 mod_details = (new_hif, mod_vers, concat avails_s)
219 -- Exclude this module from the "special-inst" modules
220 new_inst_mods = iInstMods ifaces `unionLists` (filter (/= this_mod) rd_inst_mods)
222 new_ifaces = ifaces { iModMap = addToFM mod_map load_mod mod_details,
224 iFixes = new_fixities,
225 iDefInsts = (new_insts, tycls_names),
226 iInstMods = new_inst_mods }
228 setIfacesRn new_ifaces `thenRn_`
232 loadExport :: ExportItem -> RnMG [AvailInfo]
233 loadExport (mod, entities)
234 = mapRn load_entity entities
236 new_name occ = newImportedGlobalName mod occ
238 load_entity (Avail occ)
239 = new_name occ `thenRn` \ name ->
240 returnRn (Avail name)
241 load_entity (AvailTC occ occs)
242 = new_name occ `thenRn` \ name ->
243 mapRn new_name occs `thenRn` \ names ->
244 returnRn (AvailTC name names)
247 loadFixDecl :: FixityEnv
248 -> (Version, RdrNameHsDecl)
250 loadFixDecl fixity_env (version, FixD (FixitySig rdr_name fixity loc))
251 = -- Ignore the version; when the fixity changes the version of
252 -- its 'host' entity changes, so we don't need a separate version
253 -- number for fixities
254 newImportedGlobalFromRdrName rdr_name `thenRn` \ name ->
256 new_fixity_env = addToNameEnv fixity_env name (FixitySig name fixity loc)
258 returnRn new_fixity_env
260 -- Ignore the other sorts of decl
261 loadFixDecl fixity_env other_decl = returnRn fixity_env
264 -> (Version, RdrNameHsDecl)
267 loadDecl decls_map (version, decl)
268 = getDeclBinders new_name decl `thenRn` \ maybe_avail ->
269 case maybe_avail of {
270 Nothing -> returnRn decls_map; -- No bindings
273 getDeclSysBinders new_name decl `thenRn` \ sys_bndrs ->
275 main_name = availName avail
276 new_decls_map = foldl add_decl decls_map
277 [ (name, (version,avail,decl',name==main_name))
278 | name <- sys_bndrs ++ availNames avail]
279 add_decl decls_map (name, stuff)
280 = WARN( name `elemNameEnv` decls_map, ppr name )
281 addToNameEnv decls_map name stuff
283 returnRn new_decls_map
286 new_name rdr_name loc = newImportedGlobalFromRdrName rdr_name
288 If a signature decl is being loaded, and optIgnoreIfacePragmas is on,
289 we toss away unfolding information.
291 Also, if the signature is loaded from a module we're importing from source,
292 we do the same. This is to avoid situations when compiling a pair of mutually
293 recursive modules, peering at unfolding info in the interface file of the other,
294 e.g., you compile A, it looks at B's interface file and may as a result change
295 its interface file. Hence, B is recompiled, maybe changing its interface file,
296 which will the unfolding info used in A to become invalid. Simple way out is to
297 just ignore unfolding info.
299 [Jan 99: I junked the second test above. If we're importing from an hi-boot
300 file there isn't going to *be* any pragma info. Maybe the above comment
301 dates from a time where we picked up a .hi file first if it existed?]
305 SigD (IfaceSig name tp ls loc) | opt_IgnoreIfacePragmas ->
306 SigD (IfaceSig name tp [] loc)
309 loadInstDecl :: Bag IfaceInst
311 -> RnMG (Bag IfaceInst)
312 loadInstDecl insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
314 -- Find out what type constructors and classes are "gates" for the
315 -- instance declaration. If all these "gates" are slurped in then
316 -- we should slurp the instance decl too.
318 -- We *don't* want to count names in the context part as gates, though.
320 -- instance Foo a => Baz (T a) where ...
322 -- Here the gates are Baz and T, but *not* Foo.
324 munged_inst_ty = case inst_ty of
325 HsForAllTy tvs cxt ty -> HsForAllTy tvs [] ty
328 -- We find the gates by renaming the instance type with in a
329 -- and returning the free variables of the type
330 initRnMS emptyRnEnv vanillaInterfaceMode (
331 discardOccurrencesRn (rnHsSigType (text "an instance decl") munged_inst_ty)
332 ) `thenRn` \ (_, gate_names) ->
333 getModuleRn `thenRn` \ mod_name ->
334 returnRn (((mod_name, decl), gate_names) `consBag` insts)
336 vanillaInterfaceMode = InterfaceMode Compulsory
340 %********************************************************
342 \subsection{Loading usage information}
344 %********************************************************
347 checkUpToDate :: Module -> RnMG Bool -- True <=> no need to recompile
348 checkUpToDate mod_name
349 = findAndReadIface doc_str mod_name `thenRn` \ read_result ->
351 -- CHECK WHETHER WE HAVE IT ALREADY
353 Nothing -> -- Old interface file not found, so we'd better bail out
354 traceRn (sep [ptext SLIT("Didnt find old iface"),
355 pprModule mod_name]) `thenRn_`
358 Just (ParsedIface _ _ usages _ _ _ _)
359 -> -- Found it, so now check it
362 -- Only look in current directory, with suffix .hi
363 doc_str = sep [ptext SLIT("need usage info from"), pprModule mod_name]
365 checkModUsage [] = returnRn True -- Yes! Everything is up to date!
367 checkModUsage ((mod, old_mod_vers, whats_imported) : rest)
368 = loadInterface doc_str mod `thenRn` \ ifaces ->
370 maybe_new_mod_vers = lookupFM (iModMap ifaces) mod
371 Just (_, new_mod_vers, _) = maybe_new_mod_vers
373 -- If we can't find a version number for the old module then
374 -- bail out saying things aren't up to date
375 if not (maybeToBool maybe_new_mod_vers) then
376 traceRn (sep [ptext SLIT("Can't find version number for module"), pprModule mod]) `thenRn_`
380 -- If the module version hasn't changed, just move on
381 if new_mod_vers == old_mod_vers then
382 traceRn (sep [ptext SLIT("Module version unchanged:"), pprModule mod]) `thenRn_`
385 traceRn (sep [ptext SLIT("Module version has changed:"), pprModule mod]) `thenRn_`
387 -- Module version changed, so check entities inside
389 -- If the usage info wants to say "I imported everything from this module"
390 -- it does so by making whats_imported equal to Everything
391 -- In that case, we must recompile
392 case whats_imported of {
393 Everything -> traceRn (ptext SLIT("...and I needed the whole module")) `thenRn_`
394 returnRn False; -- Bale out
396 Specifically old_local_vers ->
398 -- Non-empty usage list, so check item by item
399 checkEntityUsage mod (iDecls ifaces) old_local_vers `thenRn` \ up_to_date ->
401 traceRn (ptext SLIT("...but the bits I use haven't.")) `thenRn_`
402 checkModUsage rest -- This one's ok, so check the rest
404 returnRn False -- This one failed, so just bail out now
407 doc_str = sep [ptext SLIT("need version info for"), pprModule mod]
410 checkEntityUsage mod decls []
411 = returnRn True -- Yes! All up to date!
413 checkEntityUsage mod decls ((occ_name,old_vers) : rest)
414 = newImportedGlobalName mod occ_name `thenRn` \ name ->
415 case lookupNameEnv decls name of
417 Nothing -> -- We used it before, but it ain't there now
418 putDocRn (sep [ptext SLIT("No longer exported:"), ppr name]) `thenRn_`
421 Just (new_vers,_,_,_) -- It's there, but is it up to date?
422 | new_vers == old_vers
423 -- Up to date, so check the rest
424 -> checkEntityUsage mod decls rest
427 -- Out of date, so bale out
428 -> putDocRn (sep [ptext SLIT("Out of date:"), ppr name]) `thenRn_`
433 %*********************************************************
435 \subsection{Getting in a declaration}
437 %*********************************************************
440 importDecl :: Occurrence -> RnMode -> RnMG (Maybe RdrNameHsDecl)
441 -- Returns Nothing for a wired-in or already-slurped decl
443 importDecl (name, loc) mode
444 = checkSlurped name `thenRn` \ already_slurped ->
445 if already_slurped then
446 -- traceRn (sep [text "Already slurped:", ppr name]) `thenRn_`
447 returnRn Nothing -- Already dealt with
449 if isWiredInName name then
450 getWiredInDecl name mode
452 getIfacesRn `thenRn` \ ifaces ->
454 mod = nameModule name
456 if mod == iMod ifaces then -- Don't bring in decls from
457 addWarnRn (importDeclWarn mod name loc) `thenRn_`
458 -- pprTrace "importDecl wierdness:" (ppr name) $
459 returnRn Nothing -- the renamed module's own interface file
462 getNonWiredInDecl name loc mode
466 getNonWiredInDecl :: Name -> SrcLoc -> RnMode -> RnMG (Maybe RdrNameHsDecl)
467 getNonWiredInDecl needed_name loc mode
468 = traceRn doc_str `thenRn_`
469 loadHomeInterface doc_str needed_name `thenRn` \ ifaces ->
470 case lookupNameEnv (iDecls ifaces) needed_name of
472 -- Special case for data/newtype type declarations
473 Just (version, avail, TyClD tycl_decl, _) | isDataDecl tycl_decl
474 -> getNonWiredDataDecl needed_name version avail tycl_decl `thenRn` \ (avail', maybe_decl) ->
475 recordSlurp (Just version) necessity avail' `thenRn_`
478 Just (version,avail,decl,_)
479 -> recordSlurp (Just version) necessity avail `thenRn_`
482 Nothing -> -- Can happen legitimately for "Optional" occurrences
484 Optional -> addWarnRn (getDeclWarn needed_name loc);
485 other -> addErrRn (getDeclErr needed_name loc)
489 necessity = modeToNecessity mode
490 doc_str = sep [ptext SLIT("need decl for"), ppr needed_name, ptext SLIT("needed at"), ppr loc]
493 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
494 It behaves exactly as if the wired in decl were actually in an interface file.
497 * if the wired-in name is a data type constructor or a data constructor,
498 it brings in the type constructor and all the data constructors; and
499 marks as "occurrences" any free vars of the data con.
501 * similarly for synonum type constructor
503 * if the wired-in name is another wired-in Id, it marks as "occurrences"
504 the free vars of the Id's type.
506 * it loads the interface file for the wired-in thing for the
507 sole purpose of making sure that its instance declarations are available
509 All this is necessary so that we know all types that are "in play", so
510 that we know just what instances to bring into scope.
513 getWiredInDecl name mode
514 = setModuleRn mod_name (
515 initRnMS emptyRnEnv new_mode get_wired
516 ) `thenRn` \ avail ->
517 recordSlurp Nothing necessity avail `thenRn_`
519 -- Force in the home module in case it has instance decls for
520 -- the thing we are interested in.
522 -- Mini hack 1: no point for non-tycons/class; and if we
523 -- do this we find PrelNum trying to import PackedString,
524 -- because PrelBase's .hi file mentions PackedString.unpackString
525 -- But PackedString.hi isn't built by that point!
527 -- Mini hack 2; GHC is guaranteed not to have
528 -- instance decls, so it's a waste of time to read it
530 -- NB: We *must* look at the availName of the slurped avail,
531 -- not the name passed to getWiredInDecl! Why? Because if a data constructor
532 -- or class op is passed to getWiredInDecl we'll pull in the whole data/class
533 -- decl, and recordSlurp will record that fact. But since the data constructor
534 -- isn't a tycon/class we won't force in the home module. And even if the
535 -- type constructor/class comes along later, loadDecl will say that it's already
536 -- been slurped, so getWiredInDecl won't even be called. Pretty obscure bug, this was.
538 main_name = availName avail
539 main_is_tc = case avail of { AvailTC _ _ -> True; Avail _ -> False }
540 mod = nameModule main_name
541 doc_str = sep [ptext SLIT("need home module for wired in thing"), ppr name]
543 (if not main_is_tc || mod == pREL_GHC then
546 loadHomeInterface doc_str main_name `thenRn_`
550 returnRn Nothing -- No declaration to process further
552 necessity = modeToNecessity mode
553 new_mode = case mode of
554 InterfaceMode _ -> mode
555 SourceMode -> vanillaInterfaceMode
557 get_wired | is_tycon -- ... a type constructor
558 = get_wired_tycon the_tycon
560 | maybeToBool maybe_data_con -- ... a wired-in data constructor
561 = get_wired_tycon (dataConTyCon data_con)
563 | otherwise -- ... a wired-in non data-constructor
564 = get_wired_id the_id
566 mod_name = nameModule name
567 maybe_wired_in_tycon = maybeWiredInTyConName name
568 is_tycon = maybeToBool maybe_wired_in_tycon
569 maybe_wired_in_id = maybeWiredInIdName name
570 Just the_tycon = maybe_wired_in_tycon
571 Just the_id = maybe_wired_in_id
572 maybe_data_con = isDataConId_maybe the_id
573 Just data_con = maybe_data_con
577 = addImplicitOccsRn id_mentions `thenRn_`
578 returnRn (Avail (getName id))
580 id_mentions = nameSetToList (namesOfType ty)
583 get_wired_tycon tycon
585 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
586 returnRn (AvailTC tc_name [tc_name])
588 tc_name = getName tycon
589 (tyvars,ty) = getSynTyConDefn tycon
590 mentioned = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
592 get_wired_tycon tycon
593 | otherwise -- data or newtype
594 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
595 returnRn (AvailTC tycon_name (tycon_name : map getName data_cons))
597 tycon_name = getName tycon
598 data_cons = tyConDataCons tycon
599 mentioned = foldr (unionNameSets . namesOfType . dataConType) emptyNameSet data_cons
604 %*********************************************************
606 \subsection{Getting what a module exports}
608 %*********************************************************
611 getInterfaceExports :: Module -> RnMG Avails
612 getInterfaceExports mod
613 = loadInterface doc_str mod `thenRn` \ ifaces ->
614 case lookupFM (iModMap ifaces) mod of
615 Nothing -> -- Not there; it must be that the interface file wasn't found;
616 -- the error will have been reported already.
617 -- (Actually loadInterface should put the empty export env in there
618 -- anyway, but this does no harm.)
621 Just (_, _, avails) -> returnRn avails
623 doc_str = sep [pprModule mod, ptext SLIT("is directly imported")]
627 %*********************************************************
629 \subsection{Data type declarations are handled specially}
631 %*********************************************************
633 Data type declarations get special treatment. If we import a data type decl
634 with all its constructors, we end up importing all the types mentioned in
635 the constructors' signatures, and hence {\em their} data type decls, and so on.
636 In effect, we get the transitive closure of data type decls. Worse, this drags
637 in tons on instance decls, and their unfoldings, and so on.
639 If only the type constructor is mentioned, then all this is a waste of time.
640 If any of the data constructors are mentioned then we really have to
641 drag in the whole declaration.
643 So when we import the type constructor for a @data@ or @newtype@ decl, we
644 put it in the "deferred data/newtype decl" pile in Ifaces. Right at the end
645 we slurp these decls, if they havn't already been dragged in by an occurrence
649 getNonWiredDataDecl needed_name
651 avail@(AvailTC tycon_name _)
652 ty_decl@(TyData new_or_data context tycon tyvars condecls derivings pragmas src_loc)
653 | needed_name == tycon_name
655 -- don't prune newtypes, as the code generator may
656 -- want to peer inside a newtype type constructor
657 -- (ClosureInfo.fun_result_ty is the culprit.)
658 && not (new_or_data == NewType)
659 && not (nameUnique needed_name `elem` cCallishTyKeys)
660 -- Hack! Don't prune these tycons whose constructors
661 -- the desugarer must be able to see when desugaring
664 = -- Need the type constructor; so put it in the deferred set for now
665 getIfacesRn `thenRn` \ ifaces ->
667 deferred_data_decls = iDefData ifaces
668 new_ifaces = ifaces {iDefData = new_deferred_data_decls}
670 no_constr_ty_decl = TyData new_or_data [] tycon tyvars [] derivings pragmas src_loc
671 new_deferred_data_decls = addToNameEnv deferred_data_decls tycon_name
672 (nameModule tycon_name, no_constr_ty_decl)
673 -- Nota bene: we nuke both the constructors and the context in the deferred decl.
674 -- If we don't nuke the context then renaming the deferred data decls can give
675 -- new unresolved names (for the classes). This could be handled, but there's
676 -- no point. If the data type is completely abstract then we aren't interested
679 setIfacesRn new_ifaces `thenRn_`
680 returnRn (AvailTC tycon_name [tycon_name], Nothing)
683 = -- Need a data constructor, so delete the data decl from the deferred set if it's there
684 getIfacesRn `thenRn` \ ifaces ->
686 deferred_data_decls = iDefData ifaces
687 new_ifaces = ifaces {iDefData = new_deferred_data_decls}
689 new_deferred_data_decls = delFromNameEnv deferred_data_decls tycon_name
691 setIfacesRn new_ifaces `thenRn_`
692 returnRn (avail, Just (TyClD ty_decl))
696 getDeferredDataDecls :: RnMG [(Module, RdrNameTyClDecl)]
698 = getIfacesRn `thenRn` \ ifaces ->
700 deferred_list = nameEnvElts (iDefData ifaces)
701 trace_msg = hang (text "Slurping abstract data/newtype decls for: ")
702 4 (ppr (map fst deferred_list))
704 traceRn trace_msg `thenRn_`
705 returnRn deferred_list
709 %*********************************************************
711 \subsection{Instance declarations are handled specially}
713 %*********************************************************
716 getImportedInstDecls :: RnMG [(Module,RdrNameInstDecl)]
718 = -- First load any special-instance modules that aren't aready loaded
719 getSpecialInstModules `thenRn` \ inst_mods ->
720 mapRn load_it inst_mods `thenRn_`
722 -- Now we're ready to grab the instance declarations
723 -- Find the un-gated ones and return them,
724 -- removing them from the bag kept in Ifaces
725 getIfacesRn `thenRn` \ ifaces ->
727 (insts, tycls_names) = iDefInsts ifaces
729 -- An instance decl is ungated if all its gates have been slurped
730 select_ungated :: IfaceInst -- A gated inst decl
732 -> ([(Module, RdrNameInstDecl)], [IfaceInst]) -- Accumulator
734 -> ([(Module, RdrNameInstDecl)], -- The ungated ones
735 [IfaceInst]) -- Still gated, but with
737 select_ungated (decl,gates) (ungated_decls, gated_decls)
738 | isEmptyNameSet remaining_gates
739 = (decl : ungated_decls, gated_decls)
741 = (ungated_decls, (decl, remaining_gates) : gated_decls)
743 remaining_gates = gates `minusNameSet` tycls_names
745 (un_gated_insts, still_gated_insts) = foldrBag select_ungated ([], []) insts
747 new_ifaces = ifaces {iDefInsts = (listToBag still_gated_insts, tycls_names)}
748 -- NB: don't throw away tycls_names;
749 -- we may comre across more instance decls
751 traceRn (sep [text "getInstDecls:", fsep (map ppr (nameSetToList tycls_names))]) `thenRn_`
752 setIfacesRn new_ifaces `thenRn_`
753 returnRn un_gated_insts
755 load_it mod = loadInterface (doc_str mod) mod
756 doc_str mod = sep [pprModule mod, ptext SLIT("is a special-instance module")]
759 getSpecialInstModules :: RnMG [Module]
760 getSpecialInstModules
761 = getIfacesRn `thenRn` \ ifaces ->
762 returnRn (iInstMods ifaces)
764 getImportedFixities :: RnMG FixityEnv
766 = getIfacesRn `thenRn` \ ifaces ->
767 returnRn (iFixes ifaces)
771 %*********************************************************
773 \subsection{Keeping track of what we've slurped, and version numbers}
775 %*********************************************************
777 getImportVersions figures out what the "usage information" for this moudule is;
778 that is, what it must record in its interface file as the things it uses.
780 - anything reachable from its body code
781 - any module exported with a "module Foo".
783 Why the latter? Because if Foo changes then this module's export list
784 will change, so we must recompile this module at least as far as
785 making a new interface file --- but in practice that means complete
789 module A( f, g ) where module B( f ) where
790 import B( f ) f = h 3
793 Should we record B.f in A's usages? In fact we don't. Certainly, if
794 anything about B.f changes than anyone who imports A should be recompiled;
795 they'll get an early exit if they don't use B.f. However, even if B.f
796 doesn't change at all, B.h may do so, and this change may not be reflected
797 in f's version number. So there are two things going on when compiling module A:
799 1. Are A.o and A.hi correct? Then we can bale out early.
800 2. Should modules that import A be recompiled?
802 For (1) it is slightly harmful to record B.f in A's usages, because a change in
803 B.f's version will provoke full recompilation of A, producing an identical A.o,
804 and A.hi differing only in its usage-version of B.f (which isn't used by any importer).
806 For (2), because of the tricky B.h question above, we ensure that A.hi is touched
807 (even if identical to its previous version) if A's recompilation was triggered by
808 an imported .hi file date change. Given that, there's no need to record B.f in
811 On the other hand, if A exports "module B" then we *do* count module B among
812 A's usages, because we must recompile A to ensure that A.hi changes appropriately.
815 getImportVersions :: Module -- Name of this module
816 -> Maybe [IE any] -- Export list for this module
817 -> RnMG (VersionInfo Name) -- Version info for these names
819 getImportVersions this_mod exports
820 = getIfacesRn `thenRn` \ ifaces ->
822 mod_map = iModMap ifaces
823 imp_names = iVSlurp ifaces
825 -- mv_map groups together all the things imported from a particular module.
826 mv_map, mv_map_mod :: FiniteMap Module (WhatsImported Name)
828 mv_map_mod = foldl add_mod emptyFM export_mods
829 -- mv_map_mod records all the modules that have a "module M"
830 -- in this module's export list with an "Everything"
832 mv_map = foldl add_mv mv_map_mod imp_names
833 -- mv_map adds the version numbers of things exported individually
835 mk_version_info (mod, local_versions)
836 = case lookupFM mod_map mod of
837 Just (hif, version, _) -> (mod, version, local_versions)
839 returnRn (map mk_version_info (fmToList mv_map))
841 export_mods = case exports of
843 Just es -> [mod | IEModuleContents mod <- es, mod /= this_mod]
845 add_mv mv_map v@(name, version)
846 = addToFM_C add_item mv_map mod (Specifically [v])
848 mod = nameModule name
850 add_item Everything _ = Everything
851 add_item (Specifically xs) _ = Specifically (v:xs)
853 add_mod mv_map mod = addToFM mv_map mod Everything
858 = getIfacesRn `thenRn` \ ifaces ->
859 returnRn (name `elemNameSet` iSlurp ifaces)
861 getSlurpedNames :: RnMG NameSet
863 = getIfacesRn `thenRn` \ ifaces ->
864 returnRn (iSlurp ifaces)
866 recordSlurp maybe_version necessity avail
867 = {- traceRn (hsep [text "Record slurp:", pprAvail avail,
868 -- NB PprForDebug prints export flag, which is too
869 -- strict; it's a knot-tied thing in RnNames
870 case necessity of {Compulsory -> text "comp"; Optional -> text "opt" } ]) `thenRn_`
872 getIfacesRn `thenRn` \ ifaces ->
874 Ifaces { iSlurp = slurped_names,
876 iDefInsts = (insts, tycls_names) } = ifaces
878 new_slurped_names = addAvailToNameSet slurped_names avail
880 new_imp_names = case maybe_version of
881 Just version -> (availName avail, version) : imp_names
884 -- Add to the names that will let in instance declarations;
885 -- but only (a) if it's a type/class
886 -- (b) if it's compulsory (unless the test flag opt_PruneInstDecls is off)
887 new_tycls_names = case avail of
888 AvailTC tc _ | not opt_PruneInstDecls ||
889 case necessity of {Optional -> False; Compulsory -> True }
890 -> tycls_names `addOneToNameSet` tc
891 otherwise -> tycls_names
893 new_ifaces = ifaces { iSlurp = new_slurped_names,
894 iVSlurp = new_imp_names,
895 iDefInsts = (insts, new_tycls_names) }
897 setIfacesRn new_ifaces
901 %*********************************************************
903 \subsection{Getting binders out of a declaration}
905 %*********************************************************
907 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
908 It's used for both source code (from @availsFromDecl@) and interface files
911 It doesn't deal with source-code specific things: ValD, DefD. They
912 are handled by the sourc-code specific stuff in RnNames.
915 getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
917 -> RnMG (Maybe AvailInfo)
919 getDeclBinders new_name (TyClD (TyData _ _ tycon _ condecls _ _ src_loc))
920 = new_name tycon src_loc `thenRn` \ tycon_name ->
921 getConFieldNames new_name condecls `thenRn` \ sub_names ->
922 returnRn (Just (AvailTC tycon_name (tycon_name : nub sub_names)))
923 -- The "nub" is because getConFieldNames can legitimately return duplicates,
924 -- when a record declaration has the same field in multiple constructors
926 getDeclBinders new_name (TyClD (TySynonym tycon _ _ src_loc))
927 = new_name tycon src_loc `thenRn` \ tycon_name ->
928 returnRn (Just (AvailTC tycon_name [tycon_name]))
930 getDeclBinders new_name (TyClD (ClassDecl _ cname _ sigs _ _ tname dname src_loc))
931 = new_name cname src_loc `thenRn` \ class_name ->
933 -- Record the names for the class ops
935 -- ignoring fixity declarations
936 nonfix_sigs = nonFixitySigs sigs
938 mapRn (getClassOpNames new_name) nonfix_sigs `thenRn` \ sub_names ->
940 returnRn (Just (AvailTC class_name (class_name : sub_names)))
942 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
943 = new_name var src_loc `thenRn` \ var_name ->
944 returnRn (Just (Avail var_name))
946 getDeclBinders new_name (FixD _) = returnRn Nothing
947 getDeclBinders new_name (ForD _) = returnRn Nothing
948 getDeclBinders new_name (DefD _) = returnRn Nothing
949 getDeclBinders new_name (InstD _) = returnRn Nothing
952 getConFieldNames new_name (ConDecl con _ _ (RecCon fielddecls) src_loc : rest)
953 = mapRn (\n -> new_name n src_loc) (con:fields) `thenRn` \ cfs ->
954 getConFieldNames new_name rest `thenRn` \ ns ->
957 fields = concat (map fst fielddecls)
959 getConFieldNames new_name (ConDecl con _ _ condecl src_loc : rest)
960 = new_name con src_loc `thenRn` \ n ->
963 new_name f src_loc `thenRn` \ new_f ->
965 _ -> returnRn [n]) `thenRn` \ nn ->
966 getConFieldNames new_name rest `thenRn` \ ns ->
969 getConFieldNames new_name [] = returnRn []
971 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
974 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
975 A the moment that's just the tycon and datacon that come with a class decl.
976 They aren'te returned by getDeclBinders because they aren't in scope;
977 but they *should* be put into the DeclsMap of this module.
980 getDeclSysBinders new_name (TyClD (ClassDecl _ cname _ sigs _ _ tname dname src_loc))
981 = new_name dname src_loc `thenRn` \ datacon_name ->
982 new_name tname src_loc `thenRn` \ tycon_name ->
983 returnRn [tycon_name, datacon_name]
985 getDeclSysBinders new_name other_decl
989 %*********************************************************
991 \subsection{Reading an interface file}
993 %*********************************************************
996 findAndReadIface :: SDoc -> Module -> RnMG (Maybe ParsedIface)
997 -- Nothing <=> file not found, or unreadable, or illegible
998 -- Just x <=> successfully found and parsed
1000 findAndReadIface doc_str mod_name
1001 = traceRn trace_msg `thenRn_`
1002 -- we keep two maps for interface files,
1003 -- one for 'normal' ones, the other for .hi-boot files,
1004 -- hence the need to signal which kind we're interested.
1005 getModuleHiMap from_hi_boot `thenRn` \ himap ->
1006 case (lookupFM himap (moduleString mod_name)) of
1008 Just fpath -> readIface fpath
1009 -- Hack alert! When compiling PrelBase we have to load the
1010 -- decls for packCString# and friends; they are 'thin-air' Ids
1011 -- (see PrelInfo.lhs). So if we don't find the HiFile we quietly
1012 -- look for a .hi-boot file instead, and use that
1013 Nothing | not from_hi_boot && mod_name `elem` thinAirModules
1014 -> findAndReadIface doc_str (mkBootModule mod_name)
1016 -> traceRn (ptext SLIT("...failed")) `thenRn_`
1019 hif = moduleIfaceFlavour mod_name
1020 from_hi_boot = bootFlavour hif
1022 trace_msg = sep [hsep [ptext SLIT("Reading"),
1023 if from_hi_boot then ptext SLIT("[boot]") else empty,
1024 ptext SLIT("interface for"),
1025 pprModule mod_name <> semi],
1026 nest 4 (ptext SLIT("reason:") <+> doc_str)]
1029 @readIface@ tries just the one file.
1032 readIface :: String -> RnMG (Maybe ParsedIface)
1033 -- Nothing <=> file not found, or unreadable, or illegible
1034 -- Just x <=> successfully found and parsed
1036 = ioToRnMG (hGetStringBuffer file_path) `thenRn` \ read_result ->
1039 case parseIface contents (mkSrcLoc (mkFastString file_path) 1) of
1040 Failed err -> failWithRn Nothing err
1041 Succeeded (PIface iface) ->
1042 if opt_D_show_rn_imports then
1043 putDocRn (hcat[ptext SLIT("Read "), text file_path]) `thenRn_`
1044 returnRn (Just iface)
1046 returnRn (Just iface)
1049 if isDoesNotExistError err then
1052 failWithRn Nothing (cannaeReadFile file_path err)
1055 %*********************************************************
1059 %*********************************************************
1061 @mkSearchPath@ takes a string consisting of a colon-separated list
1062 of directories and corresponding suffixes, and turns it into a list
1063 of (directory, suffix) pairs. For example:
1066 mkSearchPath "foo%.hi:.%.p_hi:baz%.mc_hi"
1067 = [("foo",".hi"),( ".", ".p_hi"), ("baz",".mc_hi")]
1071 mkSearchPath :: Maybe String -> SearchPath
1072 mkSearchPath Nothing = [(".",".hi")]
1073 mkSearchPath (Just s)
1078 case span (/= '%') s of
1080 case span (/= ':') rs of
1081 (hisuf,_:rest) -> (dir,hisuf):go rest
1082 (hisuf,[]) -> [(dir,hisuf)]
1085 %*********************************************************
1089 %*********************************************************
1093 = hcat [ptext SLIT("Could not find valid interface file "),
1094 quotes (pprModule filename)]
1096 cannaeReadFile file err
1097 = hcat [ptext SLIT("Failed in reading file: "),
1099 ptext SLIT("; error="),
1103 = sep [ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name),
1104 ptext SLIT("needed at") <+> ppr loc]
1106 getDeclWarn name loc
1107 = sep [ptext SLIT("Failed to find (optional) interface decl for") <+> quotes (ppr name),
1108 ptext SLIT("desired at") <+> ppr loc]
1110 importDeclWarn mod name loc
1111 = sep [ptext SLIT("Compiler tried to import decl from interface file with same name as module."),
1112 ptext SLIT("(possible cause: module name clashes with interface file already in scope.)")
1114 hsep [ptext SLIT("Interface:"), quotes (pprModule mod), comma, ptext SLIT("name:"), quotes (ppr name),
1115 comma, ptext SLIT("desired at:"), ppr loc