2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
7 mkUsageInfo, -- Construct the usage info for a module
9 mkIface, -- Build a ModIface from a ModGuts,
10 -- including computing version information
12 writeIfaceFile, -- Write the interface file
14 checkOldIface, -- See if recompilation is required, by
15 -- comparing version information
17 tyThingToIfaceDecl -- Converting things to their Iface equivalents
21 -----------------------------------------------
22 MkIface.lhs deals with versioning
23 -----------------------------------------------
25 Here's the version-related info in an interface file
27 module Foo 8 -- module-version
28 3 -- export-list-version
30 Usages: -- Version info for what this compilation of Foo imported
31 Baz 3 -- Module version
32 [4] -- The export-list version if Foo depended on it
33 (g,2) -- Function and its version
34 (T,1) -- Type and its version
36 <version> f :: Int -> Int {- Unfolding: \x -> Wib.t[2] x -}
37 -- The [2] says that f's unfolding
38 -- mentions verison 2 of Wib.t
40 -----------------------------------------------
42 -----------------------------------------------
45 * In the mi_usages information in an interface, we record the
46 version number of each free variable of the module
48 * In mkIface, we compute the version number of each exported thing A.f
49 by comparing its A.f's info with its new info, and bumping its
50 version number if it differs. If A.f mentions B.g, and B.g's version
51 number has changed, then we count A.f as having changed too.
53 * In checkOldIface we compare the mi_usages for the module with
54 the actual version info for all each thing recorded in mi_usages
59 We count A.f as changing if its fixity changes
63 If a rule changes, we want to recompile any module that might be
64 affected by that rule. For non-orphan rules, this is relatively easy.
65 If module M defines f, and a rule for f, just arrange that the version
66 number for M.f changes if any of the rules for M.f change. Any module
67 that does not depend on M.f can't be affected by the rule-change
70 Orphan rules (ones whose 'head function' is not defined in M) are
71 harder. Here's what we do.
73 * We have a per-module orphan-rule version number which changes if
74 any orphan rule changes. (It's unaffected by non-orphan rules.)
76 * We record usage info for any orphan module 'below' this one,
77 giving the orphan-rule version number. We recompile if this
80 The net effect is that if an orphan rule changes, we recompile every
81 module above it. That's very conservative, but it's devilishly hard
82 to know what it might affect, so we just have to be conservative.
86 In an iface file we have
88 instance Eq a => Eq [a] = dfun29
91 We have a version number for dfun29, covering its unfolding
92 etc. Suppose we are compiling a module M that imports A only
93 indirectly. If typechecking M uses this instance decl, we record the
94 dependency on A.dfun29 as if it were a free variable of the module
95 (via the tcg_inst_usages accumulator). That means that A will appear
96 in M's usage list. If the shape of the instance declaration changes,
97 then so will dfun29's version, triggering a recompilation.
99 Adding an instance declaration, or changing an instance decl that is
100 not currently used, is more tricky. (This really only makes a
101 difference when we have overlapping instance decls, because then the
102 new instance decl might kick in to override the old one.) We handle
103 this in a very similar way that we handle rules above.
105 * For non-orphan instance decls, identify one locally-defined tycon/class
106 mentioned in the decl. Treat the instance decl as part of the defn of that
107 tycon/class, so that if the shape of the instance decl changes, so does the
108 tycon/class; that in turn will force recompilation of anything that uses
111 * For orphan instance decls, act the same way as for orphan rules.
112 Indeed, we use the same global orphan-rule version number.
116 mkUsageInfo figures out what the ``usage information'' for this
117 moudule is; that is, what it must record in its interface file as the
120 We produce a line for every module B below the module, A, currently being
123 to record the fact that A does import B indirectly. This is used to decide
124 to look to look for B.hi rather than B.hi-boot when compiling a module that
125 imports A. This line says that A imports B, but uses nothing in it.
126 So we'll get an early bale-out when compiling A if B's version changes.
128 The usage information records:
131 \item (a) anything reachable from its body code
132 \item (b) any module exported with a @module Foo@
133 \item (c) anything reachable from an exported item
136 Why (b)? Because if @Foo@ changes then this module's export list
137 will change, so we must recompile this module at least as far as
138 making a new interface file --- but in practice that means complete
141 Why (c)? Consider this:
143 module A( f, g ) where | module B( f ) where
144 import B( f ) | f = h 3
148 Here, @B.f@ isn't used in A. Should we nevertheless record @B.f@ in
149 @A@'s usages? Our idea is that we aren't going to touch A.hi if it is
150 *identical* to what it was before. If anything about @B.f@ changes
151 than anyone who imports @A@ should be recompiled in case they use
152 @B.f@ (they'll get an early exit if they don't). So, if anything
153 about @B.f@ changes we'd better make sure that something in A.hi
154 changes, and the convenient way to do that is to record the version
155 number @B.f@ in A.hi in the usage list. If B.f changes that'll force a
156 complete recompiation of A, which is overkill but it's the only way to
157 write a new, slightly different, A.hi.
159 But the example is tricker. Even if @B.f@ doesn't change at all,
160 @B.h@ may do so, and this change may not be reflected in @f@'s version
161 number. But with -O, a module that imports A must be recompiled if
162 @B.h@ changes! So A must record a dependency on @B.h@. So we treat
163 the occurrence of @B.f@ in the export list *just as if* it were in the
164 code of A, and thereby haul in all the stuff reachable from it.
166 *** Conclusion: if A mentions B.f in its export list,
167 behave just as if A mentioned B.f in its source code,
168 and slurp in B.f and all its transitive closure ***
170 [NB: If B was compiled with -O, but A isn't, we should really *still*
171 haul in all the unfoldings for B, in case the module that imports A *is*
172 compiled with -O. I think this is the case.]
176 #include "HsVersions.h"
178 import IfaceSyn -- All of it
179 import IfaceType ( toIfaceTvBndrs, toIfaceType, toIfaceContext,
181 import LoadIface ( readIface, loadInterface, pprModIface )
182 import Id ( Id, idName, idType, idInfo, idArity, isDataConWorkId_maybe, isFCallId_maybe )
183 import IdInfo ( IdInfo, CafInfo(..), WorkerInfo(..),
184 arityInfo, cafInfo, newStrictnessInfo,
185 workerInfo, unfoldingInfo, inlinePragInfo )
186 import NewDemand ( isTopSig )
188 import Class ( classExtraBigSig, classTyCon )
189 import TyCon ( TyCon, AlgTyConRhs(..), SynTyConRhs(..),
190 isRecursiveTyCon, isForeignTyCon,
191 isSynTyCon, isAlgTyCon, isPrimTyCon, isFunTyCon,
192 isTupleTyCon, tupleTyConBoxity, tyConStupidTheta,
193 tyConHasGenerics, synTyConRhs, isGadtSyntaxTyCon,
194 tyConArity, tyConTyVars, algTyConRhs, tyConExtName,
196 import DataCon ( dataConName, dataConFieldLabels, dataConStrictMarks,
197 dataConTyCon, dataConIsInfix, dataConUnivTyVars,
198 dataConExTyVars, dataConEqSpec, dataConTheta,
200 import Type ( TyThing(..), splitForAllTys, funResultTy )
201 import TcType ( deNoteType )
202 import TysPrim ( alphaTyVars )
203 import InstEnv ( Instance(..) )
204 import FamInstEnv ( FamInst(..) )
206 import HscTypes ( ModIface(..), ModDetails(..),
207 ModGuts(..), HscEnv(..), hscEPS, Dependencies(..),
209 ModSummary(..), msHiFilePath,
210 mkIfaceDepCache, mkIfaceFixCache, mkIfaceVerCache,
212 GenAvailInfo(..), availName,
213 ExternalPackageState(..),
214 Usage(..), IsBootInterface,
215 Deprecs(..), IfaceDeprecs, Deprecations,
220 import DynFlags ( GhcMode(..), DynFlags(..), DynFlag(..), dopt )
221 import Name ( Name, nameModule, nameOccName, nameParent,
222 isExternalName, isInternalName, nameParent_maybe, isWiredInName,
223 isImplicitName, NamedThing(..) )
226 import OccName ( OccName, OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
228 OccSet, emptyOccSet, elemOccSet, occSetElts,
229 extendOccSet, extendOccSetList,
230 isEmptyOccSet, intersectOccSet, intersectsOccSet,
234 import BasicTypes ( Version, initialVersion, bumpVersion, isAlwaysActive,
235 Activation(..), RecFlag(..), boolToRecFlag )
236 import Util ( createDirectoryHierarchy, directoryOf, sortLe, seqList, lengthIs )
237 import BinIface ( writeBinIface )
238 import Unique ( Unique, Uniquable(..) )
239 import ErrUtils ( dumpIfSet_dyn, showPass )
240 import Digraph ( stronglyConnComp, SCC(..) )
241 import SrcLoc ( SrcSpan )
243 import PackageConfig ( PackageId )
247 import Monad ( when )
248 import List ( insert )
249 import Maybes ( orElse, mapCatMaybes, isNothing, isJust,
250 expectJust, catMaybes, MaybeErr(..) )
255 %************************************************************************
257 \subsection{Completing an interface}
259 %************************************************************************
263 -> Maybe ModIface -- The old interface, if we have it
264 -> ModGuts -- Usages, deprecations, etc
265 -> ModDetails -- The trimmed, tidied interface
266 -> IO (ModIface, -- The new one, complete with decls and versions
267 Bool) -- True <=> there was an old Iface, and the new one
268 -- is identical, so no need to write it
270 mkIface hsc_env maybe_old_iface
271 (ModGuts{ mg_module = this_mod,
275 mg_rdr_env = rdr_env,
276 mg_fix_env = fix_env,
277 mg_deprecs = src_deprecs })
278 (ModDetails{ md_insts = insts,
279 md_fam_insts = fam_insts,
282 md_exports = exports })
284 -- NB: notice that mkIface does not look at the bindings
285 -- only at the TypeEnv. The previous Tidy phase has
286 -- put exactly the info into the TypeEnv that we want
287 -- to expose in the interface
289 = do { eps <- hscEPS hsc_env
290 ; let { ext_nm_rhs = mkExtNameFn hsc_env eps this_mod
291 ; ext_nm_lhs = mkLhsNameFn this_mod
293 ; decls = [ tyThingToIfaceDecl ext_nm_rhs thing
294 | thing <- typeEnvElts type_env,
295 let name = getName thing,
296 not (isImplicitName name || isWiredInName name) ]
297 -- Don't put implicit Ids and class tycons in the interface file
298 -- Nor wired-in things; the compiler knows about them anyhow
300 ; fixities = [ (occ,fix)
301 | FixItem occ fix _ <- nameEnvElts fix_env]
302 ; deprecs = mkIfaceDeprec src_deprecs
303 ; iface_rules = map (coreRuleToIfaceRule
304 ext_nm_lhs ext_nm_rhs) rules
305 ; iface_insts = map (instanceToIfaceInst ext_nm_lhs) insts
306 ; iface_fam_insts = map (famInstToIfaceFamInst ext_nm_lhs)
309 ; intermediate_iface = ModIface {
310 mi_module = this_mod,
314 mi_exports = mkIfaceExports exports,
315 mi_insts = sortLe le_inst iface_insts,
316 mi_fam_insts= sortLe le_fam_inst iface_fam_insts,
317 mi_rules = sortLe le_rule iface_rules,
318 mi_fixities = fixities,
319 mi_deprecs = deprecs,
320 mi_globals = Just rdr_env,
322 -- Left out deliberately: filled in by addVersionInfo
323 mi_mod_vers = initialVersion,
324 mi_exp_vers = initialVersion,
325 mi_rule_vers = initialVersion,
326 mi_orphan = False, -- Always set by addVersionInfo, but
327 -- it's a strict field, so we can't omit it.
328 mi_decls = deliberatelyOmitted "decls",
329 mi_ver_fn = deliberatelyOmitted "ver_fn",
331 -- And build the cached values
332 mi_dep_fn = mkIfaceDepCache deprecs,
333 mi_fix_fn = mkIfaceFixCache fixities }
335 -- Add version information
336 ; (new_iface, no_change_at_all, pp_diffs, pp_orphs)
337 = _scc_ "versioninfo"
338 addVersionInfo maybe_old_iface intermediate_iface decls
342 ; when (isJust pp_orphs && dopt Opt_WarnOrphans dflags)
343 (printDump (expectJust "mkIface" pp_orphs))
344 ; when (dopt Opt_D_dump_hi_diffs dflags) (printDump pp_diffs)
345 ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
346 (pprModIface new_iface)
348 ; return (new_iface, no_change_at_all) }
350 r1 `le_rule` r2 = ifRuleName r1 <= ifRuleName r2
351 i1 `le_inst` i2 = ifDFun i1 <= ifDFun i2
352 i1 `le_fam_inst` i2 = ifFamInstTyConOcc i1 <= ifFamInstTyConOcc i2
354 dflags = hsc_dflags hsc_env
355 deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
356 ifFamInstTyConOcc = ifaceTyConOccName . ifFamInstTyCon
359 -----------------------------
360 writeIfaceFile :: ModLocation -> ModIface -> IO ()
361 writeIfaceFile location new_iface
362 = do createDirectoryHierarchy (directoryOf hi_file_path)
363 writeBinIface hi_file_path new_iface
364 where hi_file_path = ml_hi_file location
367 -----------------------------
368 mkExtNameFn :: HscEnv -> ExternalPackageState -> Module -> Name -> IfaceExtName
369 mkExtNameFn hsc_env eps this_mod
372 hpt = hsc_HPT hsc_env
376 | mod == this_mod = case nameParent_maybe name of
377 Nothing -> LocalTop occ
378 Just par -> LocalTopSub occ (nameOccName par)
379 | isWiredInName name = ExtPkg mod occ
380 | is_home mod = HomePkg mod_name occ vers
381 | otherwise = ExtPkg mod occ
383 dflags = hsc_dflags hsc_env
384 this_pkg = thisPackage dflags
385 is_home mod = modulePackageId mod == this_pkg
387 mod = nameModule name
388 mod_name = moduleName mod
389 occ = nameOccName name
390 par_occ = nameOccName (nameParent name)
391 -- The version of the *parent* is the one want
392 vers = lookupVersion mod par_occ occ
394 lookupVersion :: Module -> OccName -> OccName -> Version
395 -- Even though we're looking up a home-package thing, in
396 -- one-shot mode the imported interfaces may be in the PIT
397 lookupVersion mod par_occ occ
398 = mi_ver_fn iface par_occ `orElse`
399 pprPanic "lookupVers1" (ppr mod <+> ppr par_occ <+> ppr occ)
401 iface = lookupIfaceByModule (hsc_dflags hsc_env) hpt pit mod `orElse`
402 pprPanic "lookupVers2" (ppr mod <+> ppr par_occ <+> ppr occ)
405 ---------------------
406 -- mkLhsNameFn ignores versioning info altogether
407 -- It is used for the LHS of instance decls and rules, where we
408 -- there's no point in recording version info
409 mkLhsNameFn :: Module -> Name -> IfaceExtName
410 mkLhsNameFn this_mod name
411 | isInternalName name = pprTrace "mkLhsNameFn: unexpected internal" (ppr name) $
412 LocalTop occ -- Should not happen
413 | mod == this_mod = LocalTop occ
414 | otherwise = ExtPkg mod occ
416 mod = nameModule name
417 occ = nameOccName name
420 -----------------------------
421 -- Compute version numbers for local decls
423 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
424 -> ModIface -- The new interface decls (lacking decls)
425 -> [IfaceDecl] -- The new decls
427 Bool, -- True <=> no changes at all; no need to write new Iface
429 Maybe SDoc) -- Warnings about orphans
431 addVersionInfo Nothing new_iface new_decls
432 -- No old interface, so definitely write a new one!
433 = (new_iface { mi_orphan = anyNothing ifInstOrph (mi_insts new_iface)
434 || anyNothing ifRuleOrph (mi_rules new_iface),
435 mi_decls = [(initialVersion, decl) | decl <- new_decls],
436 mi_ver_fn = \n -> Just initialVersion },
438 ptext SLIT("No old interface file"),
439 pprOrphans orph_insts orph_rules)
441 orph_insts = filter (isNothing . ifInstOrph) (mi_insts new_iface)
442 orph_rules = filter (isNothing . ifRuleOrph) (mi_rules new_iface)
444 addVersionInfo (Just old_iface@(ModIface { mi_mod_vers = old_mod_vers,
445 mi_exp_vers = old_exp_vers,
446 mi_rule_vers = old_rule_vers,
447 mi_decls = old_decls,
448 mi_ver_fn = old_decl_vers,
449 mi_fix_fn = old_fixities }))
450 new_iface@(ModIface { mi_fix_fn = new_fixities })
453 | no_change_at_all = (old_iface, True, ptext SLIT("Interface file unchanged"), pp_orphs)
454 | otherwise = (final_iface, False, vcat [ptext SLIT("Interface file has changed"),
455 nest 2 pp_diffs], pp_orphs)
457 final_iface = new_iface { mi_mod_vers = bump_unless no_output_change old_mod_vers,
458 mi_exp_vers = bump_unless no_export_change old_exp_vers,
459 mi_rule_vers = bump_unless no_rule_change old_rule_vers,
460 mi_orphan = not (null new_orph_rules && null new_orph_insts),
461 mi_decls = decls_w_vers,
462 mi_ver_fn = mkIfaceVerCache decls_w_vers }
464 decls_w_vers = [(add_vers decl, decl) | decl <- new_decls]
467 (old_non_orph_insts, old_orph_insts) = mkOrphMap ifInstOrph (mi_insts old_iface)
468 (new_non_orph_insts, new_orph_insts) = mkOrphMap ifInstOrph (mi_insts new_iface)
469 same_insts occ = eqMaybeBy (eqListBy eqIfInst)
470 (lookupOccEnv old_non_orph_insts occ)
471 (lookupOccEnv new_non_orph_insts occ)
473 (old_non_orph_rules, old_orph_rules) = mkOrphMap ifRuleOrph (mi_rules old_iface)
474 (new_non_orph_rules, new_orph_rules) = mkOrphMap ifRuleOrph (mi_rules new_iface)
475 same_rules occ = eqMaybeBy (eqListBy eqIfRule)
476 (lookupOccEnv old_non_orph_rules occ)
477 (lookupOccEnv new_non_orph_rules occ)
479 -- Computing what changed
480 no_output_change = no_decl_change && no_rule_change &&
481 no_export_change && no_deprec_change
482 no_export_change = mi_exports new_iface == mi_exports old_iface -- Kept sorted
483 no_decl_change = isEmptyOccSet changed_occs
484 no_rule_change = not (changedWrt changed_occs (eqListBy eqIfRule old_orph_rules new_orph_rules)
485 || changedWrt changed_occs (eqListBy eqIfInst old_orph_insts new_orph_insts))
486 no_deprec_change = mi_deprecs new_iface == mi_deprecs old_iface
488 -- If the usages havn't changed either, we don't need to write the interface file
489 no_other_changes = mi_usages new_iface == mi_usages old_iface &&
490 mi_deps new_iface == mi_deps old_iface
491 no_change_at_all = no_output_change && no_other_changes
493 pp_diffs = vcat [pp_change no_export_change "Export list"
494 (ppr old_exp_vers <+> arrow <+> ppr (mi_exp_vers final_iface)),
495 pp_change no_rule_change "Rules"
496 (ppr old_rule_vers <+> arrow <+> ppr (mi_rule_vers final_iface)),
497 pp_change no_deprec_change "Deprecations" empty,
498 pp_change no_other_changes "Usages" empty,
500 pp_change True what info = empty
501 pp_change False what info = text what <+> ptext SLIT("changed") <+> info
504 old_decl_env = mkOccEnv [(ifName decl, decl) | (_,decl) <- old_decls]
505 same_fixity n = bool (old_fixities n == new_fixities n)
508 -- Adding version info
509 new_version = bumpVersion old_mod_vers -- Start from the old module version, not from zero
510 -- so that if you remove f, and then add it again,
511 -- you don't thereby reduce f's version number
512 add_vers decl | occ `elemOccSet` changed_occs = new_version
513 | otherwise = expectJust "add_vers" (old_decl_vers occ)
514 -- If it's unchanged, there jolly well
515 where -- should be an old version number
519 changed_occs :: OccSet
520 changed_occs = computeChangedOccs eq_info
522 eq_info :: [(OccName, IfaceEq)]
523 eq_info = map check_eq new_decls
524 check_eq new_decl | Just old_decl <- lookupOccEnv old_decl_env occ
525 = (occ, new_decl `eqIfDecl` old_decl &&&
526 eq_indirects new_decl)
527 | otherwise {- No corresponding old decl -}
530 occ = ifName new_decl
532 eq_indirects :: IfaceDecl -> IfaceEq
533 -- When seeing if two decls are the same, remember to
534 -- check whether any relevant fixity or rules have changed
535 eq_indirects (IfaceId {ifName = occ}) = eq_ind_occ occ
536 eq_indirects (IfaceClass {ifName = cls_occ, ifSigs = sigs})
537 = same_insts cls_occ &&&
538 eq_ind_occs [op | IfaceClassOp op _ _ <- sigs]
539 eq_indirects (IfaceData {ifName = tc_occ, ifCons = cons})
540 = same_insts tc_occ &&& same_fixity tc_occ &&& -- The TyCon can have a fixity too
541 eq_ind_occs (map ifConOcc (visibleIfConDecls cons))
542 eq_indirects other = Equal -- Synonyms and foreign declarations
544 eq_ind_occ :: OccName -> IfaceEq -- For class ops and Ids; check fixity and rules
545 eq_ind_occ occ = same_fixity occ &&& same_rules occ
546 eq_ind_occs = foldr ((&&&) . eq_ind_occ) Equal
550 pp_decl_diffs :: SDoc -- Nothing => no changes
552 | isEmptyOccSet changed_occs = empty
554 = vcat [ptext SLIT("Changed occs:") <+> ppr (occSetElts changed_occs),
555 ptext SLIT("Version change for these decls:"),
556 nest 2 (vcat (map show_change new_decls))]
558 eq_env = mkOccEnv eq_info
560 | not (occ `elemOccSet` changed_occs) = empty
562 = vcat [ppr occ <+> ppr (old_decl_vers occ) <+> arrow <+> ppr new_version,
565 occ = ifName new_decl
566 why = case lookupOccEnv eq_env occ of
567 Just (EqBut occs) -> sep [ppr occ <> colon, ptext SLIT("Free vars (only) changed:"),
568 nest 2 (braces (fsep (map ppr (occSetElts
569 (occs `intersectOccSet` changed_occs)))))]
571 | Just old_decl <- lookupOccEnv old_decl_env occ
572 -> vcat [ptext SLIT("Old:") <+> ppr old_decl,
573 ptext SLIT("New:") <+> ppr new_decl]
575 -> ppr occ <+> ptext SLIT("only in new interface")
576 other -> pprPanic "MkIface.show_change" (ppr occ)
578 pp_orphs = pprOrphans new_orph_insts new_orph_rules
580 pprOrphans insts rules
581 | null insts && null rules = Nothing
584 if null insts then empty else
585 hang (ptext SLIT("Warning: orphan instances:"))
586 2 (vcat (map ppr insts)),
587 if null rules then empty else
588 hang (ptext SLIT("Warning: orphan rules:"))
589 2 (vcat (map ppr rules))
592 computeChangedOccs :: [(OccName, IfaceEq)] -> OccSet
593 computeChangedOccs eq_info
594 = foldl add_changes emptyOccSet (stronglyConnComp edges)
596 edges :: [((OccName,IfaceEq), Unique, [Unique])]
597 edges = [ (node, getUnique occ, map getUnique occs)
598 | node@(occ, iface_eq) <- eq_info
599 , let occs = case iface_eq of
600 EqBut occ_set -> occSetElts occ_set
603 -- Changes in declarations
604 add_changes :: OccSet -> SCC (OccName, IfaceEq) -> OccSet
605 add_changes so_far (AcyclicSCC (occ, iface_eq))
606 | changedWrt so_far iface_eq -- This one has changed
607 = extendOccSet so_far occ
608 add_changes so_far (CyclicSCC pairs)
609 | changedWrt so_far (foldr1 (&&&) (map snd pairs)) -- One of this group has changed
610 = extendOccSetList so_far (map fst pairs)
611 add_changes so_far other = so_far
613 changedWrt :: OccSet -> IfaceEq -> Bool
614 changedWrt so_far Equal = False
615 changedWrt so_far NotEqual = True
616 changedWrt so_far (EqBut kids) = so_far `intersectsOccSet` kids
618 ----------------------
619 -- mkOrphMap partitions instance decls or rules into
620 -- (a) an OccEnv for ones that are not orphans,
621 -- mapping the local OccName to a list of its decls
622 -- (b) a list of orphan decls
623 mkOrphMap :: (decl -> Maybe OccName) -- (Just occ) for a non-orphan decl, keyed by occ
624 -- Nothing for an orphan decl
625 -> [decl] -- Sorted into canonical order
626 -> (OccEnv [decl], -- Non-orphan decls associated with their key;
627 -- each sublist in canonical order
628 [decl]) -- Orphan decls; in canonical order
629 mkOrphMap get_key decls
630 = foldl go (emptyOccEnv, []) decls
632 go (non_orphs, orphs) d
633 | Just occ <- get_key d
634 = (extendOccEnv_C (\ ds _ -> d:ds) non_orphs occ [d], orphs)
635 | otherwise = (non_orphs, d:orphs)
637 anyNothing :: (a -> Maybe b) -> [a] -> Bool
638 anyNothing p [] = False
639 anyNothing p (x:xs) = isNothing (p x) || anyNothing p xs
641 ----------------------
642 mkIfaceDeprec :: Deprecations -> IfaceDeprecs
643 mkIfaceDeprec NoDeprecs = NoDeprecs
644 mkIfaceDeprec (DeprecAll t) = DeprecAll t
645 mkIfaceDeprec (DeprecSome env) = DeprecSome (sortLe (<=) (nameEnvElts env))
647 ----------------------
648 bump_unless :: Bool -> Version -> Version
649 bump_unless True v = v -- True <=> no change
650 bump_unless False v = bumpVersion v
654 %*********************************************************
656 \subsection{Keeping track of what we've slurped, and version numbers}
658 %*********************************************************
662 mkUsageInfo :: HscEnv
663 -> ModuleEnv (Module, Bool, SrcSpan)
664 -> [(ModuleName, IsBootInterface)]
665 -> NameSet -> IO [Usage]
666 mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
667 = do { eps <- hscEPS hsc_env
668 ; let usages = mk_usage_info (eps_PIT eps) hsc_env
669 dir_imp_mods dep_mods used_names
670 ; usages `seqList` return usages }
671 -- seq the list of Usages returned: occasionally these
672 -- don't get evaluated for a while and we can end up hanging on to
673 -- the entire collection of Ifaces.
675 mk_usage_info pit hsc_env dir_imp_mods dep_mods proto_used_names
676 = mapCatMaybes mkUsage dep_mods
677 -- ToDo: do we need to sort into canonical order?
679 hpt = hsc_HPT hsc_env
680 dflags = hsc_dflags hsc_env
682 used_names = mkNameSet $ -- Eliminate duplicates
683 [ nameParent n -- Just record usage on the 'main' names
684 | n <- nameSetToList proto_used_names
685 , not (isWiredInName n) -- Don't record usages for wired-in names
686 , isExternalName n -- Ignore internal names
689 -- ent_map groups together all the things imported and used
690 -- from a particular module in this package
691 ent_map :: ModuleEnv [OccName]
692 ent_map = foldNameSet add_mv emptyModuleEnv used_names
693 add_mv name mv_map = extendModuleEnv_C add_item mv_map mod [occ]
695 occ = nameOccName name
696 mod = nameModule name
697 add_item occs _ = occ:occs
699 depend_on_exports mod = case lookupModuleEnv dir_imp_mods mod of
700 Just (_,no_imp,_) -> not no_imp
703 -- We want to create a Usage for a home module if
704 -- a) we used something from; has something in used_names
705 -- b) we imported all of it, even if we used nothing from it
706 -- (need to recompile if its export list changes: export_vers)
707 -- c) is a home-package orphan module (need to recompile if its
708 -- instance decls change: rules_vers)
709 mkUsage :: (ModuleName, IsBootInterface) -> Maybe Usage
710 mkUsage (mod_name, _)
711 | isNothing maybe_iface -- We can't depend on it if we didn't
712 || (null used_occs -- load its interface.
713 && isNothing export_vers
715 = Nothing -- Record no usage info
718 = Just (Usage { usg_name = mod_name,
720 usg_exports = export_vers,
721 usg_entities = ent_vers,
722 usg_rules = rules_vers })
724 maybe_iface = lookupIfaceByModule dflags hpt pit mod
725 -- In one-shot mode, the interfaces for home-package
726 -- modules accumulate in the PIT not HPT. Sigh.
728 mod = mkModule (thisPackage dflags) mod_name
730 Just iface = maybe_iface
731 orphan_mod = mi_orphan iface
732 version_env = mi_ver_fn iface
733 mod_vers = mi_mod_vers iface
734 rules_vers = mi_rule_vers iface
735 export_vers | depend_on_exports mod = Just (mi_exp_vers iface)
736 | otherwise = Nothing
738 -- The sort is to put them into canonical order
739 used_occs = lookupModuleEnv ent_map mod `orElse` []
740 ent_vers :: [(OccName,Version)]
741 ent_vers = [ (occ, version_env occ `orElse` initialVersion)
742 | occ <- sortLe (<=) used_occs]
746 mkIfaceExports :: NameSet -> [(Module, [GenAvailInfo OccName])]
747 -- Group by module and sort by occurrence
748 -- This keeps the list in canonical order
749 mkIfaceExports exports
750 = [ (mod, eltsUFM avails)
751 | (mod, avails) <- fmToList groupFM
754 groupFM :: ModuleEnv (UniqFM (GenAvailInfo OccName))
755 -- Deliberately use the FastString so we
756 -- get a canonical ordering
757 groupFM = foldl add emptyModuleEnv (nameSetToList exports)
759 add env name = extendModuleEnv_C add_avail env mod
760 (unitUFM avail_fs avail)
762 occ = nameOccName name
763 mod = nameModule name
764 avail | Just p <- nameParent_maybe name = AvailTC (nameOccName p) [occ]
765 | isTcOcc occ = AvailTC occ [occ]
766 | otherwise = Avail occ
767 avail_fs = occNameFS (availName avail)
768 add_avail avail_fm _ = addToUFM_C add_item avail_fm avail_fs avail
770 add_item (AvailTC p occs) _ = AvailTC p (List.insert occ occs)
771 add_item (Avail n) _ = pprPanic "MkIface.addAvail" (ppr n <+> ppr name)
775 %************************************************************************
777 Load the old interface file for this module (unless
778 we have it aleady), and check whether it is up to date
781 %************************************************************************
784 checkOldIface :: HscEnv
786 -> Bool -- Source unchanged
787 -> Maybe ModIface -- Old interface from compilation manager, if any
788 -> IO (RecompileRequired, Maybe ModIface)
790 checkOldIface hsc_env mod_summary source_unchanged maybe_iface
791 = do { showPass (hsc_dflags hsc_env)
792 ("Checking old interface for " ++
793 showSDoc (ppr (ms_mod mod_summary))) ;
795 ; initIfaceCheck hsc_env $
796 check_old_iface hsc_env mod_summary source_unchanged maybe_iface
799 check_old_iface hsc_env mod_summary source_unchanged maybe_iface
800 = do -- CHECK WHETHER THE SOURCE HAS CHANGED
801 { ifM (not source_unchanged)
802 (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
804 -- If the source has changed and we're in interactive mode, avoid reading
805 -- an interface; just return the one we might have been supplied with.
806 ; ghc_mode <- getGhcMode
807 ; if (ghc_mode == Interactive || ghc_mode == JustTypecheck)
808 && not source_unchanged then
809 return (outOfDate, maybe_iface)
811 case maybe_iface of {
812 Just old_iface -> do -- Use the one we already have
813 { traceIf (text "We already have the old interface for" <+> ppr (ms_mod mod_summary))
814 ; recomp <- checkVersions hsc_env source_unchanged old_iface
815 ; return (recomp, Just old_iface) }
819 -- Try and read the old interface for the current module
820 -- from the .hi file left from the last time we compiled it
821 { let iface_path = msHiFilePath mod_summary
822 ; read_result <- readIface (ms_mod mod_summary) iface_path False
823 ; case read_result of {
824 Failed err -> do -- Old interface file not found, or garbled; give up
825 { traceIf (text "FYI: cannot read old interface file:"
827 ; return (outOfDate, Nothing) }
829 ; Succeeded iface -> do
831 -- We have got the old iface; check its versions
832 { traceIf (text "Read the interface file" <+> text iface_path)
833 ; recomp <- checkVersions hsc_env source_unchanged iface
834 ; returnM (recomp, Just iface)
838 @recompileRequired@ is called from the HscMain. It checks whether
839 a recompilation is required. It needs access to the persistent state,
840 finder, etc, because it may have to load lots of interface files to
841 check their versions.
844 type RecompileRequired = Bool
845 upToDate = False -- Recompile not required
846 outOfDate = True -- Recompile required
848 checkVersions :: HscEnv
849 -> Bool -- True <=> source unchanged
850 -> ModIface -- Old interface
851 -> IfG RecompileRequired
852 checkVersions hsc_env source_unchanged iface
853 | not source_unchanged
856 = do { traceHiDiffs (text "Considering whether compilation is required for" <+>
857 ppr (mi_module iface) <> colon)
859 -- Source code unchanged and no errors yet... carry on
861 -- First put the dependent-module info, read from the old interface, into the envt,
862 -- so that when we look for interfaces we look for the right one (.hi or .hi-boot)
864 -- It's just temporary because either the usage check will succeed
865 -- (in which case we are done with this module) or it'll fail (in which
866 -- case we'll compile the module from scratch anyhow).
868 -- We do this regardless of compilation mode, although in --make mode
869 -- all the dependent modules should be in the HPT already, so it's
871 ; updateEps_ $ \eps -> eps { eps_is_boot = mod_deps }
873 ; let this_pkg = thisPackage (hsc_dflags hsc_env)
874 ; checkList [checkModUsage this_pkg u | u <- mi_usages iface]
877 -- This is a bit of a hack really
878 mod_deps :: ModuleNameEnv (ModuleName, IsBootInterface)
879 mod_deps = mkModDeps (dep_mods (mi_deps iface))
881 checkModUsage :: PackageId ->Usage -> IfG RecompileRequired
882 -- Given the usage information extracted from the old
883 -- M.hi file for the module being compiled, figure out
884 -- whether M needs to be recompiled.
886 checkModUsage this_pkg (Usage { usg_name = mod_name, usg_mod = old_mod_vers,
887 usg_rules = old_rule_vers,
888 usg_exports = maybe_old_export_vers,
889 usg_entities = old_decl_vers })
890 = -- Load the imported interface is possible
892 doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
894 traceHiDiffs (text "Checking usages for module" <+> ppr mod_name) `thenM_`
897 mod = mkModule this_pkg mod_name
899 loadInterface doc_str mod ImportBySystem `thenM` \ mb_iface ->
900 -- Load the interface, but don't complain on failure;
901 -- Instead, get an Either back which we can test
904 Failed exn -> (out_of_date (sep [ptext SLIT("Can't find version number for module"),
906 -- Couldn't find or parse a module mentioned in the
907 -- old interface file. Don't complain -- it might just be that
908 -- the current module doesn't need that import and it's been deleted
912 new_mod_vers = mi_mod_vers iface
913 new_decl_vers = mi_ver_fn iface
914 new_export_vers = mi_exp_vers iface
915 new_rule_vers = mi_rule_vers iface
918 checkModuleVersion old_mod_vers new_mod_vers `thenM` \ recompile ->
919 if not recompile then
924 if checkExportList maybe_old_export_vers new_export_vers then
925 out_of_date_vers (ptext SLIT(" Export list changed"))
926 (expectJust "checkModUsage" maybe_old_export_vers)
931 if old_rule_vers /= new_rule_vers then
932 out_of_date_vers (ptext SLIT(" Rules changed"))
933 old_rule_vers new_rule_vers
936 -- CHECK ITEMS ONE BY ONE
937 checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers] `thenM` \ recompile ->
939 returnM outOfDate -- This one failed, so just bail out now
941 up_to_date (ptext SLIT(" Great! The bits I use are up to date"))
944 ------------------------
945 checkModuleVersion old_mod_vers new_mod_vers
946 | new_mod_vers == old_mod_vers
947 = up_to_date (ptext SLIT("Module version unchanged"))
950 = out_of_date_vers (ptext SLIT(" Module version has changed"))
951 old_mod_vers new_mod_vers
953 ------------------------
954 checkExportList Nothing new_vers = upToDate
955 checkExportList (Just v) new_vers = v /= new_vers
957 ------------------------
958 checkEntityUsage new_vers (name,old_vers)
959 = case new_vers name of
961 Nothing -> -- We used it before, but it ain't there now
962 out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
964 Just new_vers -- It's there, but is it up to date?
965 | new_vers == old_vers -> traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_vers)) `thenM_`
967 | otherwise -> out_of_date_vers (ptext SLIT(" Out of date:") <+> ppr name)
970 up_to_date msg = traceHiDiffs msg `thenM_` returnM upToDate
971 out_of_date msg = traceHiDiffs msg `thenM_` returnM outOfDate
972 out_of_date_vers msg old_vers new_vers
973 = out_of_date (hsep [msg, ppr old_vers, ptext SLIT("->"), ppr new_vers])
975 ----------------------
976 checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
977 -- This helper is used in two places
978 checkList [] = returnM upToDate
979 checkList (check:checks) = check `thenM` \ recompile ->
986 %************************************************************************
988 Converting things to their Iface equivalents
990 %************************************************************************
993 tyThingToIfaceDecl :: (Name -> IfaceExtName) -> TyThing -> IfaceDecl
994 -- Assumption: the thing is already tidied, so that locally-bound names
995 -- (lambdas, for-alls) already have non-clashing OccNames
996 -- Reason: Iface stuff uses OccNames, and the conversion here does
997 -- not do tidying on the way
998 tyThingToIfaceDecl ext (AnId id)
999 = IfaceId { ifName = getOccName id,
1000 ifType = toIfaceType ext (idType id),
1003 info = case toIfaceIdInfo ext (idInfo id) of
1005 items -> HasInfo items
1007 tyThingToIfaceDecl ext (AClass clas)
1008 = IfaceClass { ifCtxt = toIfaceContext ext sc_theta,
1009 ifName = getOccName clas,
1010 ifTyVars = toIfaceTvBndrs clas_tyvars,
1011 ifFDs = map toIfaceFD clas_fds,
1012 ifATs = map (tyThingToIfaceDecl ext . ATyCon) clas_ats,
1013 ifSigs = map toIfaceClassOp op_stuff,
1014 ifRec = boolToRecFlag (isRecursiveTyCon tycon) }
1016 (clas_tyvars, clas_fds, sc_theta, _, clas_ats, op_stuff)
1017 = classExtraBigSig clas
1018 tycon = classTyCon clas
1020 toIfaceClassOp (sel_id, def_meth)
1021 = ASSERT(sel_tyvars == clas_tyvars)
1022 IfaceClassOp (getOccName sel_id) def_meth (toIfaceType ext op_ty)
1024 -- Be careful when splitting the type, because of things
1025 -- like class Foo a where
1026 -- op :: (?x :: String) => a -> a
1027 -- and class Baz a where
1028 -- op :: (Ord a) => a -> a
1029 (sel_tyvars, rho_ty) = splitForAllTys (idType sel_id)
1030 op_ty = funResultTy rho_ty
1032 toIfaceFD (tvs1, tvs2) = (map (occNameFS.getOccName) tvs1, map (occNameFS.getOccName) tvs2)
1034 tyThingToIfaceDecl ext (ATyCon tycon)
1036 = IfaceSyn { ifName = getOccName tycon,
1037 ifTyVars = toIfaceTvBndrs tyvars,
1038 ifOpenSyn = syn_isOpen,
1039 ifSynRhs = toIfaceType ext syn_tyki }
1042 = IfaceData { ifName = getOccName tycon,
1043 ifTyVars = toIfaceTvBndrs tyvars,
1044 ifCtxt = toIfaceContext ext (tyConStupidTheta tycon),
1045 ifCons = ifaceConDecls (algTyConRhs tycon),
1046 ifRec = boolToRecFlag (isRecursiveTyCon tycon),
1047 ifGadtSyntax = isGadtSyntaxTyCon tycon,
1048 ifGeneric = tyConHasGenerics tycon,
1049 ifFamInst = famInstToIface (tyConFamInst_maybe tycon)}
1051 | isForeignTyCon tycon
1052 = IfaceForeign { ifName = getOccName tycon,
1053 ifExtName = tyConExtName tycon }
1055 | isPrimTyCon tycon || isFunTyCon tycon
1056 -- Needed in GHCi for ':info Int#', for example
1057 = IfaceData { ifName = getOccName tycon,
1058 ifTyVars = toIfaceTvBndrs (take (tyConArity tycon) alphaTyVars),
1060 ifCons = IfAbstractTyCon,
1061 ifGadtSyntax = False,
1063 ifRec = NonRecursive,
1064 ifFamInst = Nothing }
1066 | otherwise = pprPanic "toIfaceDecl" (ppr tycon)
1068 tyvars = tyConTyVars tycon
1069 (syn_isOpen, syn_tyki) = case synTyConRhs tycon of
1070 OpenSynTyCon ki -> (True , ki)
1071 SynonymTyCon ty -> (False, ty)
1073 ifaceConDecls (NewTyCon { data_con = con }) =
1074 IfNewTyCon (ifaceConDecl con)
1075 ifaceConDecls (DataTyCon { data_cons = cons }) =
1076 IfDataTyCon (map ifaceConDecl cons)
1077 ifaceConDecls OpenDataTyCon = IfOpenDataTyCon
1078 ifaceConDecls OpenNewTyCon = IfOpenNewTyCon
1079 ifaceConDecls AbstractTyCon = IfAbstractTyCon
1080 -- The last case happens when a TyCon has been trimmed during tidying
1081 -- Furthermore, tyThingToIfaceDecl is also used
1082 -- in TcRnDriver for GHCi, when browsing a module, in which case the
1083 -- AbstractTyCon case is perfectly sensible.
1085 ifaceConDecl data_con
1086 = IfCon { ifConOcc = getOccName (dataConName data_con),
1087 ifConInfix = dataConIsInfix data_con,
1088 ifConUnivTvs = toIfaceTvBndrs (dataConUnivTyVars data_con),
1089 ifConExTvs = toIfaceTvBndrs (dataConExTyVars data_con),
1090 ifConEqSpec = to_eq_spec (dataConEqSpec data_con),
1091 ifConCtxt = toIfaceContext ext (dataConTheta data_con),
1092 ifConArgTys = map (toIfaceType ext)
1093 (dataConOrigArgTys data_con),
1094 ifConFields = map getOccName
1095 (dataConFieldLabels data_con),
1096 ifConStricts = dataConStrictMarks data_con }
1098 to_eq_spec spec = [(getOccName tv, toIfaceType ext ty) | (tv,ty) <- spec]
1100 famInstToIface Nothing = Nothing
1101 famInstToIface (Just (famTyCon, instTys)) =
1102 Just (toIfaceTyCon ext famTyCon, map (toIfaceType ext) instTys)
1104 tyThingToIfaceDecl ext (ADataCon dc)
1105 = pprPanic "toIfaceDecl" (ppr dc) -- Should be trimmed out earlier
1108 --------------------------
1109 instanceToIfaceInst :: (Name -> IfaceExtName) -> Instance -> IfaceInst
1110 instanceToIfaceInst ext_lhs ispec@(Instance { is_dfun = dfun_id, is_flag = oflag,
1111 is_cls = cls, is_tcs = mb_tcs,
1113 = IfaceInst { ifDFun = getOccName dfun_id,
1115 ifInstCls = ext_lhs cls,
1116 ifInstTys = map do_rough mb_tcs,
1119 do_rough Nothing = Nothing
1120 do_rough (Just n) = Just (toIfaceTyCon_name ext_lhs n)
1122 --------------------------
1123 famInstToIfaceFamInst :: (Name -> IfaceExtName) -> FamInst -> IfaceFamInst
1124 famInstToIfaceFamInst ext_lhs fi@(FamInst { fi_tycon = tycon,
1125 fi_fam = fam, fi_tcs = mb_tcs })
1126 = IfaceFamInst { ifFamInstTyCon = toIfaceTyCon ext_lhs tycon
1127 , ifFamInstFam = ext_lhs fam
1128 , ifFamInstTys = map do_rough mb_tcs }
1130 do_rough Nothing = Nothing
1131 do_rough (Just n) = Just (toIfaceTyCon_name ext_lhs n)
1133 --------------------------
1134 toIfaceIdInfo :: (Name -> IfaceExtName) -> IdInfo -> [IfaceInfoItem]
1135 toIfaceIdInfo ext id_info
1136 = catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo,
1137 inline_hsinfo, wrkr_hsinfo, unfold_hsinfo]
1139 ------------ Arity --------------
1140 arity_info = arityInfo id_info
1141 arity_hsinfo | arity_info == 0 = Nothing
1142 | otherwise = Just (HsArity arity_info)
1144 ------------ Caf Info --------------
1145 caf_info = cafInfo id_info
1146 caf_hsinfo = case caf_info of
1147 NoCafRefs -> Just HsNoCafRefs
1150 ------------ Strictness --------------
1151 -- No point in explicitly exporting TopSig
1152 strict_hsinfo = case newStrictnessInfo id_info of
1153 Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
1156 ------------ Worker --------------
1157 work_info = workerInfo id_info
1158 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
1159 wrkr_hsinfo = case work_info of
1160 HasWorker work_id wrap_arity ->
1161 Just (HsWorker (ext (idName work_id)) wrap_arity)
1164 ------------ Unfolding --------------
1165 -- The unfolding is redundant if there is a worker
1166 unfold_info = unfoldingInfo id_info
1167 rhs = unfoldingTemplate unfold_info
1168 no_unfolding = neverUnfold unfold_info
1169 -- The CoreTidy phase retains unfolding info iff
1170 -- we want to expose the unfolding, taking into account
1171 -- unconditional NOINLINE, etc. See TidyPgm.addExternal
1172 unfold_hsinfo | no_unfolding = Nothing
1173 | has_worker = Nothing -- Unfolding is implicit
1174 | otherwise = Just (HsUnfold (toIfaceExpr ext rhs))
1176 ------------ Inline prag --------------
1177 inline_prag = inlinePragInfo id_info
1178 inline_hsinfo | isAlwaysActive inline_prag = Nothing
1179 | no_unfolding && not has_worker = Nothing
1180 -- If the iface file give no unfolding info, we
1181 -- don't need to say when inlining is OK!
1182 | otherwise = Just (HsInline inline_prag)
1184 --------------------------
1185 coreRuleToIfaceRule :: (Name -> IfaceExtName) -- For the LHS names
1186 -> (Name -> IfaceExtName) -- For the RHS names
1187 -> CoreRule -> IfaceRule
1188 coreRuleToIfaceRule ext_lhs ext_rhs (BuiltinRule { ru_fn = fn})
1189 = pprTrace "toHsRule: builtin" (ppr fn) $
1190 bogusIfaceRule (mkIfaceExtName fn)
1192 coreRuleToIfaceRule ext_lhs ext_rhs
1193 (Rule { ru_name = name, ru_fn = fn, ru_act = act, ru_bndrs = bndrs,
1194 ru_args = args, ru_rhs = rhs, ru_orph = orph })
1195 = IfaceRule { ifRuleName = name, ifActivation = act,
1196 ifRuleBndrs = map (toIfaceBndr ext_lhs) bndrs,
1197 ifRuleHead = ext_lhs fn,
1198 ifRuleArgs = map do_arg args,
1199 ifRuleRhs = toIfaceExpr ext_rhs rhs,
1202 -- For type args we must remove synonyms from the outermost
1203 -- level. Reason: so that when we read it back in we'll
1204 -- construct the same ru_rough field as we have right now;
1206 do_arg (Type ty) = IfaceType (toIfaceType ext_lhs (deNoteType ty))
1207 do_arg arg = toIfaceExpr ext_lhs arg
1209 bogusIfaceRule :: IfaceExtName -> IfaceRule
1210 bogusIfaceRule id_name
1211 = IfaceRule { ifRuleName = FSLIT("bogus"), ifActivation = NeverActive,
1212 ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [],
1213 ifRuleRhs = IfaceExt id_name, ifRuleOrph = Nothing }
1215 ---------------------
1216 toIfaceExpr :: (Name -> IfaceExtName) -> CoreExpr -> IfaceExpr
1217 toIfaceExpr ext (Var v) = toIfaceVar ext v
1218 toIfaceExpr ext (Lit l) = IfaceLit l
1219 toIfaceExpr ext (Type ty) = IfaceType (toIfaceType ext ty)
1220 toIfaceExpr ext (Lam x b) = IfaceLam (toIfaceBndr ext x) (toIfaceExpr ext b)
1221 toIfaceExpr ext (App f a) = toIfaceApp ext f [a]
1222 toIfaceExpr ext (Case s x ty as) = IfaceCase (toIfaceExpr ext s) (occNameFS (getOccName x)) (toIfaceType ext ty) (map (toIfaceAlt ext) as)
1223 toIfaceExpr ext (Let b e) = IfaceLet (toIfaceBind ext b) (toIfaceExpr ext e)
1224 toIfaceExpr ext (Cast e co) = IfaceCast (toIfaceExpr ext e) (toIfaceType ext co)
1225 toIfaceExpr ext (Note n e) = IfaceNote (toIfaceNote ext n) (toIfaceExpr ext e)
1227 ---------------------
1228 toIfaceNote ext (SCC cc) = IfaceSCC cc
1229 toIfaceNote ext InlineMe = IfaceInlineMe
1230 toIfaceNote ext (CoreNote s) = IfaceCoreNote s
1232 ---------------------
1233 toIfaceBind ext (NonRec b r) = IfaceNonRec (toIfaceIdBndr ext b) (toIfaceExpr ext r)
1234 toIfaceBind ext (Rec prs) = IfaceRec [(toIfaceIdBndr ext b, toIfaceExpr ext r) | (b,r) <- prs]
1236 ---------------------
1237 toIfaceAlt ext (c,bs,r) = (toIfaceCon c, map (occNameFS.getOccName) bs, toIfaceExpr ext r)
1239 ---------------------
1240 toIfaceCon (DataAlt dc) | isTupleTyCon tc = IfaceTupleAlt (tupleTyConBoxity tc)
1241 | otherwise = IfaceDataAlt (getOccName dc)
1243 tc = dataConTyCon dc
1245 toIfaceCon (LitAlt l) = IfaceLitAlt l
1246 toIfaceCon DEFAULT = IfaceDefault
1248 ---------------------
1249 toIfaceApp ext (App f a) as = toIfaceApp ext f (a:as)
1250 toIfaceApp ext (Var v) as
1251 = case isDataConWorkId_maybe v of
1252 -- We convert the *worker* for tuples into IfaceTuples
1253 Just dc | isTupleTyCon tc && saturated
1254 -> IfaceTuple (tupleTyConBoxity tc) tup_args
1256 val_args = dropWhile isTypeArg as
1257 saturated = val_args `lengthIs` idArity v
1258 tup_args = map (toIfaceExpr ext) val_args
1259 tc = dataConTyCon dc
1261 other -> mkIfaceApps ext (toIfaceVar ext v) as
1263 toIfaceApp ext e as = mkIfaceApps ext (toIfaceExpr ext e) as
1265 mkIfaceApps ext f as = foldl (\f a -> IfaceApp f (toIfaceExpr ext a)) f as
1267 ---------------------
1268 toIfaceVar :: (Name -> IfaceExtName) -> Id -> IfaceExpr
1270 | Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType ext (idType v))
1271 -- Foreign calls have special syntax
1272 | isExternalName name = IfaceExt (ext name)
1273 | otherwise = IfaceLcl (occNameFS (nameOccName name))