2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
10 mkIface, -- Build a ModIface from a ModGuts,
11 -- including computing version information
15 writeIfaceFile, -- Write the interface file
17 checkOldIface, -- See if recompilation is required, by
18 -- comparing version information
20 tyThingToIfaceDecl -- Converting things to their Iface equivalents
24 -----------------------------------------------
25 MkIface.lhs deals with versioning
26 -----------------------------------------------
28 Here's the version-related info in an interface file
30 module Foo 8 -- module-version
31 3 -- export-list-version
33 Usages: -- Version info for what this compilation of Foo imported
34 Baz 3 -- Module version
35 [4] -- The export-list version if Foo depended on it
36 (g,2) -- Function and its version
37 (T,1) -- Type and its version
39 <version> f :: Int -> Int {- Unfolding: \x -> Wib.t[2] x -}
40 -- The [2] says that f's unfolding
41 -- mentions verison 2 of Wib.t
43 -----------------------------------------------
45 -----------------------------------------------
48 * In the mi_usages information in an interface, we record the
49 version number of each free variable of the module
51 * In mkIface, we compute the version number of each exported thing A.f
52 by comparing its A.f's info with its new info, and bumping its
53 version number if it differs. If A.f mentions B.g, and B.g's version
54 number has changed, then we count A.f as having changed too.
56 * In checkOldIface we compare the mi_usages for the module with
57 the actual version info for all each thing recorded in mi_usages
62 We count A.f as changing if its fixity changes
66 If a rule changes, we want to recompile any module that might be
67 affected by that rule. For non-orphan rules, this is relatively easy.
68 If module M defines f, and a rule for f, just arrange that the version
69 number for M.f changes if any of the rules for M.f change. Any module
70 that does not depend on M.f can't be affected by the rule-change
73 Orphan rules (ones whose 'head function' is not defined in M) are
74 harder. Here's what we do.
76 * We have a per-module orphan-rule version number which changes if
77 any orphan rule changes. (It's unaffected by non-orphan rules.)
79 * We record usage info for any orphan module 'below' this one,
80 giving the orphan-rule version number. We recompile if this
83 The net effect is that if an orphan rule changes, we recompile every
84 module above it. That's very conservative, but it's devilishly hard
85 to know what it might affect, so we just have to be conservative.
89 In an iface file we have
91 instance Eq a => Eq [a] = dfun29
94 We have a version number for dfun29, covering its unfolding
95 etc. Suppose we are compiling a module M that imports A only
96 indirectly. If typechecking M uses this instance decl, we record the
97 dependency on A.dfun29 as if it were a free variable of the module
98 (via the tcg_inst_usages accumulator). That means that A will appear
99 in M's usage list. If the shape of the instance declaration changes,
100 then so will dfun29's version, triggering a recompilation.
102 Adding an instance declaration, or changing an instance decl that is
103 not currently used, is more tricky. (This really only makes a
104 difference when we have overlapping instance decls, because then the
105 new instance decl might kick in to override the old one.) We handle
106 this in a very similar way that we handle rules above.
108 * For non-orphan instance decls, identify one locally-defined tycon/class
109 mentioned in the decl. Treat the instance decl as part of the defn of that
110 tycon/class, so that if the shape of the instance decl changes, so does the
111 tycon/class; that in turn will force recompilation of anything that uses
114 * For orphan instance decls, act the same way as for orphan rules.
115 Indeed, we use the same global orphan-rule version number.
119 mkUsageInfo figures out what the ``usage information'' for this
120 moudule is; that is, what it must record in its interface file as the
123 We produce a line for every module B below the module, A, currently being
126 to record the fact that A does import B indirectly. This is used to decide
127 to look for B.hi rather than B.hi-boot when compiling a module that
128 imports A. This line says that A imports B, but uses nothing in it.
129 So we'll get an early bale-out when compiling A if B's version changes.
131 The usage information records:
134 \item (a) anything reachable from its body code
135 \item (b) any module exported with a @module Foo@
136 \item (c) anything reachable from an exported item
139 Why (b)? Because if @Foo@ changes then this module's export list
140 will change, so we must recompile this module at least as far as
141 making a new interface file --- but in practice that means complete
144 Why (c)? Consider this:
146 module A( f, g ) where | module B( f ) where
147 import B( f ) | f = h 3
151 Here, @B.f@ isn't used in A. Should we nevertheless record @B.f@ in
152 @A@'s usages? Our idea is that we aren't going to touch A.hi if it is
153 *identical* to what it was before. If anything about @B.f@ changes
154 than anyone who imports @A@ should be recompiled in case they use
155 @B.f@ (they'll get an early exit if they don't). So, if anything
156 about @B.f@ changes we'd better make sure that something in A.hi
157 changes, and the convenient way to do that is to record the version
158 number @B.f@ in A.hi in the usage list. If B.f changes that'll force a
159 complete recompiation of A, which is overkill but it's the only way to
160 write a new, slightly different, A.hi.
162 But the example is tricker. Even if @B.f@ doesn't change at all,
163 @B.h@ may do so, and this change may not be reflected in @f@'s version
164 number. But with -O, a module that imports A must be recompiled if
165 @B.h@ changes! So A must record a dependency on @B.h@. So we treat
166 the occurrence of @B.f@ in the export list *just as if* it were in the
167 code of A, and thereby haul in all the stuff reachable from it.
169 *** Conclusion: if A mentions B.f in its export list,
170 behave just as if A mentioned B.f in its source code,
171 and slurp in B.f and all its transitive closure ***
173 [NB: If B was compiled with -O, but A isn't, we should really *still*
174 haul in all the unfoldings for B, in case the module that imports A *is*
175 compiled with -O. I think this is the case.]
177 SimonM [30/11/2007]: I believe the above is all out of date; the
178 current implementation doesn't do it this way. Instead, when any of
179 the dependencies of a declaration changes, the version of the
180 declaration itself changes.
183 #include "HsVersions.h"
218 import BasicTypes hiding ( SuccessFlag(..) )
220 import Util hiding ( eqListBy )
229 import System.FilePath
234 %************************************************************************
236 \subsection{Completing an interface}
238 %************************************************************************
242 -> Maybe ModIface -- The old interface, if we have it
243 -> ModDetails -- The trimmed, tidied interface
244 -> ModGuts -- Usages, deprecations, etc
245 -> IO (ModIface, -- The new one, complete with decls and versions
246 Bool) -- True <=> there was an old Iface, and the new one
247 -- is identical, so no need to write it
249 mkIface hsc_env maybe_old_iface mod_details
250 ModGuts{ mg_module = this_mod,
252 mg_used_names = used_names,
254 mg_dir_imps = dir_imp_mods,
255 mg_rdr_env = rdr_env,
256 mg_fix_env = fix_env,
257 mg_deprecs = deprecs,
258 mg_hpc_info = hpc_info }
259 = mkIface_ hsc_env maybe_old_iface
260 this_mod is_boot used_names deps rdr_env
261 fix_env deprecs hpc_info dir_imp_mods mod_details
263 -- | make an interface from the results of typechecking only. Useful
264 -- for non-optimising compilation, or where we aren't generating any
265 -- object code at all ('HscNothing').
267 -> Maybe ModIface -- The old interface, if we have it
268 -> ModDetails -- gotten from mkBootModDetails, probably
269 -> TcGblEnv -- Usages, deprecations, etc
272 mkIfaceTc hsc_env maybe_old_iface mod_details
273 tc_result@TcGblEnv{ tcg_mod = this_mod,
275 tcg_imports = imports,
276 tcg_rdr_env = rdr_env,
277 tcg_fix_env = fix_env,
278 tcg_deprecs = deprecs,
279 tcg_hpc = other_hpc_info
282 used_names <- mkUsedNames tc_result
283 deps <- mkDependencies tc_result
284 let hpc_info = emptyHpcInfo other_hpc_info
285 mkIface_ hsc_env maybe_old_iface
286 this_mod (isHsBoot hsc_src) used_names deps rdr_env
287 fix_env deprecs hpc_info (imp_mods imports) mod_details
290 mkUsedNames :: TcGblEnv -> IO NameSet
292 TcGblEnv{ tcg_inst_uses = dfun_uses_var,
296 dfun_uses <- readIORef dfun_uses_var -- What dfuns are used
297 return (allUses dus `unionNameSets` dfun_uses)
299 mkDependencies :: TcGblEnv -> IO Dependencies
301 TcGblEnv{ tcg_mod = mod,
302 tcg_imports = imports,
306 th_used <- readIORef th_var -- Whether TH is used
308 dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
309 -- M.hi-boot can be in the imp_dep_mods, but we must remove
310 -- it before recording the modules on which this one depends!
311 -- (We want to retain M.hi-boot in imp_dep_mods so that
312 -- loadHiBootInterface can see if M's direct imports depend
313 -- on M.hi-boot, and hence that we should do the hi-boot consistency
316 -- Modules don't compare lexicographically usually,
317 -- but we want them to do so here.
318 le_mod :: Module -> Module -> Bool
319 le_mod m1 m2 = moduleNameFS (moduleName m1)
320 <= moduleNameFS (moduleName m2)
322 le_dep_mod :: (ModuleName, IsBootInterface)
323 -> (ModuleName, IsBootInterface) -> Bool
324 le_dep_mod (m1,_) (m2,_) = moduleNameFS m1 <= moduleNameFS m2
327 pkgs | th_used = insertList thPackageId (imp_dep_pkgs imports)
328 | otherwise = imp_dep_pkgs imports
330 return Deps { dep_mods = sortLe le_dep_mod dep_mods,
331 dep_pkgs = sortLe (<=) pkgs,
332 dep_orphs = sortLe le_mod (imp_orphs imports),
333 dep_finsts = sortLe le_mod (imp_finsts imports) }
334 -- sort to get into canonical order
337 mkIface_ :: HscEnv -> Maybe ModIface -> Module -> IsBootInterface
338 -> NameSet -> Dependencies -> GlobalRdrEnv
339 -> NameEnv FixItem -> Deprecations -> HpcInfo
340 -> ModuleEnv (Module, [(ModuleName, Bool, SrcSpan)])
342 -> IO (ModIface, Bool)
343 mkIface_ hsc_env maybe_old_iface
344 this_mod is_boot used_names deps rdr_env fix_env src_deprecs hpc_info
346 ModDetails{ md_insts = insts,
347 md_fam_insts = fam_insts,
349 md_vect_info = vect_info,
351 md_exports = exports }
352 -- NB: notice that mkIface does not look at the bindings
353 -- only at the TypeEnv. The previous Tidy phase has
354 -- put exactly the info into the TypeEnv that we want
355 -- to expose in the interface
357 = do {eps <- hscEPS hsc_env
359 ; usages <- mkUsageInfo hsc_env dir_imp_mods (dep_mods deps) used_names
361 ; let { entities = typeEnvElts type_env ;
362 decls = [ tyThingToIfaceDecl entity
363 | entity <- entities,
364 let name = getName entity,
365 not (isImplicitTyThing entity),
366 -- No implicit Ids and class tycons in the interface file
367 not (isWiredInName name),
368 -- Nor wired-in things; the compiler knows about them anyhow
369 nameIsLocalOrFrom this_mod name ]
370 -- Sigh: see Note [Root-main Id] in TcRnDriver
372 ; fixities = [(occ,fix) | FixItem occ fix <- nameEnvElts fix_env]
373 ; deprecs = src_deprecs
374 ; iface_rules = map (coreRuleToIfaceRule this_mod) rules
375 ; iface_insts = map instanceToIfaceInst insts
376 ; iface_fam_insts = map famInstToIfaceFamInst fam_insts
377 ; iface_vect_info = flattenVectInfo vect_info
379 ; intermediate_iface = ModIface {
380 mi_module = this_mod,
384 mi_exports = mkIfaceExports exports,
386 -- Sort these lexicographically, so that
387 -- the result is stable across compilations
388 mi_insts = sortLe le_inst iface_insts,
389 mi_fam_insts= sortLe le_fam_inst iface_fam_insts,
390 mi_rules = sortLe le_rule iface_rules,
392 mi_vect_info = iface_vect_info,
394 mi_fixities = fixities,
395 mi_deprecs = deprecs,
396 mi_globals = Just rdr_env,
398 -- Left out deliberately: filled in by addVersionInfo
399 mi_mod_vers = initialVersion,
400 mi_exp_vers = initialVersion,
401 mi_rule_vers = initialVersion,
402 mi_orphan = False, -- Always set by addVersionInfo, but
403 -- it's a strict field, so we can't omit it.
404 mi_finsts = False, -- Ditto
405 mi_decls = deliberatelyOmitted "decls",
406 mi_ver_fn = deliberatelyOmitted "ver_fn",
407 mi_hpc = isHpcUsed hpc_info,
409 -- And build the cached values
410 mi_dep_fn = mkIfaceDepCache deprecs,
411 mi_fix_fn = mkIfaceFixCache fixities }
413 -- Add version information
414 ; ext_ver_fn = mkParentVerFun hsc_env eps
415 ; (new_iface, no_change_at_all, pp_diffs, pp_orphs)
416 = {-# SCC "versioninfo" #-}
417 addVersionInfo ext_ver_fn maybe_old_iface
418 intermediate_iface decls
422 ; when (isJust pp_orphs && dopt Opt_WarnOrphans dflags)
423 (printDump (expectJust "mkIface" pp_orphs))
424 ; when (dopt Opt_D_dump_hi_diffs dflags) (printDump pp_diffs)
425 ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
426 (pprModIface new_iface)
428 -- bug #1617: on reload we weren't updating the PrintUnqualified
429 -- correctly. This stems from the fact that the interface had
430 -- not changed, so addVersionInfo returns the old ModIface
431 -- with the old GlobalRdrEnv (mi_globals).
432 ; let final_iface = new_iface{ mi_globals = Just rdr_env }
434 ; return (final_iface, no_change_at_all) }
436 r1 `le_rule` r2 = ifRuleName r1 <= ifRuleName r2
437 i1 `le_inst` i2 = ifDFun i1 `le_occ` ifDFun i2
438 i1 `le_fam_inst` i2 = ifFamInstTcName i1 `le_occ` ifFamInstTcName i2
440 le_occ :: Name -> Name -> Bool
441 -- Compare lexicographically by OccName, *not* by unique, because
442 -- the latter is not stable across compilations
443 le_occ n1 n2 = nameOccName n1 <= nameOccName n2
445 dflags = hsc_dflags hsc_env
446 deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
447 ifFamInstTcName = ifaceTyConName . ifFamInstTyCon
449 flattenVectInfo (VectInfo { vectInfoVar = vVar
450 , vectInfoTyCon = vTyCon
453 ifaceVectInfoVar = [ Var.varName v
454 | (v, _) <- varEnvElts vVar],
455 ifaceVectInfoTyCon = [ tyConName t
456 | (t, t_v) <- nameEnvElts vTyCon
458 ifaceVectInfoTyConReuse = [ tyConName t
459 | (t, t_v) <- nameEnvElts vTyCon
463 -----------------------------
464 writeIfaceFile :: DynFlags -> ModLocation -> ModIface -> IO ()
465 writeIfaceFile dflags location new_iface
466 = do createDirectoryHierarchy (takeDirectory hi_file_path)
467 writeBinIface dflags hi_file_path new_iface
468 where hi_file_path = ml_hi_file location
471 -- -----------------------------------------------------------------------------
472 -- Look up parents and versions of Names
474 -- This is like a global version of the mi_ver_fn field in each ModIface.
475 -- Given a Name, it finds the ModIface, and then uses mi_ver_fn to get
476 -- the parent and version info.
479 :: HscEnv -- needed to look up versions
480 -> ExternalPackageState -- ditto
481 -> (Name -> (OccName,Version))
482 mkParentVerFun hsc_env eps
485 mod = nameModule name
486 occ = nameOccName name
487 iface = lookupIfaceByModule (hsc_dflags hsc_env) hpt pit mod `orElse`
488 pprPanic "lookupVers2" (ppr mod <+> ppr occ)
490 mi_ver_fn iface occ `orElse`
491 pprPanic "lookupVers1" (ppr mod <+> ppr occ)
493 hpt = hsc_HPT hsc_env
496 -----------------------------------------------------------------------------
497 -- Compute version numbers for local decls
500 :: (Name -> (OccName,Version)) -- lookup parents and versions of names
501 -> Maybe ModIface -- The old interface, read from M.hi
502 -> ModIface -- The new interface (lacking decls)
503 -> [IfaceDecl] -- The new decls
504 -> (ModIface, -- Updated interface
505 Bool, -- True <=> no changes at all; no need to write Iface
507 Maybe SDoc) -- Warnings about orphans
509 addVersionInfo _ Nothing new_iface new_decls
510 -- No old interface, so definitely write a new one!
511 = (new_iface { mi_orphan = not (null orph_insts && null orph_rules)
512 , mi_finsts = not . null $ mi_fam_insts new_iface
513 , mi_decls = [(initialVersion, decl) | decl <- new_decls]
514 , mi_ver_fn = mkIfaceVerCache (zip (repeat initialVersion)
518 ptext (sLit "No old interface file"),
519 pprOrphans orph_insts orph_rules)
521 orph_insts = filter (isNothing . ifInstOrph) (mi_insts new_iface)
522 orph_rules = filter (isNothing . ifRuleOrph) (mi_rules new_iface)
524 addVersionInfo ver_fn (Just old_iface@(ModIface {
525 mi_mod_vers = old_mod_vers,
526 mi_exp_vers = old_exp_vers,
527 mi_rule_vers = old_rule_vers,
528 mi_decls = old_decls,
529 mi_ver_fn = old_decl_vers,
530 mi_fix_fn = old_fixities }))
531 new_iface@(ModIface { mi_fix_fn = new_fixities })
534 = (old_iface, True, ptext (sLit "Interface file unchanged"), pp_orphs)
536 = (final_iface, False, vcat [ptext (sLit "Interface file has changed"),
537 nest 2 pp_diffs], pp_orphs)
539 final_iface = new_iface {
540 mi_mod_vers = bump_unless no_output_change old_mod_vers,
541 mi_exp_vers = bump_unless no_export_change old_exp_vers,
542 mi_rule_vers = bump_unless no_rule_change old_rule_vers,
543 mi_orphan = not (null new_orph_rules && null new_orph_insts),
544 mi_finsts = not . null $ mi_fam_insts new_iface,
545 mi_decls = decls_w_vers,
546 mi_ver_fn = mkIfaceVerCache decls_w_vers }
548 decls_w_vers = [(add_vers decl, decl) | decl <- new_decls]
551 (old_non_orph_insts, old_orph_insts) =
552 mkOrphMap ifInstOrph (mi_insts old_iface)
553 (new_non_orph_insts, new_orph_insts) =
554 mkOrphMap ifInstOrph (mi_insts new_iface)
555 old_fam_insts = mi_fam_insts old_iface
556 new_fam_insts = mi_fam_insts new_iface
557 same_insts occ = eqMaybeBy (eqListBy eqIfInst)
558 (lookupOccEnv old_non_orph_insts occ)
559 (lookupOccEnv new_non_orph_insts occ)
561 (old_non_orph_rules, old_orph_rules) =
562 mkOrphMap ifRuleOrph (mi_rules old_iface)
563 (new_non_orph_rules, new_orph_rules) =
564 mkOrphMap ifRuleOrph (mi_rules new_iface)
565 same_rules occ = eqMaybeBy (eqListBy eqIfRule)
566 (lookupOccEnv old_non_orph_rules occ)
567 (lookupOccEnv new_non_orph_rules occ)
569 -- Computing what changed
570 no_output_change = no_decl_change && no_rule_change &&
571 no_export_change && no_deprec_change
572 no_export_change = mi_exports new_iface == mi_exports old_iface
574 no_decl_change = isEmptyOccSet changed_occs
575 no_rule_change = not (changedWrtNames changed_occs (eqListBy eqIfRule old_orph_rules new_orph_rules)
576 || changedWrtNames changed_occs (eqListBy eqIfInst old_orph_insts new_orph_insts)
577 || changedWrtNames changed_occs (eqListBy eqIfFamInst old_fam_insts new_fam_insts))
578 no_deprec_change = mi_deprecs new_iface == mi_deprecs old_iface
580 -- If the usages havn't changed either, we don't need to write the interface file
581 no_other_changes = mi_usages new_iface == mi_usages old_iface &&
582 mi_deps new_iface == mi_deps old_iface &&
583 mi_hpc new_iface == mi_hpc old_iface
584 no_change_at_all = no_output_change && no_other_changes
586 pp_diffs = vcat [pp_change no_export_change "Export list"
587 (ppr old_exp_vers <+> arrow <+> ppr (mi_exp_vers final_iface)),
588 pp_change no_rule_change "Rules"
589 (ppr old_rule_vers <+> arrow <+> ppr (mi_rule_vers final_iface)),
590 pp_change no_deprec_change "Deprecations" empty,
591 pp_change no_other_changes "Usages" empty,
593 pp_change True _ _ = empty
594 pp_change False what info = text what <+> ptext (sLit "changed") <+> info
597 old_decl_env = mkOccEnv [(ifName decl, decl) | (_,decl) <- old_decls]
598 same_fixity n = bool (old_fixities n == new_fixities n)
601 -- Adding version info
602 new_version = bumpVersion old_mod_vers
603 -- Start from the old module version, not from
604 -- zero so that if you remove f, and then add
605 -- it again, you don't thereby reduce f's
608 add_vers decl | occ `elemOccSet` changed_occs = new_version
609 | otherwise = snd (expectJust "add_vers" (old_decl_vers occ))
610 -- If it's unchanged, there jolly well
611 where -- should be an old version number
615 -- Deciding which declarations have changed
617 -- For each local decl, the IfaceEq gives the list of things that
618 -- must be unchanged for the declaration as a whole to be unchanged.
619 eq_info :: [(OccName, IfaceEq)]
620 eq_info = map check_eq new_decls
622 | Just old_decl <- lookupOccEnv old_decl_env occ
623 = (occ, new_decl `eqIfDecl` old_decl &&& eq_indirects new_decl)
624 | otherwise {- No corresponding old decl -}
627 occ = ifName new_decl
629 eq_indirects :: IfaceDecl -> IfaceEq
630 -- When seeing if two decls are the same, remember to
631 -- check whether any relevant fixity or rules have changed
632 eq_indirects (IfaceId {ifName = occ}) = eq_ind_occ occ
633 eq_indirects (IfaceClass {ifName = cls_occ, ifSigs = sigs})
634 = same_insts cls_occ &&&
635 eq_ind_occs [op | IfaceClassOp op _ _ <- sigs]
636 eq_indirects (IfaceData {ifName = tc_occ, ifCons = cons})
637 = same_insts tc_occ &&& same_fixity tc_occ &&& -- The TyCon can have a fixity too
638 eq_ind_occs (map ifConOcc (visibleIfConDecls cons))
639 eq_indirects _ = Equal -- Synonyms and foreign declarations
641 eq_ind_occ :: OccName -> IfaceEq -- For class ops and Ids; check fixity and rules
642 eq_ind_occ occ = same_fixity occ &&& same_rules occ
643 eq_ind_occs = foldr ((&&&) . eq_ind_occ) Equal
645 -- The Occs of declarations that changed.
646 changed_occs :: OccSet
647 changed_occs = computeChangedOccs ver_fn (mi_module new_iface)
648 (mi_usages old_iface) eq_info
652 pp_decl_diffs :: SDoc -- Nothing => no changes
654 | isEmptyOccSet changed_occs = empty
656 = vcat [ptext (sLit "Changed occs:") <+> ppr (occSetElts changed_occs),
657 ptext (sLit "Version change for these decls:"),
658 nest 2 (vcat (map show_change new_decls))]
660 eq_env = mkOccEnv eq_info
662 | not (occ `elemOccSet` changed_occs) = empty
664 = vcat [ppr occ <+> ppr (old_decl_vers occ) <+> arrow <+> ppr new_version,
667 occ = ifName new_decl
668 why = case lookupOccEnv eq_env occ of
669 Just (EqBut names) -> sep [ppr occ <> colon, ptext (sLit "Free vars (only) changed:") <> ppr names,
670 nest 2 (braces (fsep (map ppr (occSetElts
671 (occs `intersectOccSet` changed_occs)))))]
672 where occs = mkOccSet (map nameOccName (nameSetToList names))
674 | Just old_decl <- lookupOccEnv old_decl_env occ
675 -> vcat [ptext (sLit "Old:") <+> ppr old_decl,
676 ptext (sLit "New:") <+> ppr new_decl]
678 -> ppr occ <+> ptext (sLit "only in new interface")
679 _ -> pprPanic "MkIface.show_change" (ppr occ)
681 pp_orphs = pprOrphans new_orph_insts new_orph_rules
684 pprOrphans :: [IfaceInst] -> [IfaceRule] -> Maybe SDoc
685 pprOrphans insts rules
686 | null insts && null rules = Nothing
689 if null insts then empty else
690 hang (ptext (sLit "Warning: orphan instances:"))
691 2 (vcat (map ppr insts)),
692 if null rules then empty else
693 hang (ptext (sLit "Warning: orphan rules:"))
694 2 (vcat (map ppr rules))
698 :: (Name -> (OccName,Version)) -- get parents and versions
699 -> Module -- This module
700 -> [Usage] -- Usages from old iface
701 -> [(OccName, IfaceEq)] -- decl names, equality conditions
702 -> OccSet -- set of things that have changed
703 computeChangedOccs ver_fn this_module old_usages eq_info
704 = foldl add_changes emptyOccSet (stronglyConnComp edges)
707 -- return True if an external name has changed
708 name_changed :: Name -> Bool
710 | isWiredInName nm -- Wired-in things don't get into interface
711 = False -- files and hence don't get into the ver_fn
712 | Just ents <- lookupUFM usg_modmap (moduleName mod),
713 Just v <- lookupUFM ents parent_occ
715 | modulePackageId mod == this_pkg
716 = WARN(True, ptext (sLit "computeChangedOccs") <+> ppr nm) True
717 -- should really be a panic, see #1959. The problem is that the usages doesn't
718 -- contain all the names that might be referred to by unfoldings. So as a
719 -- conservative workaround we just assume these names have changed.
720 | otherwise = False -- must be in another package
723 (parent_occ, new_version) = ver_fn nm
725 this_pkg = modulePackageId this_module
727 -- Turn the usages from the old ModIface into a mapping
728 usg_modmap = listToUFM [ (usg_name usg, listToUFM (usg_entities usg))
729 | usg <- old_usages ]
731 get_local_eq_info :: GenIfaceEq Name -> GenIfaceEq OccName
732 get_local_eq_info Equal = Equal
733 get_local_eq_info NotEqual = NotEqual
734 get_local_eq_info (EqBut ns) = foldNameSet f Equal ns
735 where f name eq | nameModule name == this_module =
736 EqBut (unitOccSet (nameOccName name)) `and_occifeq` eq
737 | name_changed name = NotEqual
740 local_eq_infos = mapSnd get_local_eq_info eq_info
742 edges :: [((OccName, OccIfaceEq), Unique, [Unique])]
743 edges = [ (node, getUnique occ, map getUnique occs)
744 | node@(occ, iface_eq) <- local_eq_infos
745 , let occs = case iface_eq of
746 EqBut occ_set -> occSetElts occ_set
749 -- Changes in declarations
750 add_changes :: OccSet -> SCC (OccName, OccIfaceEq) -> OccSet
751 add_changes so_far (AcyclicSCC (occ, iface_eq))
752 | changedWrt so_far iface_eq -- This one has changed
753 = extendOccSet so_far occ
754 add_changes so_far (CyclicSCC pairs)
755 | changedWrt so_far (foldr1 and_occifeq iface_eqs)
756 -- One of this group has changed
757 = extendOccSetList so_far occs
758 where (occs, iface_eqs) = unzip pairs
759 add_changes so_far _ = so_far
761 type OccIfaceEq = GenIfaceEq OccName
763 changedWrt :: OccSet -> OccIfaceEq -> Bool
764 changedWrt _ Equal = False
765 changedWrt _ NotEqual = True
766 changedWrt so_far (EqBut kids) = so_far `intersectsOccSet` kids
768 changedWrtNames :: OccSet -> IfaceEq -> Bool
769 changedWrtNames _ Equal = False
770 changedWrtNames _ NotEqual = True
771 changedWrtNames so_far (EqBut kids) =
772 so_far `intersectsOccSet` mkOccSet (map nameOccName (nameSetToList kids))
774 and_occifeq :: OccIfaceEq -> OccIfaceEq -> OccIfaceEq
775 Equal `and_occifeq` x = x
776 NotEqual `and_occifeq` _ = NotEqual
777 EqBut nms `and_occifeq` Equal = EqBut nms
778 EqBut _ `and_occifeq` NotEqual = NotEqual
779 EqBut nms1 `and_occifeq` EqBut nms2 = EqBut (nms1 `unionOccSets` nms2)
781 ----------------------
782 -- mkOrphMap partitions instance decls or rules into
783 -- (a) an OccEnv for ones that are not orphans,
784 -- mapping the local OccName to a list of its decls
785 -- (b) a list of orphan decls
786 mkOrphMap :: (decl -> Maybe OccName) -- (Just occ) for a non-orphan decl, keyed by occ
787 -- Nothing for an orphan decl
788 -> [decl] -- Sorted into canonical order
789 -> (OccEnv [decl], -- Non-orphan decls associated with their key;
790 -- each sublist in canonical order
791 [decl]) -- Orphan decls; in canonical order
792 mkOrphMap get_key decls
793 = foldl go (emptyOccEnv, []) decls
795 go (non_orphs, orphs) d
796 | Just occ <- get_key d
797 = (extendOccEnv_C (\ ds _ -> d:ds) non_orphs occ [d], orphs)
798 | otherwise = (non_orphs, d:orphs)
800 ----------------------
801 bump_unless :: Bool -> Version -> Version
802 bump_unless True v = v -- True <=> no change
803 bump_unless False v = bumpVersion v
807 %*********************************************************
809 \subsection{Keeping track of what we've slurped, and version numbers}
811 %*********************************************************
815 mkUsageInfo :: HscEnv
816 -> ModuleEnv (Module, [(ModuleName, Bool, SrcSpan)])
817 -> [(ModuleName, IsBootInterface)]
818 -> NameSet -> IO [Usage]
819 mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
820 = do { eps <- hscEPS hsc_env
821 ; let usages = mk_usage_info (eps_PIT eps) hsc_env
822 dir_imp_mods dep_mods used_names
823 ; usages `seqList` return usages }
824 -- seq the list of Usages returned: occasionally these
825 -- don't get evaluated for a while and we can end up hanging on to
826 -- the entire collection of Ifaces.
828 mk_usage_info :: PackageIfaceTable
830 -> ModuleEnv (Module, [(ModuleName, Bool, SrcSpan)])
831 -> [(ModuleName, IsBootInterface)]
834 mk_usage_info pit hsc_env dir_imp_mods dep_mods used_names
835 = mapCatMaybes mkUsage dep_mods
836 -- ToDo: do we need to sort into canonical order?
838 hpt = hsc_HPT hsc_env
839 dflags = hsc_dflags hsc_env
841 -- ent_map groups together all the things imported and used
842 -- from a particular module in this package
843 ent_map :: ModuleEnv [OccName]
844 ent_map = foldNameSet add_mv emptyModuleEnv used_names
846 | isWiredInName name = mv_map -- ignore wired-in names
848 = case nameModule_maybe name of
849 Nothing -> mv_map -- ignore internal names
850 Just mod -> extendModuleEnv_C add_item mv_map mod [occ]
852 occ = nameOccName name
853 add_item occs _ = occ:occs
855 depend_on_exports mod = case lookupModuleEnv dir_imp_mods mod of
856 Just (_, xs) -> any (\(_, no_imp, _) -> not no_imp) xs
859 -- We want to create a Usage for a home module if
860 -- a) we used something from; has something in used_names
861 -- b) we imported all of it, even if we used nothing from it
862 -- (need to recompile if its export list changes: export_vers)
863 -- c) is a home-package orphan or family-instance module (need to
864 -- recompile if its instance decls change: rules_vers)
865 mkUsage :: (ModuleName, IsBootInterface) -> Maybe Usage
866 mkUsage (mod_name, _)
867 | isNothing maybe_iface -- We can't depend on it if we didn't
868 || (null used_occs -- load its interface.
869 && isNothing export_vers
872 = Nothing -- Record no usage info
875 = Just (Usage { usg_name = mod_name,
877 usg_exports = export_vers,
878 usg_entities = fmToList ent_vers,
879 usg_rules = rules_vers })
881 maybe_iface = lookupIfaceByModule dflags hpt pit mod
882 -- In one-shot mode, the interfaces for home-package
883 -- modules accumulate in the PIT not HPT. Sigh.
885 mod = mkModule (thisPackage dflags) mod_name
887 Just iface = maybe_iface
888 orphan_mod = mi_orphan iface
889 finsts_mod = mi_finsts iface
890 version_env = mi_ver_fn iface
891 mod_vers = mi_mod_vers iface
892 rules_vers = mi_rule_vers iface
893 export_vers | depend_on_exports mod = Just (mi_exp_vers iface)
894 | otherwise = Nothing
896 used_occs = lookupModuleEnv ent_map mod `orElse` []
898 -- Making a FiniteMap here ensures that (a) we remove duplicates
899 -- when we have usages on several subordinates of a single parent,
900 -- and (b) that the usages emerge in a canonical order, which
901 -- is why we use FiniteMap rather than OccEnv: FiniteMap works
902 -- using Ord on the OccNames, which is a lexicographic ordering.
903 ent_vers :: FiniteMap OccName Version
904 ent_vers = listToFM (map lookup_occ used_occs)
907 case version_env occ of
908 Nothing -> pprTrace "hmm, strange" (ppr mod <+> ppr occ) $
909 (occ, initialVersion) -- does this ever happen?
910 Just (parent, version) -> (parent, version)
914 mkIfaceExports :: [AvailInfo]
915 -> [(Module, [GenAvailInfo OccName])]
916 -- Group by module and sort by occurrence
917 -- This keeps the list in canonical order
918 mkIfaceExports exports
919 = [ (mod, eltsFM avails)
920 | (mod, avails) <- fmToList groupFM
923 -- Group by the module where the exported entities are defined
924 -- (which may not be the same for all Names in an Avail)
925 -- Deliberately use FiniteMap rather than UniqFM so we
926 -- get a canonical ordering
927 groupFM :: ModuleEnv (FiniteMap FastString (GenAvailInfo OccName))
928 groupFM = foldl add emptyModuleEnv exports
930 add_one :: ModuleEnv (FiniteMap FastString (GenAvailInfo OccName))
931 -> Module -> GenAvailInfo OccName
932 -> ModuleEnv (FiniteMap FastString (GenAvailInfo OccName))
933 add_one env mod avail
934 = extendModuleEnv_C plusFM env mod
935 (unitFM (occNameFS (availName avail)) avail)
937 -- NB: we should not get T(X) and T(Y) in the export list
938 -- else the plusFM will simply discard one! They
939 -- should have been combined by now.
941 = add_one env (nameModule n) (Avail (nameOccName n))
943 add env (AvailTC tc ns)
944 = foldl add_for_mod env mods
946 tc_occ = nameOccName tc
947 mods = nub (map nameModule ns)
948 -- Usually just one, but see Note [Original module]
951 = add_one env mod (AvailTC tc_occ (sort names_from_mod))
952 -- NB. sort the children, we need a canonical order
954 names_from_mod = [nameOccName n | n <- ns, nameModule n == mod]
957 Note [Orignal module]
958 ~~~~~~~~~~~~~~~~~~~~~
960 module X where { data family T }
961 module Y( T(..) ) where { import X; data instance T Int = MkT Int }
962 The exported Avail from Y will look like
965 - only MkT is brought into scope by the data instance;
966 - but the parent (used for grouping and naming in T(..) exports) is X.T
967 - and in this case we export X.T too
969 In the result of MkIfaceExports, the names are grouped by defining module,
970 so we may need to split up a single Avail into multiple ones.
973 %************************************************************************
975 Load the old interface file for this module (unless
976 we have it aleady), and check whether it is up to date
979 %************************************************************************
982 checkOldIface :: HscEnv
984 -> Bool -- Source unchanged
985 -> Maybe ModIface -- Old interface from compilation manager, if any
986 -> IO (RecompileRequired, Maybe ModIface)
988 checkOldIface hsc_env mod_summary source_unchanged maybe_iface
989 = do { showPass (hsc_dflags hsc_env)
990 ("Checking old interface for " ++
991 showSDoc (ppr (ms_mod mod_summary))) ;
993 ; initIfaceCheck hsc_env $
994 check_old_iface hsc_env mod_summary source_unchanged maybe_iface
997 check_old_iface :: HscEnv -> ModSummary -> Bool -> Maybe ModIface
998 -> IfG (Bool, Maybe ModIface)
999 check_old_iface hsc_env mod_summary source_unchanged maybe_iface
1000 = do -- CHECK WHETHER THE SOURCE HAS CHANGED
1001 { when (not source_unchanged)
1002 (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
1004 -- If the source has changed and we're in interactive mode, avoid reading
1005 -- an interface; just return the one we might have been supplied with.
1006 ; let dflags = hsc_dflags hsc_env
1007 ; if not (isObjectTarget (hscTarget dflags)) && not source_unchanged then
1008 return (outOfDate, maybe_iface)
1010 case maybe_iface of {
1011 Just old_iface -> do -- Use the one we already have
1012 { traceIf (text "We already have the old interface for" <+> ppr (ms_mod mod_summary))
1013 ; recomp <- checkVersions hsc_env source_unchanged mod_summary old_iface
1014 ; return (recomp, Just old_iface) }
1018 -- Try and read the old interface for the current module
1019 -- from the .hi file left from the last time we compiled it
1020 { let iface_path = msHiFilePath mod_summary
1021 ; read_result <- readIface (ms_mod mod_summary) iface_path False
1022 ; case read_result of {
1023 Failed err -> do -- Old interface file not found, or garbled; give up
1024 { traceIf (text "FYI: cannot read old interface file:"
1026 ; return (outOfDate, Nothing) }
1028 ; Succeeded iface -> do
1030 -- We have got the old iface; check its versions
1031 { traceIf (text "Read the interface file" <+> text iface_path)
1032 ; recomp <- checkVersions hsc_env source_unchanged mod_summary iface
1033 ; return (recomp, Just iface)
1038 @recompileRequired@ is called from the HscMain. It checks whether
1039 a recompilation is required. It needs access to the persistent state,
1040 finder, etc, because it may have to load lots of interface files to
1041 check their versions.
1044 type RecompileRequired = Bool
1045 upToDate, outOfDate :: Bool
1046 upToDate = False -- Recompile not required
1047 outOfDate = True -- Recompile required
1049 checkVersions :: HscEnv
1050 -> Bool -- True <=> source unchanged
1052 -> ModIface -- Old interface
1053 -> IfG RecompileRequired
1054 checkVersions hsc_env source_unchanged mod_summary iface
1055 | not source_unchanged
1058 = do { traceHiDiffs (text "Considering whether compilation is required for" <+>
1059 ppr (mi_module iface) <> colon)
1061 ; recomp <- checkDependencies hsc_env mod_summary iface
1062 ; if recomp then return outOfDate else do {
1064 -- Source code unchanged and no errors yet... carry on
1066 -- First put the dependent-module info, read from the old interface, into the envt,
1067 -- so that when we look for interfaces we look for the right one (.hi or .hi-boot)
1069 -- It's just temporary because either the usage check will succeed
1070 -- (in which case we are done with this module) or it'll fail (in which
1071 -- case we'll compile the module from scratch anyhow).
1073 -- We do this regardless of compilation mode, although in --make mode
1074 -- all the dependent modules should be in the HPT already, so it's
1076 updateEps_ $ \eps -> eps { eps_is_boot = mod_deps }
1078 ; let this_pkg = thisPackage (hsc_dflags hsc_env)
1079 ; checkList [checkModUsage this_pkg u | u <- mi_usages iface]
1082 -- This is a bit of a hack really
1083 mod_deps :: ModuleNameEnv (ModuleName, IsBootInterface)
1084 mod_deps = mkModDeps (dep_mods (mi_deps iface))
1087 -- If the direct imports of this module are resolved to targets that
1088 -- are not among the dependencies of the previous interface file,
1089 -- then we definitely need to recompile. This catches cases like
1090 -- - an exposed package has been upgraded
1091 -- - we are compiling with different package flags
1092 -- - a home module that was shadowing a package module has been removed
1093 -- - a new home module has been added that shadows a package module
1096 -- Returns True if recompilation is required.
1097 checkDependencies :: HscEnv -> ModSummary -> ModIface -> IfG RecompileRequired
1098 checkDependencies hsc_env summary iface
1099 = orM (map dep_missing (ms_imps summary ++ ms_srcimps summary))
1101 prev_dep_mods = dep_mods (mi_deps iface)
1102 prev_dep_pkgs = dep_pkgs (mi_deps iface)
1104 this_pkg = thisPackage (hsc_dflags hsc_env)
1106 orM = foldr f (return False)
1107 where f m rest = do b <- m; if b then return True else rest
1109 dep_missing (L _ mod) = do
1110 find_res <- liftIO $ findImportedModule hsc_env mod Nothing
1114 -> if moduleName mod `notElem` map fst prev_dep_mods
1115 then do traceHiDiffs $
1116 text "imported module " <> quotes (ppr mod) <>
1117 text " not among previous dependencies"
1122 -> if pkg `notElem` prev_dep_pkgs
1123 then do traceHiDiffs $
1124 text "imported module " <> quotes (ppr mod) <>
1125 text " is from package " <> quotes (ppr pkg) <>
1126 text ", which is not among previous dependencies"
1130 where pkg = modulePackageId mod
1131 _otherwise -> return outOfDate
1133 checkModUsage :: PackageId ->Usage -> IfG RecompileRequired
1134 -- Given the usage information extracted from the old
1135 -- M.hi file for the module being compiled, figure out
1136 -- whether M needs to be recompiled.
1138 checkModUsage this_pkg (Usage { usg_name = mod_name, usg_mod = old_mod_vers,
1139 usg_rules = old_rule_vers,
1140 usg_exports = maybe_old_export_vers,
1141 usg_entities = old_decl_vers })
1142 = do -- Load the imported interface is possible
1143 let doc_str = sep [ptext (sLit "need version info for"), ppr mod_name]
1144 traceHiDiffs (text "Checking usages for module" <+> ppr mod_name)
1146 let mod = mkModule this_pkg mod_name
1148 mb_iface <- loadInterface doc_str mod ImportBySystem
1149 -- Load the interface, but don't complain on failure;
1150 -- Instead, get an Either back which we can test
1153 Failed _ -> (out_of_date (sep [ptext (sLit "Can't find version number for module"),
1155 -- Couldn't find or parse a module mentioned in the
1156 -- old interface file. Don't complain -- it might just be that
1157 -- the current module doesn't need that import and it's been deleted
1161 new_mod_vers = mi_mod_vers iface
1162 new_decl_vers = mi_ver_fn iface
1163 new_export_vers = mi_exp_vers iface
1164 new_rule_vers = mi_rule_vers iface
1167 checkModuleVersion old_mod_vers new_mod_vers >>= \ recompile ->
1168 if not recompile then
1172 -- CHECK EXPORT LIST
1173 if checkExportList maybe_old_export_vers new_export_vers then
1174 out_of_date_vers (ptext (sLit " Export list changed"))
1175 (expectJust "checkModUsage" maybe_old_export_vers)
1180 if old_rule_vers /= new_rule_vers then
1181 out_of_date_vers (ptext (sLit " Rules changed"))
1182 old_rule_vers new_rule_vers
1185 -- CHECK ITEMS ONE BY ONE
1186 checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers] >>= \ recompile ->
1188 return outOfDate -- This one failed, so just bail out now
1190 up_to_date (ptext (sLit " Great! The bits I use are up to date"))
1193 ------------------------
1194 checkModuleVersion :: Version -> Version -> IfG Bool
1195 checkModuleVersion old_mod_vers new_mod_vers
1196 | new_mod_vers == old_mod_vers
1197 = up_to_date (ptext (sLit "Module version unchanged"))
1200 = out_of_date_vers (ptext (sLit " Module version has changed"))
1201 old_mod_vers new_mod_vers
1203 ------------------------
1204 checkExportList :: Maybe Version -> Version -> Bool
1205 checkExportList Nothing _ = upToDate
1206 checkExportList (Just v) new_vers = v /= new_vers
1208 ------------------------
1209 checkEntityUsage :: (OccName -> Maybe (OccName, Version))
1210 -> (OccName, Version)
1212 checkEntityUsage new_vers (name,old_vers)
1213 = case new_vers name of
1215 Nothing -> -- We used it before, but it ain't there now
1216 out_of_date (sep [ptext (sLit "No longer exported:"), ppr name])
1218 Just (_, new_vers) -- It's there, but is it up to date?
1219 | new_vers == old_vers -> do traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_vers))
1221 | otherwise -> out_of_date_vers (ptext (sLit " Out of date:") <+> ppr name)
1224 up_to_date, out_of_date :: SDoc -> IfG Bool
1225 up_to_date msg = traceHiDiffs msg >> return upToDate
1226 out_of_date msg = traceHiDiffs msg >> return outOfDate
1228 out_of_date_vers :: SDoc -> Version -> Version -> IfG Bool
1229 out_of_date_vers msg old_vers new_vers
1230 = out_of_date (hsep [msg, ppr old_vers, ptext (sLit "->"), ppr new_vers])
1232 ----------------------
1233 checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
1234 -- This helper is used in two places
1235 checkList [] = return upToDate
1236 checkList (check:checks) = do recompile <- check
1238 then return outOfDate
1239 else checkList checks
1242 %************************************************************************
1244 Converting things to their Iface equivalents
1246 %************************************************************************
1249 tyThingToIfaceDecl :: TyThing -> IfaceDecl
1250 -- Assumption: the thing is already tidied, so that locally-bound names
1251 -- (lambdas, for-alls) already have non-clashing OccNames
1252 -- Reason: Iface stuff uses OccNames, and the conversion here does
1253 -- not do tidying on the way
1254 tyThingToIfaceDecl (AnId id)
1255 = IfaceId { ifName = getOccName id,
1256 ifType = toIfaceType (idType id),
1259 info = case toIfaceIdInfo (idInfo id) of
1261 items -> HasInfo items
1263 tyThingToIfaceDecl (AClass clas)
1264 = IfaceClass { ifCtxt = toIfaceContext sc_theta,
1265 ifName = getOccName clas,
1266 ifTyVars = toIfaceTvBndrs clas_tyvars,
1267 ifFDs = map toIfaceFD clas_fds,
1268 ifATs = map (tyThingToIfaceDecl . ATyCon) clas_ats,
1269 ifSigs = map toIfaceClassOp op_stuff,
1270 ifRec = boolToRecFlag (isRecursiveTyCon tycon) }
1272 (clas_tyvars, clas_fds, sc_theta, _, clas_ats, op_stuff)
1273 = classExtraBigSig clas
1274 tycon = classTyCon clas
1276 toIfaceClassOp (sel_id, def_meth)
1277 = ASSERT(sel_tyvars == clas_tyvars)
1278 IfaceClassOp (getOccName sel_id) def_meth (toIfaceType op_ty)
1280 -- Be careful when splitting the type, because of things
1281 -- like class Foo a where
1282 -- op :: (?x :: String) => a -> a
1283 -- and class Baz a where
1284 -- op :: (Ord a) => a -> a
1285 (sel_tyvars, rho_ty) = splitForAllTys (idType sel_id)
1286 op_ty = funResultTy rho_ty
1288 toIfaceFD (tvs1, tvs2) = (map getFS tvs1, map getFS tvs2)
1290 tyThingToIfaceDecl (ATyCon tycon)
1292 = IfaceSyn { ifName = getOccName tycon,
1293 ifTyVars = toIfaceTvBndrs tyvars,
1294 ifOpenSyn = syn_isOpen,
1295 ifSynRhs = toIfaceType syn_tyki,
1296 ifFamInst = famInstToIface (tyConFamInst_maybe tycon)
1300 = IfaceData { ifName = getOccName tycon,
1301 ifTyVars = toIfaceTvBndrs tyvars,
1302 ifCtxt = toIfaceContext (tyConStupidTheta tycon),
1303 ifCons = ifaceConDecls (algTyConRhs tycon),
1304 ifRec = boolToRecFlag (isRecursiveTyCon tycon),
1305 ifGadtSyntax = isGadtSyntaxTyCon tycon,
1306 ifGeneric = tyConHasGenerics tycon,
1307 ifFamInst = famInstToIface (tyConFamInst_maybe tycon)}
1309 | isForeignTyCon tycon
1310 = IfaceForeign { ifName = getOccName tycon,
1311 ifExtName = tyConExtName tycon }
1313 | otherwise = pprPanic "toIfaceDecl" (ppr tycon)
1315 tyvars = tyConTyVars tycon
1316 (syn_isOpen, syn_tyki) = case synTyConRhs tycon of
1317 OpenSynTyCon ki _ -> (True , ki)
1318 SynonymTyCon ty -> (False, ty)
1320 ifaceConDecls (NewTyCon { data_con = con }) =
1321 IfNewTyCon (ifaceConDecl con)
1322 ifaceConDecls (DataTyCon { data_cons = cons }) =
1323 IfDataTyCon (map ifaceConDecl cons)
1324 ifaceConDecls OpenTyCon {} = IfOpenDataTyCon
1325 ifaceConDecls AbstractTyCon = IfAbstractTyCon
1326 -- The last case happens when a TyCon has been trimmed during tidying
1327 -- Furthermore, tyThingToIfaceDecl is also used
1328 -- in TcRnDriver for GHCi, when browsing a module, in which case the
1329 -- AbstractTyCon case is perfectly sensible.
1331 ifaceConDecl data_con
1332 = IfCon { ifConOcc = getOccName (dataConName data_con),
1333 ifConInfix = dataConIsInfix data_con,
1334 ifConUnivTvs = toIfaceTvBndrs (dataConUnivTyVars data_con),
1335 ifConExTvs = toIfaceTvBndrs (dataConExTyVars data_con),
1336 ifConEqSpec = to_eq_spec (dataConEqSpec data_con),
1337 ifConCtxt = toIfaceContext (dataConEqTheta data_con ++ dataConDictTheta data_con),
1338 ifConArgTys = map toIfaceType (dataConOrigArgTys data_con),
1339 ifConFields = map getOccName
1340 (dataConFieldLabels data_con),
1341 ifConStricts = dataConStrictMarks data_con }
1343 to_eq_spec spec = [(getOccName tv, toIfaceType ty) | (tv,ty) <- spec]
1345 famInstToIface Nothing = Nothing
1346 famInstToIface (Just (famTyCon, instTys)) =
1347 Just (toIfaceTyCon famTyCon, map toIfaceType instTys)
1349 tyThingToIfaceDecl (ADataCon dc)
1350 = pprPanic "toIfaceDecl" (ppr dc) -- Should be trimmed out earlier
1353 getFS :: NamedThing a => a -> FastString
1354 getFS x = occNameFS (getOccName x)
1356 --------------------------
1357 instanceToIfaceInst :: Instance -> IfaceInst
1358 instanceToIfaceInst (Instance { is_dfun = dfun_id, is_flag = oflag,
1359 is_cls = cls_name, is_tcs = mb_tcs })
1360 = ASSERT( cls_name == className cls )
1361 IfaceInst { ifDFun = dfun_name,
1363 ifInstCls = cls_name,
1364 ifInstTys = map do_rough mb_tcs,
1367 do_rough Nothing = Nothing
1368 do_rough (Just n) = Just (toIfaceTyCon_name n)
1370 dfun_name = idName dfun_id
1371 mod = nameModule dfun_name
1372 is_local name = nameIsLocalOrFrom mod name
1374 -- Compute orphanhood. See Note [Orphans] in IfaceSyn
1375 (_, _, cls, tys) = tcSplitDFunTy (idType dfun_id)
1376 -- Slightly awkward: we need the Class to get the fundeps
1377 (tvs, fds) = classTvsFds cls
1378 arg_names = [filterNameSet is_local (tyClsNamesOfType ty) | ty <- tys]
1379 orph | is_local cls_name = Just (nameOccName cls_name)
1380 | all isJust mb_ns = head mb_ns
1381 | otherwise = Nothing
1383 mb_ns :: [Maybe OccName] -- One for each fundep; a locally-defined name
1384 -- that is not in the "determined" arguments
1385 mb_ns | null fds = [choose_one arg_names]
1386 | otherwise = map do_one fds
1387 do_one (_ltvs, rtvs) = choose_one [ns | (tv,ns) <- tvs `zip` arg_names
1388 , not (tv `elem` rtvs)]
1390 choose_one :: [NameSet] -> Maybe OccName
1391 choose_one nss = case nameSetToList (unionManyNameSets nss) of
1393 (n : _) -> Just (nameOccName n)
1395 --------------------------
1396 famInstToIfaceFamInst :: FamInst -> IfaceFamInst
1397 famInstToIfaceFamInst (FamInst { fi_tycon = tycon,
1400 = IfaceFamInst { ifFamInstTyCon = toIfaceTyCon tycon
1401 , ifFamInstFam = fam
1402 , ifFamInstTys = map do_rough mb_tcs }
1404 do_rough Nothing = Nothing
1405 do_rough (Just n) = Just (toIfaceTyCon_name n)
1407 --------------------------
1408 toIfaceLetBndr :: Id -> IfaceLetBndr
1409 toIfaceLetBndr id = IfLetBndr (occNameFS (getOccName id))
1410 (toIfaceType (idType id))
1413 -- Stripped-down version of tcIfaceIdInfo
1414 -- Change this if you want to export more IdInfo for
1415 -- non-top-level Ids. Don't forget to change
1416 -- CoreTidy.tidyLetBndr too!
1418 -- See Note [IdInfo on nested let-bindings] in IfaceSyn
1420 inline_prag = inlinePragInfo id_info
1421 prag_info | isAlwaysActive inline_prag = NoInfo
1422 | otherwise = HasInfo [HsInline inline_prag]
1424 --------------------------
1425 toIfaceIdInfo :: IdInfo -> [IfaceInfoItem]
1426 toIfaceIdInfo id_info
1427 = catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo,
1428 inline_hsinfo, wrkr_hsinfo, unfold_hsinfo]
1430 ------------ Arity --------------
1431 arity_info = arityInfo id_info
1432 arity_hsinfo | arity_info == 0 = Nothing
1433 | otherwise = Just (HsArity arity_info)
1435 ------------ Caf Info --------------
1436 caf_info = cafInfo id_info
1437 caf_hsinfo = case caf_info of
1438 NoCafRefs -> Just HsNoCafRefs
1441 ------------ Strictness --------------
1442 -- No point in explicitly exporting TopSig
1443 strict_hsinfo = case newStrictnessInfo id_info of
1444 Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
1447 ------------ Worker --------------
1448 work_info = workerInfo id_info
1449 has_worker = workerExists work_info
1450 wrkr_hsinfo = case work_info of
1451 HasWorker work_id wrap_arity ->
1452 Just (HsWorker ((idName work_id)) wrap_arity)
1455 ------------ Unfolding --------------
1456 -- The unfolding is redundant if there is a worker
1457 unfold_info = unfoldingInfo id_info
1458 rhs = unfoldingTemplate unfold_info
1459 no_unfolding = neverUnfold unfold_info
1460 -- The CoreTidy phase retains unfolding info iff
1461 -- we want to expose the unfolding, taking into account
1462 -- unconditional NOINLINE, etc. See TidyPgm.addExternal
1463 unfold_hsinfo | no_unfolding = Nothing
1464 | has_worker = Nothing -- Unfolding is implicit
1465 | otherwise = Just (HsUnfold (toIfaceExpr rhs))
1467 ------------ Inline prag --------------
1468 inline_prag = inlinePragInfo id_info
1469 inline_hsinfo | isAlwaysActive inline_prag = Nothing
1470 | no_unfolding && not has_worker = Nothing
1471 -- If the iface file give no unfolding info, we
1472 -- don't need to say when inlining is OK!
1473 | otherwise = Just (HsInline inline_prag)
1475 --------------------------
1476 coreRuleToIfaceRule :: Module -> CoreRule -> IfaceRule
1477 coreRuleToIfaceRule _ (BuiltinRule { ru_fn = fn})
1478 = pprTrace "toHsRule: builtin" (ppr fn) $
1481 coreRuleToIfaceRule mod (Rule { ru_name = name, ru_fn = fn,
1482 ru_act = act, ru_bndrs = bndrs,
1483 ru_args = args, ru_rhs = rhs })
1484 = IfaceRule { ifRuleName = name, ifActivation = act,
1485 ifRuleBndrs = map toIfaceBndr bndrs,
1487 ifRuleArgs = map do_arg args,
1488 ifRuleRhs = toIfaceExpr rhs,
1491 -- For type args we must remove synonyms from the outermost
1492 -- level. Reason: so that when we read it back in we'll
1493 -- construct the same ru_rough field as we have right now;
1495 do_arg (Type ty) = IfaceType (toIfaceType (deNoteType ty))
1496 do_arg arg = toIfaceExpr arg
1498 -- Compute orphanhood. See Note [Orphans] in IfaceSyn
1499 -- A rule is an orphan only if none of the variables
1500 -- mentioned on its left-hand side are locally defined
1501 lhs_names = fn : nameSetToList (exprsFreeNames args)
1502 -- No need to delete bndrs, because
1503 -- exprsFreeNames finds only External names
1505 orph = case filter (nameIsLocalOrFrom mod) lhs_names of
1506 (n : _) -> Just (nameOccName n)
1509 bogusIfaceRule :: Name -> IfaceRule
1510 bogusIfaceRule id_name
1511 = IfaceRule { ifRuleName = fsLit "bogus", ifActivation = NeverActive,
1512 ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [],
1513 ifRuleRhs = IfaceExt id_name, ifRuleOrph = Nothing }
1515 ---------------------
1516 toIfaceExpr :: CoreExpr -> IfaceExpr
1517 toIfaceExpr (Var v) = toIfaceVar v
1518 toIfaceExpr (Lit l) = IfaceLit l
1519 toIfaceExpr (Type ty) = IfaceType (toIfaceType ty)
1520 toIfaceExpr (Lam x b) = IfaceLam (toIfaceBndr x) (toIfaceExpr b)
1521 toIfaceExpr (App f a) = toIfaceApp f [a]
1522 toIfaceExpr (Case s x ty as) = IfaceCase (toIfaceExpr s) (getFS x) (toIfaceType ty) (map toIfaceAlt as)
1523 toIfaceExpr (Let b e) = IfaceLet (toIfaceBind b) (toIfaceExpr e)
1524 toIfaceExpr (Cast e co) = IfaceCast (toIfaceExpr e) (toIfaceType co)
1525 toIfaceExpr (Note n e) = IfaceNote (toIfaceNote n) (toIfaceExpr e)
1527 ---------------------
1528 toIfaceNote :: Note -> IfaceNote
1529 toIfaceNote (SCC cc) = IfaceSCC cc
1530 toIfaceNote InlineMe = IfaceInlineMe
1531 toIfaceNote (CoreNote s) = IfaceCoreNote s
1533 ---------------------
1534 toIfaceBind :: Bind Id -> IfaceBinding
1535 toIfaceBind (NonRec b r) = IfaceNonRec (toIfaceLetBndr b) (toIfaceExpr r)
1536 toIfaceBind (Rec prs) = IfaceRec [(toIfaceLetBndr b, toIfaceExpr r) | (b,r) <- prs]
1538 ---------------------
1539 toIfaceAlt :: (AltCon, [Var], CoreExpr)
1540 -> (IfaceConAlt, [FastString], IfaceExpr)
1541 toIfaceAlt (c,bs,r) = (toIfaceCon c, map getFS bs, toIfaceExpr r)
1543 ---------------------
1544 toIfaceCon :: AltCon -> IfaceConAlt
1545 toIfaceCon (DataAlt dc) | isTupleTyCon tc = IfaceTupleAlt (tupleTyConBoxity tc)
1546 | otherwise = IfaceDataAlt (getName dc)
1548 tc = dataConTyCon dc
1550 toIfaceCon (LitAlt l) = IfaceLitAlt l
1551 toIfaceCon DEFAULT = IfaceDefault
1553 ---------------------
1554 toIfaceApp :: Expr CoreBndr -> [Arg CoreBndr] -> IfaceExpr
1555 toIfaceApp (App f a) as = toIfaceApp f (a:as)
1556 toIfaceApp (Var v) as
1557 = case isDataConWorkId_maybe v of
1558 -- We convert the *worker* for tuples into IfaceTuples
1559 Just dc | isTupleTyCon tc && saturated
1560 -> IfaceTuple (tupleTyConBoxity tc) tup_args
1562 val_args = dropWhile isTypeArg as
1563 saturated = val_args `lengthIs` idArity v
1564 tup_args = map toIfaceExpr val_args
1565 tc = dataConTyCon dc
1567 _ -> mkIfaceApps (toIfaceVar v) as
1569 toIfaceApp e as = mkIfaceApps (toIfaceExpr e) as
1571 mkIfaceApps :: IfaceExpr -> [CoreExpr] -> IfaceExpr
1572 mkIfaceApps f as = foldl (\f a -> IfaceApp f (toIfaceExpr a)) f as
1574 ---------------------
1575 toIfaceVar :: Id -> IfaceExpr
1577 | Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType (idType v))
1578 -- Foreign calls have special syntax
1579 | isExternalName name = IfaceExt name
1580 | Just (TickBox m ix) <- isTickBoxOp_maybe v
1582 | otherwise = IfaceLcl (getFS name)