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
30 import BasicTypes ( Version, NewOrData(..), IfaceFlavour(..) )
31 import RdrHsSyn ( RdrNameHsDecl, RdrNameInstDecl, RdrNameTyClDecl,
32 RdrName(..), rdrNameOcc
34 import RnEnv ( newImportedGlobalName, addImplicitOccsRn, pprAvail,
35 availName, availNames, addAvailToNameSet, ifaceFlavour
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-}, OccName,
47 nameModule, moduleString, pprModule, isLocallyDefined,
48 isWiredInName, maybeWiredInTyConName, pprModule,
49 maybeWiredInIdName, nameUnique, NamedThing(..)
52 import Id ( idType, isDataConId_maybe )
53 import DataCon ( dataConTyCon, dataConType )
54 import TyCon ( TyCon, tyConDataCons, isSynTyCon, getSynTyConDefn )
55 import Type ( namesOfType )
57 import SrcLoc ( mkSrcLoc, SrcLoc )
58 import PrelMods ( pREL_GHC )
59 import PrelInfo ( cCallishTyKeys, thinAirModules )
61 import Maybes ( MaybeErr(..), maybeToBool )
62 import ListSetOps ( unionLists )
64 import Unique ( Unique )
65 import StringBuffer ( StringBuffer, hGetStringBuffer )
66 import FastString ( mkFastString )
69 import IO ( isDoesNotExistError )
76 %*********************************************************
78 \subsection{Statistics}
80 %*********************************************************
83 getRnStats :: [RenamedHsDecl] -> RnMG SDoc
85 = getIfacesRn `thenRn` \ ifaces ->
87 n_mods = sizeFM (iModMap ifaces)
89 decls_imported = filter is_imported_decl all_decls
91 decls_read = [decl | (_, avail, decl, True) <- nameEnvElts (iDecls ifaces),
92 -- Data, newtype, and class decls are in the decls_fm
93 -- under multiple names; the tycon/class, and each
94 -- constructor/class op too.
95 -- The 'True' selects just the 'main' decl
96 not (isLocallyDefined (availName avail))
99 (cd_rd, dd_rd, add_rd, nd_rd, and_rd, sd_rd, vd_rd, _) = count_decls decls_read
100 (cd_sp, dd_sp, add_sp, nd_sp, and_sp, sd_sp, vd_sp, id_sp) = count_decls decls_imported
102 (unslurped_insts, _) = iDefInsts ifaces
103 inst_decls_unslurped = length (bagToList unslurped_insts)
104 inst_decls_read = id_sp + inst_decls_unslurped
107 [int n_mods <> text " interfaces read",
108 hsep [ int cd_sp, text "class decls imported, out of",
109 int cd_rd, text "read"],
110 hsep [ int dd_sp, text "data decls imported (of which", int add_sp,
111 text "abstractly), out of",
112 int dd_rd, text "read"],
113 hsep [ int nd_sp, text "newtype decls imported (of which", int and_sp,
114 text "abstractly), out of",
115 int nd_rd, text "read"],
116 hsep [int sd_sp, text "type synonym decls imported, out of",
117 int sd_rd, text "read"],
118 hsep [int vd_sp, text "value signatures imported, out of",
119 int vd_rd, text "read"],
120 hsep [int id_sp, text "instance decls imported, out of",
121 int inst_decls_read, text "read"]
124 returnRn (hcat [text "Renamer stats: ", stats])
126 is_imported_decl (DefD _) = False
127 is_imported_decl (ValD _) = False
128 is_imported_decl decl = not (isLocallyDefined (hsDeclName decl))
131 = -- pprTrace "count_decls" (ppr decls
136 -- ppr imported_decls
139 data_decls, abstract_data_decls,
140 newtype_decls, abstract_newtype_decls,
145 tycl_decls = [d | TyClD d <- decls]
146 (class_decls, data_decls, newtype_decls, syn_decls) = countTyClDecls tycl_decls
147 abstract_data_decls = length [() | TyData DataType _ _ _ [] _ _ _ <- tycl_decls]
148 abstract_newtype_decls = length [() | TyData NewType _ _ _ [] _ _ _ <- tycl_decls]
150 val_decls = length [() | SigD _ <- decls]
151 inst_decls = length [() | InstD _ <- decls]
155 %*********************************************************
157 \subsection{Loading a new interface file}
159 %*********************************************************
162 loadHomeInterface :: SDoc -> Name -> RnMG Ifaces
163 loadHomeInterface doc_str name
164 = loadInterface doc_str (nameModule name) (ifaceFlavour name)
166 loadInterface :: SDoc -> Module -> IfaceFlavour -> RnMG Ifaces
167 loadInterface doc_str load_mod as_source
168 = getIfacesRn `thenRn` \ ifaces ->
170 this_mod = iMod ifaces
171 mod_map = iModMap ifaces
172 (insts, tycls_names) = iDefInsts ifaces
174 -- CHECK WHETHER WE HAVE IT ALREADY
175 case lookupFM mod_map load_mod of {
176 Just (hif, _, _) | hif `as_good_as` as_source
177 -> -- Already in the cache; don't re-read it
181 -- READ THE MODULE IN
182 findAndReadIface doc_str load_mod as_source `thenRn` \ read_result ->
183 case read_result of {
184 -- Check for not found
185 Nothing -> -- Not found, so add an empty export env to the Ifaces map
186 -- so that we don't look again
188 new_mod_map = addToFM mod_map load_mod (HiFile, 0, [])
189 new_ifaces = ifaces { iModMap = new_mod_map }
191 setIfacesRn new_ifaces `thenRn_`
192 failWithRn new_ifaces (noIfaceErr load_mod) ;
195 Just (ParsedIface _ mod_vers usages exports rd_inst_mods rd_decls rd_insts) ->
197 -- LOAD IT INTO Ifaces
198 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
199 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
200 -- If we do loadExport first the wrong info gets into the cache (unless we
201 -- explicitly tag each export which seems a bit of a bore)
202 foldlRn (loadDecl load_mod as_source)
203 (iDecls ifaces) rd_decls `thenRn` \ new_decls ->
204 foldlRn (loadFixDecl load_mod as_source)
205 (iFixes ifaces) rd_decls `thenRn` \ new_fixities ->
206 mapRn loadExport exports `thenRn` \ avails_s ->
207 foldlRn (loadInstDecl load_mod) insts rd_insts `thenRn` \ new_insts ->
209 mod_details = (as_source, mod_vers, concat avails_s)
211 -- Exclude this module from the "special-inst" modules
212 new_inst_mods = iInstMods ifaces `unionLists` (filter (/= this_mod) rd_inst_mods)
214 new_ifaces = ifaces { iModMap = addToFM mod_map load_mod mod_details,
216 iFixes = new_fixities,
217 iDefInsts = (new_insts, tycls_names),
218 iInstMods = new_inst_mods }
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 :: ExportItem -> RnMG [AvailInfo]
230 loadExport (mod, hif, entities)
231 = mapRn load_entity entities
233 new_name occ = newImportedGlobalName 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)
244 loadFixDecl :: Module -> IfaceFlavour -> FixityEnv
245 -> (Version, RdrNameHsDecl)
247 loadFixDecl mod as_source fixity_env (version, FixD (FixitySig rdr_name fixity loc))
248 = -- Ignore the version; when the fixity changes the version of
249 -- its 'host' entity changes, so we don't need a separate version
250 -- number for fixities
251 new_implicit_name mod as_source rdr_name `thenRn` \ name ->
253 new_fixity_env = addToNameEnv fixity_env name (FixitySig name fixity loc)
255 returnRn new_fixity_env
257 -- Ignore the other sorts of decl
258 loadFixDecl mod as_source fixity_env other_decl = returnRn fixity_env
260 loadDecl :: Module -> IfaceFlavour -> DeclsMap
261 -> (Version, RdrNameHsDecl)
264 loadDecl mod as_source decls_map (version, decl)
265 = getDeclBinders new_name decl `thenRn` \ avail ->
266 getDeclSysBinders new_name decl `thenRn` \ sys_bndrs ->
268 main_name = availName avail
269 new_decls_map = foldl add_decl decls_map
270 [ (name, (version,avail,decl',name==main_name))
271 | name <- sys_bndrs ++ availNames avail]
272 add_decl decls_map (name, stuff)
273 = ASSERT2( not (name `elemNameEnv` decls_map), ppr name )
274 addToNameEnv decls_map name stuff
276 returnRn new_decls_map
278 new_name rdr_name loc = new_implicit_name mod as_source rdr_name
280 If a signature decl is being loaded, and optIgnoreIfacePragmas is on,
281 we toss away unfolding information.
283 Also, if the signature is loaded from a module we're importing from source,
284 we do the same. This is to avoid situations when compiling a pair of mutually
285 recursive modules, peering at unfolding info in the interface file of the other,
286 e.g., you compile A, it looks at B's interface file and may as a result change
287 its interface file. Hence, B is recompiled, maybe changing its interface file,
288 which will the unfolding info used in A to become invalid. Simple way out is to
289 just ignore unfolding info.
293 SigD (IfaceSig name tp ls loc) | from_hi_boot || opt_IgnoreIfacePragmas ->
294 SigD (IfaceSig name tp [] loc)
297 from_hi_boot = case as_source of
301 new_implicit_name mod as_source rdr_name
302 = newImportedGlobalName mod (rdrNameOcc rdr_name) as_source
304 loadInstDecl :: Module
307 -> RnMG (Bag IfaceInst)
308 loadInstDecl mod_name insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
310 -- Find out what type constructors and classes are "gates" for the
311 -- instance declaration. If all these "gates" are slurped in then
312 -- we should slurp the instance decl too.
314 -- We *don't* want to count names in the context part as gates, though.
316 -- instance Foo a => Baz (T a) where ...
318 -- Here the gates are Baz and T, but *not* Foo.
320 munged_inst_ty = case inst_ty of
321 HsForAllTy tvs cxt ty -> HsForAllTy tvs [] ty
324 -- We find the gates by renaming the instance type with in a
325 -- and returning the free variables of the type
326 initRnMS emptyRnEnv mod_name vanillaInterfaceMode (
327 discardOccurrencesRn (rnHsSigType (text "an instance decl") munged_inst_ty)
328 ) `thenRn` \ (_, gate_names) ->
329 returnRn (((mod_name, decl), gate_names) `consBag` insts)
331 vanillaInterfaceMode = InterfaceMode Compulsory
335 %********************************************************
337 \subsection{Loading usage information}
339 %********************************************************
342 checkUpToDate :: Module -> RnMG Bool -- True <=> no need to recompile
343 checkUpToDate mod_name
344 = findAndReadIface doc_str mod_name HiFile `thenRn` \ read_result ->
346 -- CHECK WHETHER WE HAVE IT ALREADY
348 Nothing -> -- Old interface file not found, so we'd better bail out
349 traceRn (sep [ptext SLIT("Didnt find old iface"),
350 pprModule mod_name]) `thenRn_`
353 Just (ParsedIface _ _ usages _ _ _ _)
354 -> -- Found it, so now check it
357 -- Only look in current directory, with suffix .hi
358 doc_str = sep [ptext SLIT("need usage info from"), pprModule mod_name]
360 checkModUsage [] = returnRn True -- Yes! Everything is up to date!
362 checkModUsage ((mod, hif, old_mod_vers, whats_imported) : rest)
363 = loadInterface doc_str mod hif `thenRn` \ ifaces ->
365 maybe_new_mod_vers = lookupFM (iModMap ifaces) mod
366 Just (_, new_mod_vers, _) = maybe_new_mod_vers
368 -- If we can't find a version number for the old module then
369 -- bail out saying things aren't up to date
370 if not (maybeToBool maybe_new_mod_vers) then
371 traceRn (sep [ptext SLIT("Can't find version number for module"), pprModule mod]) `thenRn_`
375 -- If the module version hasn't changed, just move on
376 if new_mod_vers == old_mod_vers then
377 traceRn (sep [ptext SLIT("Module version unchanged:"), pprModule mod]) `thenRn_`
380 traceRn (sep [ptext SLIT("Module version has changed:"), pprModule mod]) `thenRn_`
382 -- Module version changed, so check entities inside
384 -- If the usage info wants to say "I imported everything from this module"
385 -- it does so by making whats_imported equal to Everything
386 -- In that case, we must recompile
387 case whats_imported of {
388 Everything -> traceRn (ptext SLIT("...and I needed the whole module")) `thenRn_`
389 returnRn False; -- Bale out
391 Specifically old_local_vers ->
393 -- Non-empty usage list, so check item by item
394 checkEntityUsage mod (iDecls ifaces) old_local_vers `thenRn` \ up_to_date ->
396 traceRn (ptext SLIT("...but the bits I use haven't.")) `thenRn_`
397 checkModUsage rest -- This one's ok, so check the rest
399 returnRn False -- This one failed, so just bail out now
402 doc_str = sep [ptext SLIT("need version info for"), pprModule mod]
405 checkEntityUsage mod decls []
406 = returnRn True -- Yes! All up to date!
408 checkEntityUsage mod decls ((occ_name,old_vers) : rest)
409 = newImportedGlobalName mod occ_name HiFile `thenRn` \ name ->
410 case lookupNameEnv decls name of
412 Nothing -> -- We used it before, but it ain't there now
413 putDocRn (sep [ptext SLIT("No longer exported:"), ppr name]) `thenRn_`
416 Just (new_vers,_,_,_) -- It's there, but is it up to date?
417 | new_vers == old_vers
418 -- Up to date, so check the rest
419 -> checkEntityUsage mod decls rest
422 -- Out of date, so bale out
423 -> putDocRn (sep [ptext SLIT("Out of date:"), ppr name]) `thenRn_`
428 %*********************************************************
430 \subsection{Getting in a declaration}
432 %*********************************************************
435 importDecl :: Occurrence -> RnSMode -> RnMG (Maybe RdrNameHsDecl)
436 -- Returns Nothing for a wired-in or already-slurped decl
438 importDecl (name, loc) mode
439 = checkSlurped name `thenRn` \ already_slurped ->
440 if already_slurped then
441 -- traceRn (sep [text "Already slurped:", ppr name]) `thenRn_`
442 returnRn Nothing -- Already dealt with
444 if isWiredInName name then
445 getWiredInDecl name mode
447 getIfacesRn `thenRn` \ ifaces ->
449 mod = nameModule name
451 if mod == iMod ifaces then -- Don't bring in decls from
452 addWarnRn (importDeclWarn mod name loc) `thenRn_`
453 -- pprTrace "importDecl wierdness:" (ppr name) $
454 returnRn Nothing -- the renamed module's own interface file
457 getNonWiredInDecl name loc mode
461 getNonWiredInDecl :: Name -> SrcLoc -> RnSMode -> RnMG (Maybe RdrNameHsDecl)
462 getNonWiredInDecl needed_name loc mode
463 = traceRn doc_str `thenRn_`
464 loadHomeInterface doc_str needed_name `thenRn` \ ifaces ->
465 case lookupNameEnv (iDecls ifaces) needed_name of
467 -- Special case for data/newtype type declarations
468 Just (version, avail, TyClD tycl_decl, _) | isDataDecl tycl_decl
469 -> getNonWiredDataDecl needed_name version avail tycl_decl `thenRn` \ (avail', maybe_decl) ->
470 recordSlurp (Just version) necessity avail' `thenRn_`
473 Just (version,avail,decl,_)
474 -> recordSlurp (Just version) necessity avail `thenRn_`
477 Nothing -> -- Can happen legitimately for "Optional" occurrences
479 Optional -> addWarnRn (getDeclWarn needed_name loc);
480 other -> addErrRn (getDeclErr needed_name loc)
484 necessity = modeToNecessity mode
485 doc_str = sep [ptext SLIT("need decl for"), ppr needed_name, ptext SLIT("needed at"), ppr loc]
488 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
489 It behaves exactly as if the wired in decl were actually in an interface file.
492 * if the wired-in name is a data type constructor or a data constructor,
493 it brings in the type constructor and all the data constructors; and
494 marks as "occurrences" any free vars of the data con.
496 * similarly for synonum type constructor
498 * if the wired-in name is another wired-in Id, it marks as "occurrences"
499 the free vars of the Id's type.
501 * it loads the interface file for the wired-in thing for the
502 sole purpose of making sure that its instance declarations are available
504 All this is necessary so that we know all types that are "in play", so
505 that we know just what instances to bring into scope.
508 getWiredInDecl name mode
509 = initRnMS emptyRnEnv mod_name new_mode
510 get_wired `thenRn` \ avail ->
511 recordSlurp Nothing necessity avail `thenRn_`
513 -- Force in the home module in case it has instance decls for
514 -- the thing we are interested in.
516 -- Mini hack 1: no point for non-tycons/class; and if we
517 -- do this we find PrelNum trying to import PackedString,
518 -- because PrelBase's .hi file mentions PackedString.unpackString
519 -- But PackedString.hi isn't built by that point!
521 -- Mini hack 2; GHC is guaranteed not to have
522 -- instance decls, so it's a waste of time to read it
524 -- NB: We *must* look at the availName of the slurped avail,
525 -- not the name passed to getWiredInDecl! Why? Because if a data constructor
526 -- or class op is passed to getWiredInDecl we'll pull in the whole data/class
527 -- decl, and recordSlurp will record that fact. But since the data constructor
528 -- isn't a tycon/class we won't force in the home module. And even if the
529 -- type constructor/class comes along later, loadDecl will say that it's already
530 -- been slurped, so getWiredInDecl won't even be called. Pretty obscure bug, this was.
532 main_name = availName avail
533 main_is_tc = case avail of { AvailTC _ _ -> True; Avail _ -> False }
534 mod = nameModule main_name
535 doc_str = sep [ptext SLIT("need home module for wired in thing"), ppr name]
537 (if not main_is_tc || mod == pREL_GHC then
540 loadHomeInterface doc_str main_name `thenRn_`
544 returnRn Nothing -- No declaration to process further
546 necessity = modeToNecessity mode
547 new_mode = case mode of
548 InterfaceMode _ -> mode
549 SourceMode -> vanillaInterfaceMode
551 get_wired | is_tycon -- ... a type constructor
552 = get_wired_tycon the_tycon
554 | maybeToBool maybe_data_con -- ... a wired-in data constructor
555 = get_wired_tycon (dataConTyCon data_con)
557 | otherwise -- ... a wired-in non data-constructor
558 = get_wired_id the_id
560 mod_name = nameModule name
561 maybe_wired_in_tycon = maybeWiredInTyConName name
562 is_tycon = maybeToBool maybe_wired_in_tycon
563 maybe_wired_in_id = maybeWiredInIdName name
564 Just the_tycon = maybe_wired_in_tycon
565 Just the_id = maybe_wired_in_id
566 maybe_data_con = isDataConId_maybe the_id
567 Just data_con = maybe_data_con
571 = addImplicitOccsRn id_mentions `thenRn_`
572 returnRn (Avail (getName id))
574 id_mentions = nameSetToList (namesOfType ty)
577 get_wired_tycon tycon
579 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
580 returnRn (AvailTC tc_name [tc_name])
582 tc_name = getName tycon
583 (tyvars,ty) = getSynTyConDefn tycon
584 mentioned = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
586 get_wired_tycon tycon
587 | otherwise -- data or newtype
588 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
589 returnRn (AvailTC tycon_name (tycon_name : map getName data_cons))
591 tycon_name = getName tycon
592 data_cons = tyConDataCons tycon
593 mentioned = foldr (unionNameSets . namesOfType . dataConType) emptyNameSet data_cons
598 %*********************************************************
600 \subsection{Getting what a module exports}
602 %*********************************************************
605 getInterfaceExports :: Module -> IfaceFlavour -> RnMG Avails
606 getInterfaceExports mod as_source
607 = loadInterface doc_str mod as_source `thenRn` \ ifaces ->
608 case lookupFM (iModMap ifaces) mod of
609 Nothing -> -- Not there; it must be that the interface file wasn't found;
610 -- the error will have been reported already.
611 -- (Actually loadInterface should put the empty export env in there
612 -- anyway, but this does no harm.)
615 Just (_, _, avails) -> returnRn avails
617 doc_str = sep [pprModule mod, ptext SLIT("is directly imported")]
621 %*********************************************************
623 \subsection{Data type declarations are handled specially}
625 %*********************************************************
627 Data type declarations get special treatment. If we import a data type decl
628 with all its constructors, we end up importing all the types mentioned in
629 the constructors' signatures, and hence {\em their} data type decls, and so on.
630 In effect, we get the transitive closure of data type decls. Worse, this drags
631 in tons on instance decls, and their unfoldings, and so on.
633 If only the type constructor is mentioned, then all this is a waste of time.
634 If any of the data constructors are mentioned then we really have to
635 drag in the whole declaration.
637 So when we import the type constructor for a @data@ or @newtype@ decl, we
638 put it in the "deferred data/newtype decl" pile in Ifaces. Right at the end
639 we slurp these decls, if they havn't already been dragged in by an occurrence
643 getNonWiredDataDecl needed_name
645 avail@(AvailTC tycon_name _)
646 ty_decl@(TyData new_or_data context tycon tyvars condecls derivings pragmas src_loc)
647 | needed_name == tycon_name
649 -- don't prune newtypes, as the code generator may
650 -- want to peer inside a newtype type constructor
651 -- (ClosureInfo.fun_result_ty is the culprit.)
652 && not (new_or_data == NewType)
653 && not (nameUnique needed_name `elem` cCallishTyKeys)
654 -- Hack! Don't prune these tycons whose constructors
655 -- the desugarer must be able to see when desugaring
658 = -- Need the type constructor; so put it in the deferred set for now
659 getIfacesRn `thenRn` \ ifaces ->
661 deferred_data_decls = iDefData ifaces
662 new_ifaces = ifaces {iDefData = new_deferred_data_decls}
664 no_constr_ty_decl = TyData new_or_data [] tycon tyvars [] derivings pragmas src_loc
665 new_deferred_data_decls = addToNameEnv deferred_data_decls tycon_name
666 (nameModule tycon_name, no_constr_ty_decl)
667 -- Nota bene: we nuke both the constructors and the context in the deferred decl.
668 -- If we don't nuke the context then renaming the deferred data decls can give
669 -- new unresolved names (for the classes). This could be handled, but there's
670 -- no point. If the data type is completely abstract then we aren't interested
673 setIfacesRn new_ifaces `thenRn_`
674 returnRn (AvailTC tycon_name [tycon_name], Nothing)
677 = -- Need a data constructor, so delete the data decl from the deferred set if it's there
678 getIfacesRn `thenRn` \ ifaces ->
680 deferred_data_decls = iDefData ifaces
681 new_ifaces = ifaces {iDefData = new_deferred_data_decls}
683 new_deferred_data_decls = delFromNameEnv deferred_data_decls tycon_name
685 setIfacesRn new_ifaces `thenRn_`
686 returnRn (avail, Just (TyClD ty_decl))
690 getDeferredDataDecls :: RnMG [(Module, RdrNameTyClDecl)]
692 = getIfacesRn `thenRn` \ ifaces ->
694 deferred_list = nameEnvElts (iDefData ifaces)
695 trace_msg = hang (text "Slurping abstract data/newtype decls for: ")
696 4 (ppr (map fst deferred_list))
698 traceRn trace_msg `thenRn_`
699 returnRn deferred_list
703 %*********************************************************
705 \subsection{Instance declarations are handled specially}
707 %*********************************************************
710 getImportedInstDecls :: RnMG [(Module,RdrNameInstDecl)]
712 = -- First load any special-instance modules that aren't aready loaded
713 getSpecialInstModules `thenRn` \ inst_mods ->
714 mapRn load_it inst_mods `thenRn_`
716 -- Now we're ready to grab the instance declarations
717 -- Find the un-gated ones and return them,
718 -- removing them from the bag kept in Ifaces
719 getIfacesRn `thenRn` \ ifaces ->
721 (insts, tycls_names) = iDefInsts ifaces
723 -- An instance decl is ungated if all its gates have been slurped
724 select_ungated :: IfaceInst -- A gated inst decl
726 -> ([(Module, RdrNameInstDecl)], [IfaceInst]) -- Accumulator
728 -> ([(Module, RdrNameInstDecl)], -- The ungated ones
729 [IfaceInst]) -- Still gated, but with
731 select_ungated (decl,gates) (ungated_decls, gated_decls)
732 | isEmptyNameSet remaining_gates
733 = (decl : ungated_decls, gated_decls)
735 = (ungated_decls, (decl, remaining_gates) : gated_decls)
737 remaining_gates = gates `minusNameSet` tycls_names
739 (un_gated_insts, still_gated_insts) = foldrBag select_ungated ([], []) insts
741 new_ifaces = ifaces {iDefInsts = (listToBag still_gated_insts, tycls_names)}
742 -- NB: don't throw away tycls_names;
743 -- we may comre across more instance decls
745 traceRn (sep [text "getInstDecls:", fsep (map ppr (nameSetToList tycls_names))]) `thenRn_`
746 setIfacesRn new_ifaces `thenRn_`
747 returnRn un_gated_insts
749 load_it mod = loadInterface (doc_str mod) mod HiFile
750 doc_str mod = sep [pprModule mod, ptext SLIT("is a special-instance module")]
753 getSpecialInstModules :: RnMG [Module]
754 getSpecialInstModules
755 = getIfacesRn `thenRn` \ ifaces ->
756 returnRn (iInstMods ifaces)
758 getImportedFixities :: RnMG FixityEnv
760 = getIfacesRn `thenRn` \ ifaces ->
761 returnRn (iFixes ifaces)
765 %*********************************************************
767 \subsection{Keeping track of what we've slurped, and version numbers}
769 %*********************************************************
771 getImportVersions figures out what the "usage information" for this moudule is;
772 that is, what it must record in its interface file as the things it uses.
774 - anything reachable from its body code
775 - any module exported with a "module Foo".
777 Why the latter? Because if Foo changes then this module's export list
778 will change, so we must recompile this module at least as far as
779 making a new interface file --- but in practice that means complete
783 module A( f, g ) where module B( f ) where
784 import B( f ) f = h 3
787 Should we record B.f in A's usages? In fact we don't. Certainly, if
788 anything about B.f changes than anyone who imports A should be recompiled;
789 they'll get an early exit if they don't use B.f. However, even if B.f
790 doesn't change at all, B.h may do so, and this change may not be reflected
791 in f's version number. So there are two things going on when compiling module A:
793 1. Are A.o and A.hi correct? Then we can bale out early.
794 2. Should modules that import A be recompiled?
796 For (1) it is slightly harmful to record B.f in A's usages, because a change in
797 B.f's version will provoke full recompilation of A, producing an identical A.o,
798 and A.hi differing only in its usage-version of B.f (which isn't used by any importer).
800 For (2), because of the tricky B.h question above, we ensure that A.hi is touched
801 (even if identical to its previous version) if A's recompilation was triggered by
802 an imported .hi file date change. Given that, there's no need to record B.f in
805 On the other hand, if A exports "module B" then we *do* count module B among
806 A's usages, because we must recompile A to ensure that A.hi changes appropriately.
809 getImportVersions :: Module -- Name of this module
810 -> Maybe [IE any] -- Export list for this module
811 -> RnMG (VersionInfo Name) -- Version info for these names
813 getImportVersions this_mod exports
814 = getIfacesRn `thenRn` \ ifaces ->
816 mod_map = iModMap ifaces
817 imp_names = iVSlurp ifaces
819 -- mv_map groups together all the things imported from a particular module.
820 mv_map, mv_map_mod :: FiniteMap Module (WhatsImported Name)
822 mv_map_mod = foldl add_mod emptyFM export_mods
823 -- mv_map_mod records all the modules that have a "module M"
824 -- in this module's export list with an "Everything"
826 mv_map = foldl add_mv mv_map_mod imp_names
827 -- mv_map adds the version numbers of things exported individually
829 mk_version_info (mod, local_versions)
830 = case lookupFM mod_map mod of
831 Just (hif, version, _) -> (mod, hif, version, local_versions)
833 returnRn (map mk_version_info (fmToList mv_map))
835 export_mods = case exports of
837 Just es -> [mod | IEModuleContents mod <- es, mod /= this_mod]
839 add_mv mv_map v@(name, version)
840 = addToFM_C add_item mv_map mod (Specifically [v])
842 mod = nameModule name
844 add_item Everything _ = Everything
845 add_item (Specifically xs) _ = Specifically (v:xs)
847 add_mod mv_map mod = addToFM mv_map mod Everything
852 = getIfacesRn `thenRn` \ ifaces ->
853 returnRn (name `elemNameSet` iSlurp ifaces)
855 getSlurpedNames :: RnMG NameSet
857 = getIfacesRn `thenRn` \ ifaces ->
858 returnRn (iSlurp ifaces)
860 recordSlurp maybe_version necessity avail
861 = {- traceRn (hsep [text "Record slurp:", pprAvail avail,
862 -- NB PprForDebug prints export flag, which is too
863 -- strict; it's a knot-tied thing in RnNames
864 case necessity of {Compulsory -> text "comp"; Optional -> text "opt" } ]) `thenRn_`
866 getIfacesRn `thenRn` \ ifaces ->
868 Ifaces { iSlurp = slurped_names,
870 iDefInsts = (insts, tycls_names) } = ifaces
872 new_slurped_names = addAvailToNameSet slurped_names avail
874 new_imp_names = case maybe_version of
875 Just version -> (availName avail, version) : imp_names
878 -- Add to the names that will let in instance declarations;
879 -- but only (a) if it's a type/class
880 -- (b) if it's compulsory (unless the test flag opt_PruneInstDecls is off)
881 new_tycls_names = case avail of
882 AvailTC tc _ | not opt_PruneInstDecls ||
883 case necessity of {Optional -> False; Compulsory -> True }
884 -> tycls_names `addOneToNameSet` tc
885 otherwise -> tycls_names
887 new_ifaces = ifaces { iSlurp = new_slurped_names,
888 iVSlurp = new_imp_names,
889 iDefInsts = (insts, new_tycls_names) }
891 setIfacesRn new_ifaces
895 %*********************************************************
897 \subsection{Getting binders out of a declaration}
899 %*********************************************************
901 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
902 It's used for both source code (from @availsFromDecl@) and interface files
905 It doesn't deal with source-code specific things: ValD, DefD. They
906 are handled by the sourc-code specific stuff in RnNames.
909 getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
913 getDeclBinders new_name (TyClD (TyData _ _ tycon _ condecls _ _ src_loc))
914 = new_name tycon src_loc `thenRn` \ tycon_name ->
915 getConFieldNames new_name condecls `thenRn` \ sub_names ->
916 returnRn (AvailTC tycon_name (tycon_name : nub sub_names))
917 -- The "nub" is because getConFieldNames can legitimately return duplicates,
918 -- when a record declaration has the same field in multiple constructors
920 getDeclBinders new_name (TyClD (TySynonym tycon _ _ src_loc))
921 = new_name tycon src_loc `thenRn` \ tycon_name ->
922 returnRn (AvailTC tycon_name [tycon_name])
924 getDeclBinders new_name (TyClD (ClassDecl _ cname _ sigs _ _ tname dname src_loc))
925 = new_name cname src_loc `thenRn` \ class_name ->
927 -- Record the names for the class ops
928 mapRn (getClassOpNames new_name) sigs `thenRn` \ sub_names ->
930 returnRn (AvailTC class_name (class_name : sub_names))
932 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
933 = new_name var src_loc `thenRn` \ var_name ->
934 returnRn (Avail var_name)
936 getDeclBinders new_name (FixD _) = returnRn NotAvailable
937 getDeclBinders new_name (ForD _) = returnRn NotAvailable
938 getDeclBinders new_name (DefD _) = returnRn NotAvailable
939 getDeclBinders new_name (InstD _) = returnRn NotAvailable
942 getConFieldNames new_name (ConDecl con _ _ (RecCon fielddecls) src_loc : rest)
943 = mapRn (\n -> new_name n src_loc) (con:fields) `thenRn` \ cfs ->
944 getConFieldNames new_name rest `thenRn` \ ns ->
947 fields = concat (map fst fielddecls)
949 getConFieldNames new_name (ConDecl con _ _ _ src_loc : rest)
950 = new_name con src_loc `thenRn` \ n ->
951 getConFieldNames new_name rest `thenRn` \ ns ->
954 getConFieldNames new_name [] = returnRn []
956 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
959 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
960 A the moment that's just the tycon and datacon that come with a class decl.
961 They aren'te returned by getDeclBinders because they aren't in scope;
962 but they should be put into the DeclsMap of this module.
965 getDeclSysBinders new_name (TyClD (ClassDecl _ cname _ sigs _ _ tname dname src_loc))
966 = new_name dname src_loc `thenRn` \ datacon_name ->
967 new_name tname src_loc `thenRn` \ tycon_name ->
968 returnRn [tycon_name, datacon_name]
970 getDeclSysBinders new_name other_decl
974 %*********************************************************
976 \subsection{Reading an interface file}
978 %*********************************************************
981 findAndReadIface :: SDoc -> Module
983 -> RnMG (Maybe ParsedIface)
984 -- Nothing <=> file not found, or unreadable, or illegible
985 -- Just x <=> successfully found and parsed
986 findAndReadIface doc_str mod_name as_source
987 = traceRn trace_msg `thenRn_`
988 -- we keep two maps for interface files,
989 -- one for 'normal' ones, the other for .hi-boot files,
990 -- hence the need to signal which kind we're interested.
991 getModuleHiMap as_source `thenRn` \ himap ->
992 case (lookupFM himap (moduleString mod_name)) of
994 Just fpath -> readIface fpath
995 -- Hack alert! When compiling PrelBase we have to load the
996 -- decls for packCString# and friends; they are 'thin-air' Ids
997 -- (see PrelInfo.lhs). So if we don't find the HiFile we quietly
998 -- look for a .hi-boot file instead, and use that
999 Nothing | thinAirLoop mod_name as_source
1000 -> findAndReadIface doc_str mod_name HiBootFile
1002 -> traceRn (ptext SLIT("...failed")) `thenRn_`
1005 thinAirLoop mod_name HiFile = mod_name `elem` thinAirModules
1006 thinAirLoop mod_name hif = False
1008 trace_msg = sep [hsep [ptext SLIT("Reading"),
1009 case as_source of { HiBootFile -> ptext SLIT("[boot]"); other -> empty},
1010 ptext SLIT("interface for"),
1011 pprModule mod_name <> semi],
1012 nest 4 (ptext SLIT("reason:") <+> doc_str)]
1015 @readIface@ tries just the one file.
1018 readIface :: String -> RnMG (Maybe ParsedIface)
1019 -- Nothing <=> file not found, or unreadable, or illegible
1020 -- Just x <=> successfully found and parsed
1022 = ioToRnMG (hGetStringBuffer file_path) `thenRn` \ read_result ->
1025 case parseIface contents (mkSrcLoc (mkFastString file_path) 1) of
1026 Failed err -> failWithRn Nothing err
1027 Succeeded (PIface iface) ->
1028 if opt_D_show_rn_imports then
1029 putDocRn (hcat[ptext SLIT("Read "), text file_path]) `thenRn_`
1030 returnRn (Just iface)
1032 returnRn (Just iface)
1035 if isDoesNotExistError err then
1038 failWithRn Nothing (cannaeReadFile file_path err)
1041 %*********************************************************
1045 %*********************************************************
1047 @mkSearchPath@ takes a string consisting of a colon-separated list
1048 of directories and corresponding suffixes, and turns it into a list
1049 of (directory, suffix) pairs. For example:
1052 mkSearchPath "foo%.hi:.%.p_hi:baz%.mc_hi"
1053 = [("foo",".hi"),( ".", ".p_hi"), ("baz",".mc_hi")]
1057 mkSearchPath :: Maybe String -> SearchPath
1058 mkSearchPath Nothing = [(".",".hi")]
1059 mkSearchPath (Just s)
1064 case span (/= '%') s of
1066 case span (/= ':') rs of
1067 (hisuf,_:rest) -> (dir,hisuf):go rest
1068 (hisuf,[]) -> [(dir,hisuf)]
1071 %*********************************************************
1075 %*********************************************************
1079 = hcat [ptext SLIT("Could not find valid interface file "),
1080 quotes (pprModule filename)]
1082 cannaeReadFile file err
1083 = hcat [ptext SLIT("Failed in reading file: "),
1085 ptext SLIT("; error="),
1089 = sep [ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name),
1090 ptext SLIT("needed at") <+> ppr loc]
1092 getDeclWarn name loc
1093 = sep [ptext SLIT("Failed to find (optional) interface decl for") <+> quotes (ppr name),
1094 ptext SLIT("desired at") <+> ppr loc]
1096 importDeclWarn mod name loc
1097 = sep [ptext SLIT("Compiler tried to import decl from interface file with same name as module."),
1098 ptext SLIT("(possible cause: module name clashes with interface file already in scope.)")
1100 hsep [ptext SLIT("Interface:"), quotes (pprModule mod), comma, ptext SLIT("name:"), quotes (ppr name),
1101 comma, ptext SLIT("desired at:"), ppr loc