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,
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, moduleUserString, 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 )
79 %*********************************************************
81 \subsection{Statistics}
83 %*********************************************************
86 getRnStats :: [RenamedHsDecl] -> RnMG SDoc
88 = getIfacesRn `thenRn` \ ifaces ->
90 n_mods = sizeFM (iModMap ifaces)
92 decls_imported = filter is_imported_decl all_decls
94 decls_read = [decl | (_, avail, decl, True) <- nameEnvElts (iDecls ifaces),
95 -- Data, newtype, and class decls are in the decls_fm
96 -- under multiple names; the tycon/class, and each
97 -- constructor/class op too.
98 -- The 'True' selects just the 'main' decl
99 not (isLocallyDefined (availName avail))
102 (cd_rd, dd_rd, add_rd, nd_rd, and_rd, sd_rd, vd_rd, _) = count_decls decls_read
103 (cd_sp, dd_sp, add_sp, nd_sp, and_sp, sd_sp, vd_sp, id_sp) = count_decls decls_imported
105 (unslurped_insts, _) = iDefInsts ifaces
106 inst_decls_unslurped = length (bagToList unslurped_insts)
107 inst_decls_read = id_sp + inst_decls_unslurped
110 [int n_mods <> text " interfaces read",
111 hsep [ int cd_sp, text "class decls imported, out of",
112 int cd_rd, text "read"],
113 hsep [ int dd_sp, text "data decls imported (of which", int add_sp,
114 text "abstractly), out of",
115 int dd_rd, text "read"],
116 hsep [ int nd_sp, text "newtype decls imported (of which", int and_sp,
117 text "abstractly), out of",
118 int nd_rd, text "read"],
119 hsep [int sd_sp, text "type synonym decls imported, out of",
120 int sd_rd, text "read"],
121 hsep [int vd_sp, text "value signatures imported, out of",
122 int vd_rd, text "read"],
123 hsep [int id_sp, text "instance decls imported, out of",
124 int inst_decls_read, text "read"]
127 returnRn (hcat [text "Renamer stats: ", stats])
129 is_imported_decl (DefD _) = False
130 is_imported_decl (ValD _) = False
131 is_imported_decl decl = not (isLocallyDefined (hsDeclName decl))
134 = -- pprTrace "count_decls" (ppr decls
139 -- ppr imported_decls
142 data_decls, abstract_data_decls,
143 newtype_decls, abstract_newtype_decls,
148 tycl_decls = [d | TyClD d <- decls]
149 (class_decls, data_decls, newtype_decls, syn_decls) = countTyClDecls tycl_decls
150 abstract_data_decls = length [() | TyData DataType _ _ _ [] _ _ _ <- tycl_decls]
151 abstract_newtype_decls = length [() | TyData NewType _ _ _ [] _ _ _ <- tycl_decls]
153 val_decls = length [() | SigD _ <- decls]
154 inst_decls = length [() | InstD _ <- decls]
158 %*********************************************************
160 \subsection{Loading a new interface file}
162 %*********************************************************
165 loadHomeInterface :: SDoc -> Name -> RnMG Ifaces
166 loadHomeInterface doc_str name
167 = loadInterface doc_str (nameModule name)
169 loadInterface :: SDoc -> Module -> RnMG Ifaces
170 loadInterface doc_str load_mod
171 = getIfacesRn `thenRn` \ ifaces ->
173 new_hif = moduleIfaceFlavour load_mod
174 this_mod = iMod ifaces
175 mod_map = iModMap ifaces
176 (insts, tycls_names) = iDefInsts ifaces
178 -- CHECK WHETHER WE HAVE IT ALREADY
179 case lookupFM mod_map load_mod of {
180 Just (existing_hif, _, _)
181 | bootFlavour new_hif || not (bootFlavour existing_hif)
182 -> -- Already in the cache, and new version is no better than old,
183 -- so don't re-read it
187 -- READ THE MODULE IN
188 findAndReadIface doc_str load_mod `thenRn` \ read_result ->
189 case read_result of {
190 -- Check for not found
191 Nothing -> -- Not found, so add an empty export env to the Ifaces map
192 -- so that we don't look again
194 new_mod_map = addToFM mod_map load_mod (hiFile, 0, [])
195 new_ifaces = ifaces { iModMap = new_mod_map }
197 setIfacesRn new_ifaces `thenRn_`
198 failWithRn new_ifaces (noIfaceErr load_mod) ;
201 Just (ParsedIface _ mod_vers usages exports rd_inst_mods rd_decls rd_insts) ->
203 -- LOAD IT INTO Ifaces
204 -- First set the module
206 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
207 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
208 -- If we do loadExport first the wrong info gets into the cache (unless we
209 -- explicitly tag each export which seems a bit of a bore)
211 getModuleRn `thenRn` \ this_mod ->
212 setModuleRn load_mod $ -- First set the module name of the module being loaded,
213 -- so that unqualified occurrences in the interface file
214 -- get the right qualifer
215 foldlRn loadDecl (iDecls ifaces) rd_decls `thenRn` \ new_decls ->
216 foldlRn loadFixDecl (iFixes ifaces) rd_decls `thenRn` \ new_fixities ->
217 foldlRn loadInstDecl insts rd_insts `thenRn` \ new_insts ->
219 mapRn (loadExport this_mod) exports `thenRn` \ avails_s ->
221 mod_details = (new_hif, mod_vers, concat avails_s)
223 -- Exclude this module from the "special-inst" modules
224 new_inst_mods = iInstMods ifaces `unionLists` (filter (/= this_mod) rd_inst_mods)
226 new_ifaces = ifaces { iModMap = addToFM mod_map load_mod mod_details,
228 iFixes = new_fixities,
229 iDefInsts = (new_insts, tycls_names),
230 iInstMods = new_inst_mods }
232 setIfacesRn new_ifaces `thenRn_`
236 loadExport :: Module -> ExportItem -> RnMG [AvailInfo]
237 loadExport this_mod (mod, entities)
238 | mod == this_mod = returnRn []
239 -- If the module exports anything defined in this module, just ignore it.
240 -- Reason: otherwise it looks as if there are two local definition sites
241 -- for the thing, and an error gets reported. Easiest thing is just to
242 -- filter them out up front. This situation only arises if a module
243 -- imports itself, or another module that imported it. (Necessarily,
244 -- this invoves a loop.) Consequence: if you say
249 -- module B( AType ) where
250 -- import {-# SOURCE #-} A( AType )
252 -- then you'll get a 'B does not export AType' message. A bit bogus
253 -- but it's a bogus thing to do!
256 = mapRn load_entity entities
258 new_name occ = newImportedGlobalName mod occ
260 load_entity (Avail occ)
261 = new_name occ `thenRn` \ name ->
262 returnRn (Avail name)
263 load_entity (AvailTC occ occs)
264 = new_name occ `thenRn` \ name ->
265 mapRn new_name occs `thenRn` \ names ->
266 returnRn (AvailTC name names)
269 loadFixDecl :: FixityEnv
270 -> (Version, RdrNameHsDecl)
272 loadFixDecl fixity_env (version, FixD (FixitySig rdr_name fixity loc))
273 = -- Ignore the version; when the fixity changes the version of
274 -- its 'host' entity changes, so we don't need a separate version
275 -- number for fixities
276 newImportedGlobalFromRdrName rdr_name `thenRn` \ name ->
278 new_fixity_env = addToNameEnv fixity_env name (FixitySig name fixity loc)
280 returnRn new_fixity_env
282 -- Ignore the other sorts of decl
283 loadFixDecl fixity_env other_decl = returnRn fixity_env
286 -> (Version, RdrNameHsDecl)
289 loadDecl decls_map (version, decl)
290 = getDeclBinders new_name decl `thenRn` \ maybe_avail ->
291 case maybe_avail of {
292 Nothing -> returnRn decls_map; -- No bindings
295 getDeclSysBinders new_name decl `thenRn` \ sys_bndrs ->
297 main_name = availName avail
298 new_decls_map = foldl add_decl decls_map
299 [ (name, (version,avail,decl',name==main_name))
300 | name <- sys_bndrs ++ availNames avail]
301 add_decl decls_map (name, stuff)
302 = WARN( name `elemNameEnv` decls_map, ppr name )
303 addToNameEnv decls_map name stuff
305 returnRn new_decls_map
308 new_name rdr_name loc = newImportedGlobalFromRdrName rdr_name
310 If a signature decl is being loaded, and optIgnoreIfacePragmas is on,
311 we toss away unfolding information.
313 Also, if the signature is loaded from a module we're importing from source,
314 we do the same. This is to avoid situations when compiling a pair of mutually
315 recursive modules, peering at unfolding info in the interface file of the other,
316 e.g., you compile A, it looks at B's interface file and may as a result change
317 its interface file. Hence, B is recompiled, maybe changing its interface file,
318 which will the unfolding info used in A to become invalid. Simple way out is to
319 just ignore unfolding info.
321 [Jan 99: I junked the second test above. If we're importing from an hi-boot
322 file there isn't going to *be* any pragma info. Maybe the above comment
323 dates from a time where we picked up a .hi file first if it existed?]
327 SigD (IfaceSig name tp ls loc) | opt_IgnoreIfacePragmas ->
328 SigD (IfaceSig name tp [] loc)
331 loadInstDecl :: Bag IfaceInst
333 -> RnMG (Bag IfaceInst)
334 loadInstDecl insts decl@(InstDecl inst_ty binds uprags dfun_name src_loc)
336 -- Find out what type constructors and classes are "gates" for the
337 -- instance declaration. If all these "gates" are slurped in then
338 -- we should slurp the instance decl too.
340 -- We *don't* want to count names in the context part as gates, though.
342 -- instance Foo a => Baz (T a) where ...
344 -- Here the gates are Baz and T, but *not* Foo.
346 munged_inst_ty = case inst_ty of
347 HsForAllTy tvs cxt ty -> HsForAllTy tvs [] ty
350 -- We find the gates by renaming the instance type with in a
351 -- and returning the free variables of the type
352 initRnMS emptyRnEnv vanillaInterfaceMode (
353 discardOccurrencesRn (rnHsSigType (text "an instance decl") munged_inst_ty)
354 ) `thenRn` \ (_, gate_names) ->
355 getModuleRn `thenRn` \ mod_name ->
356 returnRn (((mod_name, decl), gate_names) `consBag` insts)
358 vanillaInterfaceMode = InterfaceMode Compulsory
362 %********************************************************
364 \subsection{Loading usage information}
366 %********************************************************
369 checkUpToDate :: Module -> RnMG Bool -- True <=> no need to recompile
370 checkUpToDate mod_name
371 = findAndReadIface doc_str mod_name `thenRn` \ read_result ->
373 -- CHECK WHETHER WE HAVE IT ALREADY
375 Nothing -> -- Old interface file not found, so we'd better bail out
376 traceRn (sep [ptext SLIT("Didnt find old iface"),
377 pprModule mod_name]) `thenRn_`
380 Just (ParsedIface _ _ usages _ _ _ _)
381 -> -- Found it, so now check it
384 -- Only look in current directory, with suffix .hi
385 doc_str = sep [ptext SLIT("need usage info from"), pprModule mod_name]
387 checkModUsage [] = returnRn True -- Yes! Everything is up to date!
389 checkModUsage ((mod, old_mod_vers, whats_imported) : rest)
390 = loadInterface doc_str mod `thenRn` \ ifaces ->
392 maybe_new_mod_vers = lookupFM (iModMap ifaces) mod
393 Just (_, new_mod_vers, _) = maybe_new_mod_vers
395 -- If we can't find a version number for the old module then
396 -- bail out saying things aren't up to date
397 if not (maybeToBool maybe_new_mod_vers) then
398 traceRn (sep [ptext SLIT("Can't find version number for module"), pprModule mod]) `thenRn_`
402 -- If the module version hasn't changed, just move on
403 if new_mod_vers == old_mod_vers then
404 traceRn (sep [ptext SLIT("Module version unchanged:"), pprModule mod]) `thenRn_`
407 traceRn (sep [ptext SLIT("Module version has changed:"), pprModule mod]) `thenRn_`
409 -- Module version changed, so check entities inside
411 -- If the usage info wants to say "I imported everything from this module"
412 -- it does so by making whats_imported equal to Everything
413 -- In that case, we must recompile
414 case whats_imported of {
415 Everything -> traceRn (ptext SLIT("...and I needed the whole module")) `thenRn_`
416 returnRn False; -- Bale out
418 Specifically old_local_vers ->
420 -- Non-empty usage list, so check item by item
421 checkEntityUsage mod (iDecls ifaces) old_local_vers `thenRn` \ up_to_date ->
423 traceRn (ptext SLIT("...but the bits I use haven't.")) `thenRn_`
424 checkModUsage rest -- This one's ok, so check the rest
426 returnRn False -- This one failed, so just bail out now
429 doc_str = sep [ptext SLIT("need version info for"), pprModule mod]
432 checkEntityUsage mod decls []
433 = returnRn True -- Yes! All up to date!
435 checkEntityUsage mod decls ((occ_name,old_vers) : rest)
436 = newImportedGlobalName mod occ_name `thenRn` \ name ->
437 case lookupNameEnv decls name of
439 Nothing -> -- We used it before, but it ain't there now
440 putDocRn (sep [ptext SLIT("No longer exported:"), ppr name]) `thenRn_`
443 Just (new_vers,_,_,_) -- It's there, but is it up to date?
444 | new_vers == old_vers
445 -- Up to date, so check the rest
446 -> checkEntityUsage mod decls rest
449 -- Out of date, so bale out
450 -> putDocRn (sep [ptext SLIT("Out of date:"), ppr name]) `thenRn_`
455 %*********************************************************
457 \subsection{Getting in a declaration}
459 %*********************************************************
462 importDecl :: Occurrence -> RnMode -> RnMG (Maybe RdrNameHsDecl)
463 -- Returns Nothing for a wired-in or already-slurped decl
465 importDecl (name, loc) mode
466 = checkSlurped name `thenRn` \ already_slurped ->
467 if already_slurped then
468 -- traceRn (sep [text "Already slurped:", ppr name]) `thenRn_`
469 returnRn Nothing -- Already dealt with
471 if isWiredInName name then
472 getWiredInDecl name mode
474 getIfacesRn `thenRn` \ ifaces ->
476 mod = nameModule name
478 if mod == iMod ifaces then -- Don't bring in decls from
479 addWarnRn (importDeclWarn mod name loc) `thenRn_`
480 -- pprTrace "importDecl wierdness:" (ppr name) $
481 returnRn Nothing -- the renamed module's own interface file
484 getNonWiredInDecl name loc mode
488 getNonWiredInDecl :: Name -> SrcLoc -> RnMode -> RnMG (Maybe RdrNameHsDecl)
489 getNonWiredInDecl needed_name loc mode
490 = traceRn doc_str `thenRn_`
491 loadHomeInterface doc_str needed_name `thenRn` \ ifaces ->
492 case lookupNameEnv (iDecls ifaces) needed_name of
494 -- Special case for data/newtype type declarations
495 Just (version, avail, TyClD tycl_decl, _) | isDataDecl tycl_decl
496 -> getNonWiredDataDecl needed_name version avail tycl_decl `thenRn` \ (avail', maybe_decl) ->
497 recordSlurp (Just version) necessity avail' `thenRn_`
500 Just (version,avail,decl,_)
501 -> recordSlurp (Just version) necessity avail `thenRn_`
504 Nothing -> -- Can happen legitimately for "Optional" occurrences
506 Optional -> addWarnRn (getDeclWarn needed_name loc);
507 other -> addErrRn (getDeclErr needed_name loc)
511 necessity = modeToNecessity mode
512 doc_str = sep [ptext SLIT("need decl for"), ppr needed_name, ptext SLIT("needed at"), ppr loc]
515 @getWiredInDecl@ maps a wired-in @Name@ to what it makes available.
516 It behaves exactly as if the wired in decl were actually in an interface file.
519 * if the wired-in name is a data type constructor or a data constructor,
520 it brings in the type constructor and all the data constructors; and
521 marks as "occurrences" any free vars of the data con.
523 * similarly for synonum type constructor
525 * if the wired-in name is another wired-in Id, it marks as "occurrences"
526 the free vars of the Id's type.
528 * it loads the interface file for the wired-in thing for the
529 sole purpose of making sure that its instance declarations are available
531 All this is necessary so that we know all types that are "in play", so
532 that we know just what instances to bring into scope.
535 getWiredInDecl name mode
536 = setModuleRn mod_name (
537 initRnMS emptyRnEnv new_mode get_wired
538 ) `thenRn` \ avail ->
539 recordSlurp Nothing necessity avail `thenRn_`
541 -- Force in the home module in case it has instance decls for
542 -- the thing we are interested in.
544 -- Mini hack 1: no point for non-tycons/class; and if we
545 -- do this we find PrelNum trying to import PackedString,
546 -- because PrelBase's .hi file mentions PackedString.unpackString
547 -- But PackedString.hi isn't built by that point!
549 -- Mini hack 2; GHC is guaranteed not to have
550 -- instance decls, so it's a waste of time to read it
552 -- NB: We *must* look at the availName of the slurped avail,
553 -- not the name passed to getWiredInDecl! Why? Because if a data constructor
554 -- or class op is passed to getWiredInDecl we'll pull in the whole data/class
555 -- decl, and recordSlurp will record that fact. But since the data constructor
556 -- isn't a tycon/class we won't force in the home module. And even if the
557 -- type constructor/class comes along later, loadDecl will say that it's already
558 -- been slurped, so getWiredInDecl won't even be called. Pretty obscure bug, this was.
560 main_name = availName avail
561 main_is_tc = case avail of { AvailTC _ _ -> True; Avail _ -> False }
562 mod = nameModule main_name
563 doc_str = sep [ptext SLIT("need home module for wired in thing"), ppr name]
565 (if not main_is_tc || mod == pREL_GHC then
568 loadHomeInterface doc_str main_name `thenRn_`
572 returnRn Nothing -- No declaration to process further
574 necessity = modeToNecessity mode
575 new_mode = case mode of
576 InterfaceMode _ -> mode
577 SourceMode -> vanillaInterfaceMode
579 get_wired | is_tycon -- ... a type constructor
580 = get_wired_tycon the_tycon
582 | maybeToBool maybe_data_con -- ... a wired-in data constructor
583 = get_wired_tycon (dataConTyCon data_con)
585 | otherwise -- ... a wired-in non data-constructor
586 = get_wired_id the_id
588 mod_name = nameModule name
589 maybe_wired_in_tycon = maybeWiredInTyConName name
590 is_tycon = maybeToBool maybe_wired_in_tycon
591 maybe_wired_in_id = maybeWiredInIdName name
592 Just the_tycon = maybe_wired_in_tycon
593 Just the_id = maybe_wired_in_id
594 maybe_data_con = isDataConId_maybe the_id
595 Just data_con = maybe_data_con
599 = addImplicitOccsRn id_mentions `thenRn_`
600 returnRn (Avail (getName id))
602 id_mentions = nameSetToList (namesOfType ty)
605 get_wired_tycon tycon
607 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
608 returnRn (AvailTC tc_name [tc_name])
610 tc_name = getName tycon
611 (tyvars,ty) = getSynTyConDefn tycon
612 mentioned = namesOfType ty `minusNameSet` mkNameSet (map getName tyvars)
614 get_wired_tycon tycon
615 | otherwise -- data or newtype
616 = addImplicitOccsRn (nameSetToList mentioned) `thenRn_`
617 returnRn (AvailTC tycon_name (tycon_name : map getName data_cons))
619 tycon_name = getName tycon
620 data_cons = tyConDataCons tycon
621 mentioned = foldr (unionNameSets . namesOfType . dataConType) emptyNameSet data_cons
626 %*********************************************************
628 \subsection{Getting what a module exports}
630 %*********************************************************
633 getInterfaceExports :: Module -> RnMG Avails
634 getInterfaceExports mod
635 = loadInterface doc_str mod `thenRn` \ ifaces ->
636 case lookupFM (iModMap ifaces) mod of
637 Nothing -> -- Not there; it must be that the interface file wasn't found;
638 -- the error will have been reported already.
639 -- (Actually loadInterface should put the empty export env in there
640 -- anyway, but this does no harm.)
643 Just (_, _, avails) -> returnRn avails
645 doc_str = sep [pprModule mod, ptext SLIT("is directly imported")]
649 %*********************************************************
651 \subsection{Data type declarations are handled specially}
653 %*********************************************************
655 Data type declarations get special treatment. If we import a data type decl
656 with all its constructors, we end up importing all the types mentioned in
657 the constructors' signatures, and hence {\em their} data type decls, and so on.
658 In effect, we get the transitive closure of data type decls. Worse, this drags
659 in tons on instance decls, and their unfoldings, and so on.
661 If only the type constructor is mentioned, then all this is a waste of time.
662 If any of the data constructors are mentioned then we really have to
663 drag in the whole declaration.
665 So when we import the type constructor for a @data@ or @newtype@ decl, we
666 put it in the "deferred data/newtype decl" pile in Ifaces. Right at the end
667 we slurp these decls, if they havn't already been dragged in by an occurrence
671 getNonWiredDataDecl needed_name
673 avail@(AvailTC tycon_name _)
674 ty_decl@(TyData new_or_data context tycon tyvars condecls derivings pragmas src_loc)
675 | needed_name == tycon_name
677 -- don't prune newtypes, as the code generator may
678 -- want to peer inside a newtype type constructor
679 -- (ClosureInfo.fun_result_ty is the culprit.)
680 && not (new_or_data == NewType)
681 && not (nameUnique needed_name `elem` cCallishTyKeys)
682 -- Hack! Don't prune these tycons whose constructors
683 -- the desugarer must be able to see when desugaring
686 = -- Need the type constructor; so put it in the deferred set for now
687 getIfacesRn `thenRn` \ ifaces ->
689 deferred_data_decls = iDefData ifaces
690 new_ifaces = ifaces {iDefData = new_deferred_data_decls}
692 no_constr_ty_decl = TyData new_or_data [] tycon tyvars [] derivings pragmas src_loc
693 new_deferred_data_decls = addToNameEnv deferred_data_decls tycon_name
694 (nameModule tycon_name, no_constr_ty_decl)
695 -- Nota bene: we nuke both the constructors and the context in the deferred decl.
696 -- If we don't nuke the context then renaming the deferred data decls can give
697 -- new unresolved names (for the classes). This could be handled, but there's
698 -- no point. If the data type is completely abstract then we aren't interested
701 setIfacesRn new_ifaces `thenRn_`
702 returnRn (AvailTC tycon_name [tycon_name], Nothing)
705 = -- Need a data constructor, so delete the data decl from the deferred set if it's there
706 getIfacesRn `thenRn` \ ifaces ->
708 deferred_data_decls = iDefData ifaces
709 new_ifaces = ifaces {iDefData = new_deferred_data_decls}
711 new_deferred_data_decls = delFromNameEnv deferred_data_decls tycon_name
713 setIfacesRn new_ifaces `thenRn_`
714 returnRn (avail, Just (TyClD ty_decl))
718 getDeferredDataDecls :: RnMG [(Module, RdrNameTyClDecl)]
720 = getIfacesRn `thenRn` \ ifaces ->
722 deferred_list = nameEnvElts (iDefData ifaces)
723 trace_msg = hang (text "Slurping abstract data/newtype decls for: ")
724 4 (ppr (map fst deferred_list))
726 traceRn trace_msg `thenRn_`
727 returnRn deferred_list
731 %*********************************************************
733 \subsection{Instance declarations are handled specially}
735 %*********************************************************
738 getImportedInstDecls :: RnMG [(Module,RdrNameInstDecl)]
740 = -- First load any special-instance modules that aren't aready loaded
741 getSpecialInstModules `thenRn` \ inst_mods ->
742 mapRn load_it inst_mods `thenRn_`
744 -- Now we're ready to grab the instance declarations
745 -- Find the un-gated ones and return them,
746 -- removing them from the bag kept in Ifaces
747 getIfacesRn `thenRn` \ ifaces ->
749 (insts, tycls_names) = iDefInsts ifaces
751 -- An instance decl is ungated if all its gates have been slurped
752 select_ungated :: IfaceInst -- A gated inst decl
754 -> ([(Module, RdrNameInstDecl)], [IfaceInst]) -- Accumulator
756 -> ([(Module, RdrNameInstDecl)], -- The ungated ones
757 [IfaceInst]) -- Still gated, but with
759 select_ungated (decl,gates) (ungated_decls, gated_decls)
760 | isEmptyNameSet remaining_gates
761 = (decl : ungated_decls, gated_decls)
763 = (ungated_decls, (decl, remaining_gates) : gated_decls)
765 remaining_gates = gates `minusNameSet` tycls_names
767 (un_gated_insts, still_gated_insts) = foldrBag select_ungated ([], []) insts
769 new_ifaces = ifaces {iDefInsts = (listToBag still_gated_insts, tycls_names)}
770 -- NB: don't throw away tycls_names;
771 -- we may comre across more instance decls
773 traceRn (sep [text "getInstDecls:", fsep (map ppr (nameSetToList tycls_names))]) `thenRn_`
774 setIfacesRn new_ifaces `thenRn_`
775 returnRn un_gated_insts
777 load_it mod = loadInterface (doc_str mod) mod
778 doc_str mod = sep [pprModule mod, ptext SLIT("is a special-instance module")]
781 getSpecialInstModules :: RnMG [Module]
782 getSpecialInstModules
783 = getIfacesRn `thenRn` \ ifaces ->
784 returnRn (iInstMods ifaces)
786 getImportedFixities :: GlobalRdrEnv -> RnMG FixityEnv
787 -- Get all imported fixities
788 -- We first make sure that all the home modules
789 -- of all in-scope variables are loaded.
790 getImportedFixities gbl_env
792 home_modules = [ nameModule name | names <- rdrEnvElts gbl_env,
794 not (isLocallyDefined name)
797 mapRn load (nub home_modules) `thenRn_`
799 -- Now we can snaffle the fixity env
800 getIfacesRn `thenRn` \ ifaces ->
801 returnRn (iFixes ifaces)
803 load mod = loadInterface doc_str mod
805 doc_str = ptext SLIT("Need fixities from") <+> ppr mod
809 %*********************************************************
811 \subsection{Keeping track of what we've slurped, and version numbers}
813 %*********************************************************
815 getImportVersions figures out what the "usage information" for this moudule is;
816 that is, what it must record in its interface file as the things it uses.
818 - anything reachable from its body code
819 - any module exported with a "module Foo".
821 Why the latter? Because if Foo changes then this module's export list
822 will change, so we must recompile this module at least as far as
823 making a new interface file --- but in practice that means complete
827 module A( f, g ) where module B( f ) where
828 import B( f ) f = h 3
831 Should we record B.f in A's usages? In fact we don't. Certainly, if
832 anything about B.f changes than anyone who imports A should be recompiled;
833 they'll get an early exit if they don't use B.f. However, even if B.f
834 doesn't change at all, B.h may do so, and this change may not be reflected
835 in f's version number. So there are two things going on when compiling module A:
837 1. Are A.o and A.hi correct? Then we can bale out early.
838 2. Should modules that import A be recompiled?
840 For (1) it is slightly harmful to record B.f in A's usages, because a change in
841 B.f's version will provoke full recompilation of A, producing an identical A.o,
842 and A.hi differing only in its usage-version of B.f (which isn't used by any importer).
844 For (2), because of the tricky B.h question above, we ensure that A.hi is touched
845 (even if identical to its previous version) if A's recompilation was triggered by
846 an imported .hi file date change. Given that, there's no need to record B.f in
849 On the other hand, if A exports "module B" then we *do* count module B among
850 A's usages, because we must recompile A to ensure that A.hi changes appropriately.
853 getImportVersions :: Module -- Name of this module
854 -> Maybe [IE any] -- Export list for this module
855 -> RnMG (VersionInfo Name) -- Version info for these names
857 getImportVersions this_mod exports
858 = getIfacesRn `thenRn` \ ifaces ->
860 mod_map = iModMap ifaces
861 imp_names = iVSlurp ifaces
863 -- mv_map groups together all the things imported from a particular module.
864 mv_map, mv_map_mod :: FiniteMap Module (WhatsImported Name)
866 mv_map_mod = foldl add_mod emptyFM export_mods
867 -- mv_map_mod records all the modules that have a "module M"
868 -- in this module's export list with an "Everything"
870 mv_map = foldl add_mv mv_map_mod imp_names
871 -- mv_map adds the version numbers of things exported individually
873 mk_version_info (mod, local_versions)
874 = case lookupFM mod_map mod of
875 Just (hif, version, _) -> (mod, version, local_versions)
877 returnRn (map mk_version_info (fmToList mv_map))
879 export_mods = case exports of
881 Just es -> [mod | IEModuleContents mod <- es, mod /= this_mod]
883 add_mv mv_map v@(name, version)
884 = addToFM_C add_item mv_map mod (Specifically [v])
886 mod = nameModule name
888 add_item Everything _ = Everything
889 add_item (Specifically xs) _ = Specifically (v:xs)
891 add_mod mv_map mod = addToFM mv_map mod Everything
896 = getIfacesRn `thenRn` \ ifaces ->
897 returnRn (name `elemNameSet` iSlurp ifaces)
899 getSlurpedNames :: RnMG NameSet
901 = getIfacesRn `thenRn` \ ifaces ->
902 returnRn (iSlurp ifaces)
904 recordSlurp maybe_version necessity avail
905 = {- traceRn (hsep [text "Record slurp:", pprAvail avail,
906 -- NB PprForDebug prints export flag, which is too
907 -- strict; it's a knot-tied thing in RnNames
908 case necessity of {Compulsory -> text "comp"; Optional -> text "opt" } ]) `thenRn_`
910 getIfacesRn `thenRn` \ ifaces ->
912 Ifaces { iSlurp = slurped_names,
914 iDefInsts = (insts, tycls_names) } = ifaces
916 new_slurped_names = addAvailToNameSet slurped_names avail
918 new_imp_names = case maybe_version of
919 Just version -> (availName avail, version) : imp_names
922 -- Add to the names that will let in instance declarations;
923 -- but only (a) if it's a type/class
924 -- (b) if it's compulsory (unless the test flag opt_PruneInstDecls is off)
925 new_tycls_names = case avail of
926 AvailTC tc _ | not opt_PruneInstDecls ||
927 case necessity of {Optional -> False; Compulsory -> True }
928 -> tycls_names `addOneToNameSet` tc
929 otherwise -> tycls_names
931 new_ifaces = ifaces { iSlurp = new_slurped_names,
932 iVSlurp = new_imp_names,
933 iDefInsts = (insts, new_tycls_names) }
935 setIfacesRn new_ifaces
939 %*********************************************************
941 \subsection{Getting binders out of a declaration}
943 %*********************************************************
945 @getDeclBinders@ returns the names for a @RdrNameHsDecl@.
946 It's used for both source code (from @availsFromDecl@) and interface files
949 It doesn't deal with source-code specific things: ValD, DefD. They
950 are handled by the sourc-code specific stuff in RnNames.
953 getDeclBinders :: (RdrName -> SrcLoc -> RnMG Name) -- New-name function
955 -> RnMG (Maybe AvailInfo)
957 getDeclBinders new_name (TyClD (TyData _ _ tycon _ condecls _ _ src_loc))
958 = new_name tycon src_loc `thenRn` \ tycon_name ->
959 getConFieldNames new_name condecls `thenRn` \ sub_names ->
960 returnRn (Just (AvailTC tycon_name (tycon_name : nub sub_names)))
961 -- The "nub" is because getConFieldNames can legitimately return duplicates,
962 -- when a record declaration has the same field in multiple constructors
964 getDeclBinders new_name (TyClD (TySynonym tycon _ _ src_loc))
965 = new_name tycon src_loc `thenRn` \ tycon_name ->
966 returnRn (Just (AvailTC tycon_name [tycon_name]))
968 getDeclBinders new_name (TyClD (ClassDecl _ cname _ sigs _ _ tname dname src_loc))
969 = new_name cname src_loc `thenRn` \ class_name ->
971 -- Record the names for the class ops
973 -- ignoring fixity declarations
974 nonfix_sigs = nonFixitySigs sigs
976 mapRn (getClassOpNames new_name) nonfix_sigs `thenRn` \ sub_names ->
978 returnRn (Just (AvailTC class_name (class_name : sub_names)))
980 getDeclBinders new_name (SigD (IfaceSig var ty prags src_loc))
981 = new_name var src_loc `thenRn` \ var_name ->
982 returnRn (Just (Avail var_name))
984 getDeclBinders new_name (FixD _) = returnRn Nothing
985 getDeclBinders new_name (ForD _) = returnRn Nothing
986 getDeclBinders new_name (DefD _) = returnRn Nothing
987 getDeclBinders new_name (InstD _) = returnRn Nothing
990 getConFieldNames new_name (ConDecl con _ _ (RecCon fielddecls) src_loc : rest)
991 = mapRn (\n -> new_name n src_loc) (con:fields) `thenRn` \ cfs ->
992 getConFieldNames new_name rest `thenRn` \ ns ->
995 fields = concat (map fst fielddecls)
997 getConFieldNames new_name (ConDecl con _ _ condecl src_loc : rest)
998 = new_name con src_loc `thenRn` \ n ->
1000 NewCon _ (Just f) ->
1001 new_name f src_loc `thenRn` \ new_f ->
1003 _ -> returnRn [n]) `thenRn` \ nn ->
1004 getConFieldNames new_name rest `thenRn` \ ns ->
1007 getConFieldNames new_name [] = returnRn []
1009 getClassOpNames new_name (ClassOpSig op _ _ src_loc) = new_name op src_loc
1012 @getDeclSysBinders@ gets the implicit binders introduced by a decl.
1013 A the moment that's just the tycon and datacon that come with a class decl.
1014 They aren'te returned by getDeclBinders because they aren't in scope;
1015 but they *should* be put into the DeclsMap of this module.
1018 getDeclSysBinders new_name (TyClD (ClassDecl _ cname _ sigs _ _ tname dname src_loc))
1019 = new_name dname src_loc `thenRn` \ datacon_name ->
1020 new_name tname src_loc `thenRn` \ tycon_name ->
1021 returnRn [tycon_name, datacon_name]
1023 getDeclSysBinders new_name other_decl
1027 %*********************************************************
1029 \subsection{Reading an interface file}
1031 %*********************************************************
1034 findAndReadIface :: SDoc -> Module -> RnMG (Maybe ParsedIface)
1035 -- Nothing <=> file not found, or unreadable, or illegible
1036 -- Just x <=> successfully found and parsed
1038 findAndReadIface doc_str mod_name
1039 = traceRn trace_msg `thenRn_`
1040 -- we keep two maps for interface files,
1041 -- one for 'normal' ones, the other for .hi-boot files,
1042 -- hence the need to signal which kind we're interested.
1043 getModuleHiMap from_hi_boot `thenRn` \ himap ->
1044 case (lookupFM himap (moduleUserString mod_name)) of
1046 Just fpath -> readIface fpath
1047 -- Hack alert! When compiling PrelBase we have to load the
1048 -- decls for packCString# and friends; they are 'thin-air' Ids
1049 -- (see PrelInfo.lhs). So if we don't find the HiFile we quietly
1050 -- look for a .hi-boot file instead, and use that
1051 Nothing | not from_hi_boot && mod_name `elem` thinAirModules
1052 -> findAndReadIface doc_str (mkBootModule mod_name)
1054 -> traceRn (ptext SLIT("...failed")) `thenRn_`
1057 hif = moduleIfaceFlavour mod_name
1058 from_hi_boot = bootFlavour hif
1060 trace_msg = sep [hsep [ptext SLIT("Reading"),
1061 if from_hi_boot then ptext SLIT("[boot]") else empty,
1062 ptext SLIT("interface for"),
1063 pprModule mod_name <> semi],
1064 nest 4 (ptext SLIT("reason:") <+> doc_str)]
1067 @readIface@ tries just the one file.
1070 readIface :: String -> RnMG (Maybe ParsedIface)
1071 -- Nothing <=> file not found, or unreadable, or illegible
1072 -- Just x <=> successfully found and parsed
1074 = ioToRnMG (hGetStringBuffer file_path) `thenRn` \ read_result ->
1077 case parseIface contents (mkSrcLoc (mkFastString file_path) 1) of
1078 Failed err -> failWithRn Nothing err
1079 Succeeded (PIface iface) ->
1080 if opt_D_show_rn_imports then
1081 putDocRn (hcat[ptext SLIT("Read "), text file_path]) `thenRn_`
1082 returnRn (Just iface)
1084 returnRn (Just iface)
1087 if isDoesNotExistError err then
1090 failWithRn Nothing (cannaeReadFile file_path err)
1093 %*********************************************************
1097 %*********************************************************
1099 @mkSearchPath@ takes a string consisting of a colon-separated list
1100 of directories and corresponding suffixes, and turns it into a list
1101 of (directory, suffix) pairs. For example:
1104 mkSearchPath "foo%.hi:.%.p_hi:baz%.mc_hi"
1105 = [("foo",".hi"),( ".", ".p_hi"), ("baz",".mc_hi")]
1109 mkSearchPath :: Maybe String -> SearchPath
1110 mkSearchPath Nothing = [(".",".hi")]
1111 mkSearchPath (Just s)
1116 case span (/= '%') s of
1118 case span (/= ':') rs of
1119 (hisuf,_:rest) -> (dir,hisuf):go rest
1120 (hisuf,[]) -> [(dir,hisuf)]
1123 %*********************************************************
1127 %*********************************************************
1131 = hcat [ptext SLIT("Could not find valid interface file "),
1132 quotes (pprModule filename)]
1134 cannaeReadFile file err
1135 = hcat [ptext SLIT("Failed in reading file: "),
1137 ptext SLIT("; error="),
1141 = sep [ptext SLIT("Failed to find interface decl for") <+> quotes (ppr name),
1142 ptext SLIT("needed at") <+> ppr loc]
1144 getDeclWarn name loc
1145 = sep [ptext SLIT("Failed to find (optional) interface decl for") <+> quotes (ppr name),
1146 ptext SLIT("desired at") <+> ppr loc]
1148 importDeclWarn mod name loc
1149 = sep [ptext SLIT("Compiler tried to import decl from interface file with same name as module."),
1150 ptext SLIT("(possible cause: module name clashes with interface file already in scope.)")
1152 hsep [ptext SLIT("Interface:"), quotes (pprModule mod), comma, ptext SLIT("name:"), quotes (ppr name),
1153 comma, ptext SLIT("desired at:"), ppr loc