2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
17 mkIface, -- Build a ModIface from a ModGuts,
18 -- including computing version information
22 writeIfaceFile, -- Write the interface file
24 checkOldIface, -- See if recompilation is required, by
25 -- comparing version information
27 tyThingToIfaceDecl -- Converting things to their Iface equivalents
31 -----------------------------------------------
32 MkIface.lhs deals with versioning
33 -----------------------------------------------
35 Here's the version-related info in an interface file
37 module Foo 8 -- module-version
38 3 -- export-list-version
40 Usages: -- Version info for what this compilation of Foo imported
41 Baz 3 -- Module version
42 [4] -- The export-list version if Foo depended on it
43 (g,2) -- Function and its version
44 (T,1) -- Type and its version
46 <version> f :: Int -> Int {- Unfolding: \x -> Wib.t[2] x -}
47 -- The [2] says that f's unfolding
48 -- mentions verison 2 of Wib.t
50 -----------------------------------------------
52 -----------------------------------------------
55 * In the mi_usages information in an interface, we record the
56 version number of each free variable of the module
58 * In mkIface, we compute the version number of each exported thing A.f
59 by comparing its A.f's info with its new info, and bumping its
60 version number if it differs. If A.f mentions B.g, and B.g's version
61 number has changed, then we count A.f as having changed too.
63 * In checkOldIface we compare the mi_usages for the module with
64 the actual version info for all each thing recorded in mi_usages
69 We count A.f as changing if its fixity changes
73 If a rule changes, we want to recompile any module that might be
74 affected by that rule. For non-orphan rules, this is relatively easy.
75 If module M defines f, and a rule for f, just arrange that the version
76 number for M.f changes if any of the rules for M.f change. Any module
77 that does not depend on M.f can't be affected by the rule-change
80 Orphan rules (ones whose 'head function' is not defined in M) are
81 harder. Here's what we do.
83 * We have a per-module orphan-rule version number which changes if
84 any orphan rule changes. (It's unaffected by non-orphan rules.)
86 * We record usage info for any orphan module 'below' this one,
87 giving the orphan-rule version number. We recompile if this
90 The net effect is that if an orphan rule changes, we recompile every
91 module above it. That's very conservative, but it's devilishly hard
92 to know what it might affect, so we just have to be conservative.
96 In an iface file we have
98 instance Eq a => Eq [a] = dfun29
101 We have a version number for dfun29, covering its unfolding
102 etc. Suppose we are compiling a module M that imports A only
103 indirectly. If typechecking M uses this instance decl, we record the
104 dependency on A.dfun29 as if it were a free variable of the module
105 (via the tcg_inst_usages accumulator). That means that A will appear
106 in M's usage list. If the shape of the instance declaration changes,
107 then so will dfun29's version, triggering a recompilation.
109 Adding an instance declaration, or changing an instance decl that is
110 not currently used, is more tricky. (This really only makes a
111 difference when we have overlapping instance decls, because then the
112 new instance decl might kick in to override the old one.) We handle
113 this in a very similar way that we handle rules above.
115 * For non-orphan instance decls, identify one locally-defined tycon/class
116 mentioned in the decl. Treat the instance decl as part of the defn of that
117 tycon/class, so that if the shape of the instance decl changes, so does the
118 tycon/class; that in turn will force recompilation of anything that uses
121 * For orphan instance decls, act the same way as for orphan rules.
122 Indeed, we use the same global orphan-rule version number.
126 mkUsageInfo figures out what the ``usage information'' for this
127 moudule is; that is, what it must record in its interface file as the
130 We produce a line for every module B below the module, A, currently being
133 to record the fact that A does import B indirectly. This is used to decide
134 to look for B.hi rather than B.hi-boot when compiling a module that
135 imports A. This line says that A imports B, but uses nothing in it.
136 So we'll get an early bale-out when compiling A if B's version changes.
138 The usage information records:
141 \item (a) anything reachable from its body code
142 \item (b) any module exported with a @module Foo@
143 \item (c) anything reachable from an exported item
146 Why (b)? Because if @Foo@ changes then this module's export list
147 will change, so we must recompile this module at least as far as
148 making a new interface file --- but in practice that means complete
151 Why (c)? Consider this:
153 module A( f, g ) where | module B( f ) where
154 import B( f ) | f = h 3
158 Here, @B.f@ isn't used in A. Should we nevertheless record @B.f@ in
159 @A@'s usages? Our idea is that we aren't going to touch A.hi if it is
160 *identical* to what it was before. If anything about @B.f@ changes
161 than anyone who imports @A@ should be recompiled in case they use
162 @B.f@ (they'll get an early exit if they don't). So, if anything
163 about @B.f@ changes we'd better make sure that something in A.hi
164 changes, and the convenient way to do that is to record the version
165 number @B.f@ in A.hi in the usage list. If B.f changes that'll force a
166 complete recompiation of A, which is overkill but it's the only way to
167 write a new, slightly different, A.hi.
169 But the example is tricker. Even if @B.f@ doesn't change at all,
170 @B.h@ may do so, and this change may not be reflected in @f@'s version
171 number. But with -O, a module that imports A must be recompiled if
172 @B.h@ changes! So A must record a dependency on @B.h@. So we treat
173 the occurrence of @B.f@ in the export list *just as if* it were in the
174 code of A, and thereby haul in all the stuff reachable from it.
176 *** Conclusion: if A mentions B.f in its export list,
177 behave just as if A mentioned B.f in its source code,
178 and slurp in B.f and all its transitive closure ***
180 [NB: If B was compiled with -O, but A isn't, we should really *still*
181 haul in all the unfoldings for B, in case the module that imports A *is*
182 compiled with -O. I think this is the case.]
184 SimonM [30/11/2007]: I believe the above is all out of date; the
185 current implementation doesn't do it this way. Instead, when any of
186 the dependencies of a declaration changes, the version of the
187 declaration itself changes.
190 #include "HsVersions.h"
223 import PackageConfig hiding ( Version )
225 import BasicTypes hiding ( SuccessFlag(..) )
227 import Util hiding ( eqListBy )
236 import System.FilePath
241 %************************************************************************
243 \subsection{Completing an interface}
245 %************************************************************************
249 -> Maybe ModIface -- The old interface, if we have it
250 -> ModDetails -- The trimmed, tidied interface
251 -> ModGuts -- Usages, deprecations, etc
252 -> IO (ModIface, -- The new one, complete with decls and versions
253 Bool) -- True <=> there was an old Iface, and the new one
254 -- is identical, so no need to write it
256 mkIface hsc_env maybe_old_iface mod_details
257 ModGuts{ mg_module = this_mod,
259 mg_used_names = used_names,
261 mg_dir_imps = dir_imp_mods,
262 mg_rdr_env = rdr_env,
263 mg_fix_env = fix_env,
264 mg_deprecs = deprecs,
265 mg_hpc_info = hpc_info }
266 = mkIface_ hsc_env maybe_old_iface
267 this_mod is_boot used_names deps rdr_env
268 fix_env deprecs hpc_info dir_imp_mods mod_details
270 -- | make an interface from the results of typechecking only. Useful
271 -- for non-optimising compilation, or where we aren't generating any
272 -- object code at all ('HscNothing').
274 -> Maybe ModIface -- The old interface, if we have it
275 -> ModDetails -- gotten from mkBootModDetails, probably
276 -> TcGblEnv -- Usages, deprecations, etc
279 mkIfaceTc hsc_env maybe_old_iface mod_details
280 tc_result@TcGblEnv{ tcg_mod = this_mod,
282 tcg_imports = imports,
283 tcg_rdr_env = rdr_env,
284 tcg_fix_env = fix_env,
285 tcg_deprecs = deprecs,
286 tcg_hpc = other_hpc_info
289 used_names <- mkUsedNames tc_result
290 deps <- mkDependencies tc_result
291 let hpc_info = emptyHpcInfo other_hpc_info
292 mkIface_ hsc_env maybe_old_iface
293 this_mod (isHsBoot hsc_src) used_names deps rdr_env
294 fix_env deprecs hpc_info (imp_mods imports) mod_details
297 mkUsedNames :: TcGblEnv -> IO NameSet
299 TcGblEnv{ tcg_inst_uses = dfun_uses_var,
303 dfun_uses <- readIORef dfun_uses_var -- What dfuns are used
304 return (allUses dus `unionNameSets` dfun_uses)
306 mkDependencies :: TcGblEnv -> IO Dependencies
308 TcGblEnv{ tcg_mod = mod,
309 tcg_imports = imports,
313 th_used <- readIORef th_var -- Whether TH is used
315 dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
316 -- M.hi-boot can be in the imp_dep_mods, but we must remove
317 -- it before recording the modules on which this one depends!
318 -- (We want to retain M.hi-boot in imp_dep_mods so that
319 -- loadHiBootInterface can see if M's direct imports depend
320 -- on M.hi-boot, and hence that we should do the hi-boot consistency
323 dir_imp_mods = imp_mods imports
325 -- Modules don't compare lexicographically usually,
326 -- but we want them to do so here.
327 le_mod :: Module -> Module -> Bool
328 le_mod m1 m2 = moduleNameFS (moduleName m1)
329 <= moduleNameFS (moduleName m2)
331 le_dep_mod :: (ModuleName, IsBootInterface)
332 -> (ModuleName, IsBootInterface) -> Bool
333 le_dep_mod (m1,_) (m2,_) = moduleNameFS m1 <= moduleNameFS m2
336 pkgs | th_used = insertList thPackageId (imp_dep_pkgs imports)
337 | otherwise = imp_dep_pkgs imports
339 return Deps { dep_mods = sortLe le_dep_mod dep_mods,
340 dep_pkgs = sortLe (<=) pkgs,
341 dep_orphs = sortLe le_mod (imp_orphs imports),
342 dep_finsts = sortLe le_mod (imp_finsts imports) }
343 -- sort to get into canonical order
346 mkIface_ hsc_env maybe_old_iface
347 this_mod is_boot used_names deps rdr_env fix_env src_deprecs hpc_info
349 ModDetails{ md_insts = insts,
350 md_fam_insts = fam_insts,
352 md_vect_info = vect_info,
354 md_exports = exports }
355 -- NB: notice that mkIface does not look at the bindings
356 -- only at the TypeEnv. The previous Tidy phase has
357 -- put exactly the info into the TypeEnv that we want
358 -- to expose in the interface
360 = do {eps <- hscEPS hsc_env
362 ; usages <- mkUsageInfo hsc_env dir_imp_mods (dep_mods deps) used_names
364 ; let { entities = typeEnvElts type_env ;
365 decls = [ tyThingToIfaceDecl entity
366 | entity <- entities,
367 let name = getName entity,
368 not (isImplicitTyThing entity),
369 -- No implicit Ids and class tycons in the interface file
370 not (isWiredInName name),
371 -- Nor wired-in things; the compiler knows about them anyhow
372 nameIsLocalOrFrom this_mod name ]
373 -- Sigh: see Note [Root-main Id] in TcRnDriver
375 ; fixities = [(occ,fix) | FixItem occ fix <- nameEnvElts fix_env]
376 ; deprecs = src_deprecs
377 ; iface_rules = map (coreRuleToIfaceRule this_mod) rules
378 ; iface_insts = map instanceToIfaceInst insts
379 ; iface_fam_insts = map famInstToIfaceFamInst fam_insts
380 ; iface_vect_info = flattenVectInfo vect_info
382 ; intermediate_iface = ModIface {
383 mi_module = this_mod,
387 mi_exports = mkIfaceExports exports,
389 -- Sort these lexicographically, so that
390 -- the result is stable across compilations
391 mi_insts = sortLe le_inst iface_insts,
392 mi_fam_insts= sortLe le_fam_inst iface_fam_insts,
393 mi_rules = sortLe le_rule iface_rules,
395 mi_vect_info = iface_vect_info,
397 mi_fixities = fixities,
398 mi_deprecs = deprecs,
399 mi_globals = Just rdr_env,
401 -- Left out deliberately: filled in by addVersionInfo
402 mi_mod_vers = initialVersion,
403 mi_exp_vers = initialVersion,
404 mi_rule_vers = initialVersion,
405 mi_orphan = False, -- Always set by addVersionInfo, but
406 -- it's a strict field, so we can't omit it.
407 mi_finsts = False, -- Ditto
408 mi_decls = deliberatelyOmitted "decls",
409 mi_ver_fn = deliberatelyOmitted "ver_fn",
410 mi_hpc = isHpcUsed hpc_info,
412 -- And build the cached values
413 mi_dep_fn = mkIfaceDepCache deprecs,
414 mi_fix_fn = mkIfaceFixCache fixities }
416 -- Add version information
417 ; ext_ver_fn = mkParentVerFun hsc_env eps
418 ; (new_iface, no_change_at_all, pp_diffs, pp_orphs)
419 = {-# SCC "versioninfo" #-}
420 addVersionInfo ext_ver_fn maybe_old_iface
421 intermediate_iface decls
425 ; when (isJust pp_orphs && dopt Opt_WarnOrphans dflags)
426 (printDump (expectJust "mkIface" pp_orphs))
427 ; when (dopt Opt_D_dump_hi_diffs dflags) (printDump pp_diffs)
428 ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
429 (pprModIface new_iface)
431 -- bug #1617: on reload we weren't updating the PrintUnqualified
432 -- correctly. This stems from the fact that the interface had
433 -- not changed, so addVersionInfo returns the old ModIface
434 -- with the old GlobalRdrEnv (mi_globals).
435 ; let final_iface = new_iface{ mi_globals = Just rdr_env }
437 ; return (final_iface, no_change_at_all) }
439 r1 `le_rule` r2 = ifRuleName r1 <= ifRuleName r2
440 i1 `le_inst` i2 = ifDFun i1 `le_occ` ifDFun i2
441 i1 `le_fam_inst` i2 = ifFamInstTcName i1 `le_occ` ifFamInstTcName i2
443 le_occ :: Name -> Name -> Bool
444 -- Compare lexicographically by OccName, *not* by unique, because
445 -- the latter is not stable across compilations
446 le_occ n1 n2 = nameOccName n1 <= nameOccName n2
448 dflags = hsc_dflags hsc_env
449 deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
450 ifFamInstTcName = ifaceTyConName . ifFamInstTyCon
452 flattenVectInfo (VectInfo { vectInfoVar = vVar
453 , vectInfoTyCon = vTyCon
456 ifaceVectInfoVar = [ Var.varName v
457 | (v, _) <- varEnvElts vVar],
458 ifaceVectInfoTyCon = [ tyConName t
459 | (t, t_v) <- nameEnvElts vTyCon
461 ifaceVectInfoTyConReuse = [ tyConName t
462 | (t, t_v) <- nameEnvElts vTyCon
466 -----------------------------
467 writeIfaceFile :: DynFlags -> ModLocation -> ModIface -> IO ()
468 writeIfaceFile dflags location new_iface
469 = do createDirectoryHierarchy (takeDirectory hi_file_path)
470 writeBinIface dflags hi_file_path new_iface
471 where hi_file_path = ml_hi_file location
474 -- -----------------------------------------------------------------------------
475 -- Look up parents and versions of Names
477 -- This is like a global version of the mi_ver_fn field in each ModIface.
478 -- Given a Name, it finds the ModIface, and then uses mi_ver_fn to get
479 -- the parent and version info.
482 :: HscEnv -- needed to look up versions
483 -> ExternalPackageState -- ditto
484 -> (Name -> (OccName,Version))
485 mkParentVerFun hsc_env eps
488 mod = nameModule name
489 occ = nameOccName name
490 iface = lookupIfaceByModule (hsc_dflags hsc_env) hpt pit mod `orElse`
491 pprPanic "lookupVers2" (ppr mod <+> ppr occ)
493 mi_ver_fn iface occ `orElse`
494 pprPanic "lookupVers1" (ppr mod <+> ppr occ)
496 hpt = hsc_HPT hsc_env
499 -----------------------------------------------------------------------------
500 -- Compute version numbers for local decls
503 :: (Name -> (OccName,Version)) -- lookup parents and versions of names
504 -> Maybe ModIface -- The old interface, read from M.hi
505 -> ModIface -- The new interface (lacking decls)
506 -> [IfaceDecl] -- The new decls
507 -> (ModIface, -- Updated interface
508 Bool, -- True <=> no changes at all; no need to write Iface
510 Maybe SDoc) -- Warnings about orphans
512 addVersionInfo ver_fn Nothing new_iface new_decls
513 -- No old interface, so definitely write a new one!
514 = (new_iface { mi_orphan = not (null orph_insts && null orph_rules)
515 , mi_finsts = not . null $ mi_fam_insts new_iface
516 , mi_decls = [(initialVersion, decl) | decl <- new_decls]
517 , mi_ver_fn = mkIfaceVerCache (zip (repeat initialVersion)
521 ptext (sLit "No old interface file"),
522 pprOrphans orph_insts orph_rules)
524 orph_insts = filter (isNothing . ifInstOrph) (mi_insts new_iface)
525 orph_rules = filter (isNothing . ifRuleOrph) (mi_rules new_iface)
527 addVersionInfo ver_fn (Just old_iface@(ModIface {
528 mi_mod_vers = old_mod_vers,
529 mi_exp_vers = old_exp_vers,
530 mi_rule_vers = old_rule_vers,
531 mi_decls = old_decls,
532 mi_ver_fn = old_decl_vers,
533 mi_fix_fn = old_fixities }))
534 new_iface@(ModIface { mi_fix_fn = new_fixities })
537 = (old_iface, True, ptext (sLit "Interface file unchanged"), pp_orphs)
539 = (final_iface, False, vcat [ptext (sLit "Interface file has changed"),
540 nest 2 pp_diffs], pp_orphs)
542 final_iface = new_iface {
543 mi_mod_vers = bump_unless no_output_change old_mod_vers,
544 mi_exp_vers = bump_unless no_export_change old_exp_vers,
545 mi_rule_vers = bump_unless no_rule_change old_rule_vers,
546 mi_orphan = not (null new_orph_rules && null new_orph_insts),
547 mi_finsts = not . null $ mi_fam_insts new_iface,
548 mi_decls = decls_w_vers,
549 mi_ver_fn = mkIfaceVerCache decls_w_vers }
551 decls_w_vers = [(add_vers decl, decl) | decl <- new_decls]
554 (old_non_orph_insts, old_orph_insts) =
555 mkOrphMap ifInstOrph (mi_insts old_iface)
556 (new_non_orph_insts, new_orph_insts) =
557 mkOrphMap ifInstOrph (mi_insts new_iface)
558 old_fam_insts = mi_fam_insts old_iface
559 new_fam_insts = mi_fam_insts new_iface
560 same_insts occ = eqMaybeBy (eqListBy eqIfInst)
561 (lookupOccEnv old_non_orph_insts occ)
562 (lookupOccEnv new_non_orph_insts occ)
564 (old_non_orph_rules, old_orph_rules) =
565 mkOrphMap ifRuleOrph (mi_rules old_iface)
566 (new_non_orph_rules, new_orph_rules) =
567 mkOrphMap ifRuleOrph (mi_rules new_iface)
568 same_rules occ = eqMaybeBy (eqListBy eqIfRule)
569 (lookupOccEnv old_non_orph_rules occ)
570 (lookupOccEnv new_non_orph_rules occ)
572 -- Computing what changed
573 no_output_change = no_decl_change && no_rule_change &&
574 no_export_change && no_deprec_change
575 no_export_change = mi_exports new_iface == mi_exports old_iface
577 no_decl_change = isEmptyOccSet changed_occs
578 no_rule_change = not (changedWrtNames changed_occs (eqListBy eqIfRule old_orph_rules new_orph_rules)
579 || changedWrtNames changed_occs (eqListBy eqIfInst old_orph_insts new_orph_insts)
580 || changedWrtNames changed_occs (eqListBy eqIfFamInst old_fam_insts new_fam_insts))
581 no_deprec_change = mi_deprecs new_iface == mi_deprecs old_iface
583 -- If the usages havn't changed either, we don't need to write the interface file
584 no_other_changes = mi_usages new_iface == mi_usages old_iface &&
585 mi_deps new_iface == mi_deps old_iface &&
586 mi_hpc new_iface == mi_hpc old_iface
587 no_change_at_all = no_output_change && no_other_changes
589 pp_diffs = vcat [pp_change no_export_change "Export list"
590 (ppr old_exp_vers <+> arrow <+> ppr (mi_exp_vers final_iface)),
591 pp_change no_rule_change "Rules"
592 (ppr old_rule_vers <+> arrow <+> ppr (mi_rule_vers final_iface)),
593 pp_change no_deprec_change "Deprecations" empty,
594 pp_change no_other_changes "Usages" empty,
596 pp_change True what info = empty
597 pp_change False what info = text what <+> ptext (sLit "changed") <+> info
600 old_decl_env = mkOccEnv [(ifName decl, decl) | (_,decl) <- old_decls]
601 same_fixity n = bool (old_fixities n == new_fixities n)
604 -- Adding version info
605 new_version = bumpVersion old_mod_vers
606 -- Start from the old module version, not from
607 -- zero so that if you remove f, and then add
608 -- it again, you don't thereby reduce f's
611 add_vers decl | occ `elemOccSet` changed_occs = new_version
612 | otherwise = snd (expectJust "add_vers" (old_decl_vers occ))
613 -- If it's unchanged, there jolly well
614 where -- should be an old version number
618 -- Deciding which declarations have changed
620 -- For each local decl, the IfaceEq gives the list of things that
621 -- must be unchanged for the declaration as a whole to be unchanged.
622 eq_info :: [(OccName, IfaceEq)]
623 eq_info = map check_eq new_decls
625 | Just old_decl <- lookupOccEnv old_decl_env occ
626 = (occ, new_decl `eqIfDecl` old_decl &&& eq_indirects new_decl)
627 | otherwise {- No corresponding old decl -}
630 occ = ifName new_decl
632 eq_indirects :: IfaceDecl -> IfaceEq
633 -- When seeing if two decls are the same, remember to
634 -- check whether any relevant fixity or rules have changed
635 eq_indirects (IfaceId {ifName = occ}) = eq_ind_occ occ
636 eq_indirects (IfaceClass {ifName = cls_occ, ifSigs = sigs})
637 = same_insts cls_occ &&&
638 eq_ind_occs [op | IfaceClassOp op _ _ <- sigs]
639 eq_indirects (IfaceData {ifName = tc_occ, ifCons = cons})
640 = same_insts tc_occ &&& same_fixity tc_occ &&& -- The TyCon can have a fixity too
641 eq_ind_occs (map ifConOcc (visibleIfConDecls cons))
642 eq_indirects other = Equal -- Synonyms and foreign declarations
644 eq_ind_occ :: OccName -> IfaceEq -- For class ops and Ids; check fixity and rules
645 eq_ind_occ occ = same_fixity occ &&& same_rules occ
646 eq_ind_occs = foldr ((&&&) . eq_ind_occ) Equal
648 -- The Occs of declarations that changed.
649 changed_occs :: OccSet
650 changed_occs = computeChangedOccs ver_fn (mi_module new_iface)
651 (mi_usages old_iface) eq_info
655 pp_decl_diffs :: SDoc -- Nothing => no changes
657 | isEmptyOccSet changed_occs = empty
659 = vcat [ptext (sLit "Changed occs:") <+> ppr (occSetElts changed_occs),
660 ptext (sLit "Version change for these decls:"),
661 nest 2 (vcat (map show_change new_decls))]
663 eq_env = mkOccEnv eq_info
665 | not (occ `elemOccSet` changed_occs) = empty
667 = vcat [ppr occ <+> ppr (old_decl_vers occ) <+> arrow <+> ppr new_version,
670 occ = ifName new_decl
671 why = case lookupOccEnv eq_env occ of
672 Just (EqBut names) -> sep [ppr occ <> colon, ptext (sLit "Free vars (only) changed:") <> ppr names,
673 nest 2 (braces (fsep (map ppr (occSetElts
674 (occs `intersectOccSet` changed_occs)))))]
675 where occs = mkOccSet (map nameOccName (nameSetToList names))
677 | Just old_decl <- lookupOccEnv old_decl_env occ
678 -> vcat [ptext (sLit "Old:") <+> ppr old_decl,
679 ptext (sLit "New:") <+> ppr new_decl]
681 -> ppr occ <+> ptext (sLit "only in new interface")
682 other -> pprPanic "MkIface.show_change" (ppr occ)
684 pp_orphs = pprOrphans new_orph_insts new_orph_rules
687 pprOrphans insts rules
688 | null insts && null rules = Nothing
691 if null insts then empty else
692 hang (ptext (sLit "Warning: orphan instances:"))
693 2 (vcat (map ppr insts)),
694 if null rules then empty else
695 hang (ptext (sLit "Warning: orphan rules:"))
696 2 (vcat (map ppr rules))
700 :: (Name -> (OccName,Version)) -- get parents and versions
701 -> Module -- This module
702 -> [Usage] -- Usages from old iface
703 -> [(OccName, IfaceEq)] -- decl names, equality conditions
704 -> OccSet -- set of things that have changed
705 computeChangedOccs ver_fn this_module old_usages eq_info
706 = foldl add_changes emptyOccSet (stronglyConnComp edges)
709 -- return True if an external name has changed
710 name_changed :: Name -> Bool
712 | isWiredInName nm -- Wired-in things don't get into interface
713 = False -- files and hence don't get into the ver_fn
714 | Just ents <- lookupUFM usg_modmap (moduleName mod),
715 Just v <- lookupUFM ents parent_occ
717 | modulePackageId mod == this_pkg
718 = WARN(True, ptext (sLit "computeChangedOccs") <+> ppr nm) True
719 -- should really be a panic, see #1959. The problem is that the usages doesn't
720 -- contain all the names that might be referred to by unfoldings. So as a
721 -- conservative workaround we just assume these names have changed.
722 | otherwise = False -- must be in another package
725 (parent_occ, new_version) = ver_fn nm
727 this_pkg = modulePackageId this_module
729 -- Turn the usages from the old ModIface into a mapping
730 usg_modmap = listToUFM [ (usg_name usg, listToUFM (usg_entities usg))
731 | usg <- old_usages ]
733 get_local_eq_info :: GenIfaceEq Name -> GenIfaceEq OccName
734 get_local_eq_info Equal = Equal
735 get_local_eq_info NotEqual = NotEqual
736 get_local_eq_info (EqBut ns) = foldNameSet f Equal ns
737 where f name eq | nameModule name == this_module =
738 EqBut (unitOccSet (nameOccName name)) `and_occifeq` eq
739 | name_changed name = NotEqual
742 local_eq_infos = mapSnd get_local_eq_info eq_info
744 edges :: [((OccName, OccIfaceEq), Unique, [Unique])]
745 edges = [ (node, getUnique occ, map getUnique occs)
746 | node@(occ, iface_eq) <- local_eq_infos
747 , let occs = case iface_eq of
748 EqBut occ_set -> occSetElts occ_set
751 -- Changes in declarations
752 add_changes :: OccSet -> SCC (OccName, OccIfaceEq) -> OccSet
753 add_changes so_far (AcyclicSCC (occ, iface_eq))
754 | changedWrt so_far iface_eq -- This one has changed
755 = extendOccSet so_far occ
756 add_changes so_far (CyclicSCC pairs)
757 | changedWrt so_far (foldr1 and_occifeq iface_eqs)
758 -- One of this group has changed
759 = extendOccSetList so_far occs
760 where (occs, iface_eqs) = unzip pairs
761 add_changes so_far other = so_far
763 type OccIfaceEq = GenIfaceEq OccName
765 changedWrt :: OccSet -> OccIfaceEq -> Bool
766 changedWrt so_far Equal = False
767 changedWrt so_far NotEqual = True
768 changedWrt so_far (EqBut kids) = so_far `intersectsOccSet` kids
770 changedWrtNames :: OccSet -> IfaceEq -> Bool
771 changedWrtNames so_far Equal = False
772 changedWrtNames so_far NotEqual = True
773 changedWrtNames so_far (EqBut kids) =
774 so_far `intersectsOccSet` mkOccSet (map nameOccName (nameSetToList kids))
776 and_occifeq :: OccIfaceEq -> OccIfaceEq -> OccIfaceEq
777 Equal `and_occifeq` x = x
778 NotEqual `and_occifeq` x = NotEqual
779 EqBut nms `and_occifeq` Equal = EqBut nms
780 EqBut nms `and_occifeq` NotEqual = NotEqual
781 EqBut nms1 `and_occifeq` EqBut nms2 = EqBut (nms1 `unionOccSets` nms2)
783 ----------------------
784 -- mkOrphMap partitions instance decls or rules into
785 -- (a) an OccEnv for ones that are not orphans,
786 -- mapping the local OccName to a list of its decls
787 -- (b) a list of orphan decls
788 mkOrphMap :: (decl -> Maybe OccName) -- (Just occ) for a non-orphan decl, keyed by occ
789 -- Nothing for an orphan decl
790 -> [decl] -- Sorted into canonical order
791 -> (OccEnv [decl], -- Non-orphan decls associated with their key;
792 -- each sublist in canonical order
793 [decl]) -- Orphan decls; in canonical order
794 mkOrphMap get_key decls
795 = foldl go (emptyOccEnv, []) decls
797 go (non_orphs, orphs) d
798 | Just occ <- get_key d
799 = (extendOccEnv_C (\ ds _ -> d:ds) non_orphs occ [d], orphs)
800 | otherwise = (non_orphs, d:orphs)
802 ----------------------
803 bump_unless :: Bool -> Version -> Version
804 bump_unless True v = v -- True <=> no change
805 bump_unless False v = bumpVersion v
809 %*********************************************************
811 \subsection{Keeping track of what we've slurped, and version numbers}
813 %*********************************************************
817 mkUsageInfo :: HscEnv
818 -> ModuleEnv (Module, [(ModuleName, Bool, SrcSpan)])
819 -> [(ModuleName, IsBootInterface)]
820 -> NameSet -> IO [Usage]
821 mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
822 = do { eps <- hscEPS hsc_env
823 ; let usages = mk_usage_info (eps_PIT eps) hsc_env
824 dir_imp_mods dep_mods used_names
825 ; usages `seqList` return usages }
826 -- seq the list of Usages returned: occasionally these
827 -- don't get evaluated for a while and we can end up hanging on to
828 -- the entire collection of Ifaces.
830 mk_usage_info :: PackageIfaceTable
832 -> ModuleEnv (Module, [(ModuleName, Bool, SrcSpan)])
833 -> [(ModuleName, IsBootInterface)]
836 mk_usage_info pit hsc_env dir_imp_mods dep_mods used_names
837 = mapCatMaybes mkUsage dep_mods
838 -- ToDo: do we need to sort into canonical order?
840 hpt = hsc_HPT hsc_env
841 dflags = hsc_dflags hsc_env
843 -- ent_map groups together all the things imported and used
844 -- from a particular module in this package
845 ent_map :: ModuleEnv [OccName]
846 ent_map = foldNameSet add_mv emptyModuleEnv used_names
848 | isWiredInName name = mv_map -- ignore wired-in names
850 = case nameModule_maybe name of
851 Nothing -> mv_map -- ignore internal names
852 Just mod -> extendModuleEnv_C add_item mv_map mod [occ]
854 occ = nameOccName name
855 add_item occs _ = occ:occs
857 depend_on_exports mod = case lookupModuleEnv dir_imp_mods mod of
858 Just (_, xs) -> any (\(_, no_imp, _) -> not no_imp) xs
861 -- We want to create a Usage for a home module if
862 -- a) we used something from; has something in used_names
863 -- b) we imported all of it, even if we used nothing from it
864 -- (need to recompile if its export list changes: export_vers)
865 -- c) is a home-package orphan or family-instance module (need to
866 -- recompile if its instance decls change: rules_vers)
867 mkUsage :: (ModuleName, IsBootInterface) -> Maybe Usage
868 mkUsage (mod_name, _)
869 | isNothing maybe_iface -- We can't depend on it if we didn't
870 || (null used_occs -- load its interface.
871 && isNothing export_vers
874 = Nothing -- Record no usage info
877 = Just (Usage { usg_name = mod_name,
879 usg_exports = export_vers,
880 usg_entities = fmToList ent_vers,
881 usg_rules = rules_vers })
883 maybe_iface = lookupIfaceByModule dflags hpt pit mod
884 -- In one-shot mode, the interfaces for home-package
885 -- modules accumulate in the PIT not HPT. Sigh.
887 mod = mkModule (thisPackage dflags) mod_name
889 Just iface = maybe_iface
890 orphan_mod = mi_orphan iface
891 finsts_mod = mi_finsts iface
892 version_env = mi_ver_fn iface
893 mod_vers = mi_mod_vers iface
894 rules_vers = mi_rule_vers iface
895 export_vers | depend_on_exports mod = Just (mi_exp_vers iface)
896 | otherwise = Nothing
898 used_occs = lookupModuleEnv ent_map mod `orElse` []
900 -- Making a FiniteMap here ensures that (a) we remove duplicates
901 -- when we have usages on several subordinates of a single parent,
902 -- and (b) that the usages emerge in a canonical order, which
903 -- is why we use FiniteMap rather than OccEnv: FiniteMap works
904 -- using Ord on the OccNames, which is a lexicographic ordering.
905 ent_vers :: FiniteMap OccName Version
906 ent_vers = listToFM (map lookup_occ used_occs)
909 case version_env occ of
910 Nothing -> pprTrace "hmm, strange" (ppr mod <+> ppr occ) $
911 (occ, initialVersion) -- does this ever happen?
912 Just (parent, version) -> (parent, version)
916 mkIfaceExports :: [AvailInfo]
917 -> [(Module, [GenAvailInfo OccName])]
918 -- Group by module and sort by occurrence
919 -- This keeps the list in canonical order
920 mkIfaceExports exports
921 = [ (mod, eltsFM avails)
922 | (mod, avails) <- fmToList groupFM
925 -- Group by the module where the exported entities are defined
926 -- (which may not be the same for all Names in an Avail)
927 -- Deliberately use FiniteMap rather than UniqFM so we
928 -- get a canonical ordering
929 groupFM :: ModuleEnv (FiniteMap FastString (GenAvailInfo OccName))
930 groupFM = foldl add emptyModuleEnv exports
932 add_one :: ModuleEnv (FiniteMap FastString (GenAvailInfo OccName))
933 -> Module -> GenAvailInfo OccName
934 -> ModuleEnv (FiniteMap FastString (GenAvailInfo OccName))
935 add_one env mod avail
936 = extendModuleEnv_C plusFM env mod
937 (unitFM (occNameFS (availName avail)) avail)
939 -- NB: we should not get T(X) and T(Y) in the export list
940 -- else the plusFM will simply discard one! They
941 -- should have been combined by now.
943 = add_one env (nameModule n) (Avail (nameOccName n))
945 add env (AvailTC tc ns)
946 = foldl add_for_mod env mods
948 tc_occ = nameOccName tc
949 mods = nub (map nameModule ns)
950 -- Usually just one, but see Note [Original module]
953 = add_one env mod (AvailTC tc_occ (sort names_from_mod))
954 -- NB. sort the children, we need a canonical order
956 names_from_mod = [nameOccName n | n <- ns, nameModule n == mod]
959 Note [Orignal module]
960 ~~~~~~~~~~~~~~~~~~~~~
962 module X where { data family T }
963 module Y( T(..) ) where { import X; data instance T Int = MkT Int }
964 The exported Avail from Y will look like
967 - only MkT is brought into scope by the data instance;
968 - but the parent (used for grouping and naming in T(..) exports) is X.T
969 - and in this case we export X.T too
971 In the result of MkIfaceExports, the names are grouped by defining module,
972 so we may need to split up a single Avail into multiple ones.
975 %************************************************************************
977 Load the old interface file for this module (unless
978 we have it aleady), and check whether it is up to date
981 %************************************************************************
984 checkOldIface :: HscEnv
986 -> Bool -- Source unchanged
987 -> Maybe ModIface -- Old interface from compilation manager, if any
988 -> IO (RecompileRequired, Maybe ModIface)
990 checkOldIface hsc_env mod_summary source_unchanged maybe_iface
991 = do { showPass (hsc_dflags hsc_env)
992 ("Checking old interface for " ++
993 showSDoc (ppr (ms_mod mod_summary))) ;
995 ; initIfaceCheck hsc_env $
996 check_old_iface hsc_env mod_summary source_unchanged maybe_iface
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 = False -- Recompile not required
1046 outOfDate = True -- Recompile required
1048 checkVersions :: HscEnv
1049 -> Bool -- True <=> source unchanged
1051 -> ModIface -- Old interface
1052 -> IfG RecompileRequired
1053 checkVersions hsc_env source_unchanged mod_summary iface
1054 | not source_unchanged
1057 = do { traceHiDiffs (text "Considering whether compilation is required for" <+>
1058 ppr (mi_module iface) <> colon)
1060 ; recomp <- checkDependencies hsc_env mod_summary iface
1061 ; if recomp then return outOfDate else do {
1063 -- Source code unchanged and no errors yet... carry on
1065 -- First put the dependent-module info, read from the old interface, into the envt,
1066 -- so that when we look for interfaces we look for the right one (.hi or .hi-boot)
1068 -- It's just temporary because either the usage check will succeed
1069 -- (in which case we are done with this module) or it'll fail (in which
1070 -- case we'll compile the module from scratch anyhow).
1072 -- We do this regardless of compilation mode, although in --make mode
1073 -- all the dependent modules should be in the HPT already, so it's
1075 updateEps_ $ \eps -> eps { eps_is_boot = mod_deps }
1077 ; let this_pkg = thisPackage (hsc_dflags hsc_env)
1078 ; checkList [checkModUsage this_pkg u | u <- mi_usages iface]
1081 -- This is a bit of a hack really
1082 mod_deps :: ModuleNameEnv (ModuleName, IsBootInterface)
1083 mod_deps = mkModDeps (dep_mods (mi_deps iface))
1086 -- If the direct imports of this module are resolved to targets that
1087 -- are not among the dependencies of the previous interface file,
1088 -- then we definitely need to recompile. This catches cases like
1089 -- - an exposed package has been upgraded
1090 -- - we are compiling with different package flags
1091 -- - a home module that was shadowing a package module has been removed
1092 -- - a new home module has been added that shadows a package module
1095 -- Returns True if recompilation is required.
1096 checkDependencies :: HscEnv -> ModSummary -> ModIface -> IfG RecompileRequired
1097 checkDependencies hsc_env summary iface
1098 = orM (map dep_missing (ms_imps summary ++ ms_srcimps summary))
1100 prev_dep_mods = dep_mods (mi_deps iface)
1101 prev_dep_pkgs = dep_pkgs (mi_deps iface)
1103 this_pkg = thisPackage (hsc_dflags hsc_env)
1105 orM = foldr f (return False)
1106 where f m rest = do b <- m; if b then return True else rest
1108 dep_missing (L _ mod) = do
1109 find_res <- liftIO $ findImportedModule hsc_env mod Nothing
1113 -> if moduleName mod `notElem` map fst prev_dep_mods
1114 then do traceHiDiffs $
1115 text "imported module " <> quotes (ppr mod) <>
1116 text " not among previous dependencies"
1121 -> if pkg `notElem` prev_dep_pkgs
1122 then do traceHiDiffs $
1123 text "imported module " <> quotes (ppr mod) <>
1124 text " is from package " <> quotes (ppr pkg) <>
1125 text ", which is not among previous dependencies"
1129 where pkg = modulePackageId mod
1130 _otherwise -> return outOfDate
1132 checkModUsage :: PackageId ->Usage -> IfG RecompileRequired
1133 -- Given the usage information extracted from the old
1134 -- M.hi file for the module being compiled, figure out
1135 -- whether M needs to be recompiled.
1137 checkModUsage this_pkg (Usage { usg_name = mod_name, usg_mod = old_mod_vers,
1138 usg_rules = old_rule_vers,
1139 usg_exports = maybe_old_export_vers,
1140 usg_entities = old_decl_vers })
1141 = do -- Load the imported interface is possible
1142 let doc_str = sep [ptext (sLit "need version info for"), ppr mod_name]
1143 traceHiDiffs (text "Checking usages for module" <+> ppr mod_name)
1145 let mod = mkModule this_pkg mod_name
1147 mb_iface <- loadInterface doc_str mod ImportBySystem
1148 -- Load the interface, but don't complain on failure;
1149 -- Instead, get an Either back which we can test
1152 Failed exn -> (out_of_date (sep [ptext (sLit "Can't find version number for module"),
1154 -- Couldn't find or parse a module mentioned in the
1155 -- old interface file. Don't complain -- it might just be that
1156 -- the current module doesn't need that import and it's been deleted
1160 new_mod_vers = mi_mod_vers iface
1161 new_decl_vers = mi_ver_fn iface
1162 new_export_vers = mi_exp_vers iface
1163 new_rule_vers = mi_rule_vers iface
1166 checkModuleVersion old_mod_vers new_mod_vers >>= \ recompile ->
1167 if not recompile then
1171 -- CHECK EXPORT LIST
1172 if checkExportList maybe_old_export_vers new_export_vers then
1173 out_of_date_vers (ptext (sLit " Export list changed"))
1174 (expectJust "checkModUsage" maybe_old_export_vers)
1179 if old_rule_vers /= new_rule_vers then
1180 out_of_date_vers (ptext (sLit " Rules changed"))
1181 old_rule_vers new_rule_vers
1184 -- CHECK ITEMS ONE BY ONE
1185 checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers] >>= \ recompile ->
1187 return outOfDate -- This one failed, so just bail out now
1189 up_to_date (ptext (sLit " Great! The bits I use are up to date"))
1192 ------------------------
1193 checkModuleVersion old_mod_vers new_mod_vers
1194 | new_mod_vers == old_mod_vers
1195 = up_to_date (ptext (sLit "Module version unchanged"))
1198 = out_of_date_vers (ptext (sLit " Module version has changed"))
1199 old_mod_vers new_mod_vers
1201 ------------------------
1202 checkExportList Nothing new_vers = upToDate
1203 checkExportList (Just v) new_vers = v /= new_vers
1205 ------------------------
1206 checkEntityUsage new_vers (name,old_vers)
1207 = case new_vers name of
1209 Nothing -> -- We used it before, but it ain't there now
1210 out_of_date (sep [ptext (sLit "No longer exported:"), ppr name])
1212 Just (_, new_vers) -- It's there, but is it up to date?
1213 | new_vers == old_vers -> do traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_vers))
1215 | otherwise -> out_of_date_vers (ptext (sLit " Out of date:") <+> ppr name)
1218 up_to_date msg = traceHiDiffs msg >> return upToDate
1219 out_of_date msg = traceHiDiffs msg >> return outOfDate
1220 out_of_date_vers msg old_vers new_vers
1221 = out_of_date (hsep [msg, ppr old_vers, ptext (sLit "->"), ppr new_vers])
1223 ----------------------
1224 checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
1225 -- This helper is used in two places
1226 checkList [] = return upToDate
1227 checkList (check:checks) = do recompile <- check
1229 then return outOfDate
1230 else checkList checks
1233 %************************************************************************
1235 Converting things to their Iface equivalents
1237 %************************************************************************
1240 tyThingToIfaceDecl :: TyThing -> IfaceDecl
1241 -- Assumption: the thing is already tidied, so that locally-bound names
1242 -- (lambdas, for-alls) already have non-clashing OccNames
1243 -- Reason: Iface stuff uses OccNames, and the conversion here does
1244 -- not do tidying on the way
1245 tyThingToIfaceDecl (AnId id)
1246 = IfaceId { ifName = getOccName id,
1247 ifType = toIfaceType (idType id),
1250 info = case toIfaceIdInfo (idInfo id) of
1252 items -> HasInfo items
1254 tyThingToIfaceDecl (AClass clas)
1255 = IfaceClass { ifCtxt = toIfaceContext sc_theta,
1256 ifName = getOccName clas,
1257 ifTyVars = toIfaceTvBndrs clas_tyvars,
1258 ifFDs = map toIfaceFD clas_fds,
1259 ifATs = map (tyThingToIfaceDecl . ATyCon) clas_ats,
1260 ifSigs = map toIfaceClassOp op_stuff,
1261 ifRec = boolToRecFlag (isRecursiveTyCon tycon) }
1263 (clas_tyvars, clas_fds, sc_theta, _, clas_ats, op_stuff)
1264 = classExtraBigSig clas
1265 tycon = classTyCon clas
1267 toIfaceClassOp (sel_id, def_meth)
1268 = ASSERT(sel_tyvars == clas_tyvars)
1269 IfaceClassOp (getOccName sel_id) def_meth (toIfaceType op_ty)
1271 -- Be careful when splitting the type, because of things
1272 -- like class Foo a where
1273 -- op :: (?x :: String) => a -> a
1274 -- and class Baz a where
1275 -- op :: (Ord a) => a -> a
1276 (sel_tyvars, rho_ty) = splitForAllTys (idType sel_id)
1277 op_ty = funResultTy rho_ty
1279 toIfaceFD (tvs1, tvs2) = (map getFS tvs1, map getFS tvs2)
1281 tyThingToIfaceDecl (ATyCon tycon)
1283 = IfaceSyn { ifName = getOccName tycon,
1284 ifTyVars = toIfaceTvBndrs tyvars,
1285 ifOpenSyn = syn_isOpen,
1286 ifSynRhs = toIfaceType syn_tyki,
1287 ifFamInst = famInstToIface (tyConFamInst_maybe tycon)
1291 = IfaceData { ifName = getOccName tycon,
1292 ifTyVars = toIfaceTvBndrs tyvars,
1293 ifCtxt = toIfaceContext (tyConStupidTheta tycon),
1294 ifCons = ifaceConDecls (algTyConRhs tycon),
1295 ifRec = boolToRecFlag (isRecursiveTyCon tycon),
1296 ifGadtSyntax = isGadtSyntaxTyCon tycon,
1297 ifGeneric = tyConHasGenerics tycon,
1298 ifFamInst = famInstToIface (tyConFamInst_maybe tycon)}
1300 | isForeignTyCon tycon
1301 = IfaceForeign { ifName = getOccName tycon,
1302 ifExtName = tyConExtName tycon }
1304 | otherwise = pprPanic "toIfaceDecl" (ppr tycon)
1306 tyvars = tyConTyVars tycon
1307 (syn_isOpen, syn_tyki) = case synTyConRhs tycon of
1308 OpenSynTyCon ki _ -> (True , ki)
1309 SynonymTyCon ty -> (False, ty)
1311 ifaceConDecls (NewTyCon { data_con = con }) =
1312 IfNewTyCon (ifaceConDecl con)
1313 ifaceConDecls (DataTyCon { data_cons = cons }) =
1314 IfDataTyCon (map ifaceConDecl cons)
1315 ifaceConDecls OpenTyCon {} = IfOpenDataTyCon
1316 ifaceConDecls AbstractTyCon = IfAbstractTyCon
1317 -- The last case happens when a TyCon has been trimmed during tidying
1318 -- Furthermore, tyThingToIfaceDecl is also used
1319 -- in TcRnDriver for GHCi, when browsing a module, in which case the
1320 -- AbstractTyCon case is perfectly sensible.
1322 ifaceConDecl data_con
1323 = IfCon { ifConOcc = getOccName (dataConName data_con),
1324 ifConInfix = dataConIsInfix data_con,
1325 ifConUnivTvs = toIfaceTvBndrs (dataConUnivTyVars data_con),
1326 ifConExTvs = toIfaceTvBndrs (dataConExTyVars data_con),
1327 ifConEqSpec = to_eq_spec (dataConEqSpec data_con),
1328 ifConCtxt = toIfaceContext (dataConEqTheta data_con ++ dataConDictTheta data_con),
1329 ifConArgTys = map toIfaceType (dataConOrigArgTys data_con),
1330 ifConFields = map getOccName
1331 (dataConFieldLabels data_con),
1332 ifConStricts = dataConStrictMarks data_con }
1334 to_eq_spec spec = [(getOccName tv, toIfaceType ty) | (tv,ty) <- spec]
1336 famInstToIface Nothing = Nothing
1337 famInstToIface (Just (famTyCon, instTys)) =
1338 Just (toIfaceTyCon famTyCon, map toIfaceType instTys)
1340 tyThingToIfaceDecl (ADataCon dc)
1341 = pprPanic "toIfaceDecl" (ppr dc) -- Should be trimmed out earlier
1344 getFS x = occNameFS (getOccName x)
1346 --------------------------
1347 instanceToIfaceInst :: Instance -> IfaceInst
1348 instanceToIfaceInst ispec@(Instance { is_dfun = dfun_id, is_flag = oflag,
1349 is_cls = cls_name, is_tcs = mb_tcs })
1350 = ASSERT( cls_name == className cls )
1351 IfaceInst { ifDFun = dfun_name,
1353 ifInstCls = cls_name,
1354 ifInstTys = map do_rough mb_tcs,
1357 do_rough Nothing = Nothing
1358 do_rough (Just n) = Just (toIfaceTyCon_name n)
1360 dfun_name = idName dfun_id
1361 mod = nameModule dfun_name
1362 is_local name = nameIsLocalOrFrom mod name
1364 -- Compute orphanhood. See Note [Orphans] in IfaceSyn
1365 (_, _, cls, tys) = tcSplitDFunTy (idType dfun_id)
1366 -- Slightly awkward: we need the Class to get the fundeps
1367 (tvs, fds) = classTvsFds cls
1368 arg_names = [filterNameSet is_local (tyClsNamesOfType ty) | ty <- tys]
1369 orph | is_local cls_name = Just (nameOccName cls_name)
1370 | all isJust mb_ns = head mb_ns
1371 | otherwise = Nothing
1373 mb_ns :: [Maybe OccName] -- One for each fundep; a locally-defined name
1374 -- that is not in the "determined" arguments
1375 mb_ns | null fds = [choose_one arg_names]
1376 | otherwise = map do_one fds
1377 do_one (ltvs,rtvs) = choose_one [ns | (tv,ns) <- tvs `zip` arg_names
1378 , not (tv `elem` rtvs)]
1380 choose_one :: [NameSet] -> Maybe OccName
1381 choose_one nss = case nameSetToList (unionManyNameSets nss) of
1383 (n:ns) -> Just (nameOccName n)
1385 --------------------------
1386 famInstToIfaceFamInst :: FamInst -> IfaceFamInst
1387 famInstToIfaceFamInst fi@(FamInst { fi_tycon = tycon,
1388 fi_fam = fam, fi_tcs = mb_tcs })
1389 = IfaceFamInst { ifFamInstTyCon = toIfaceTyCon tycon
1390 , ifFamInstFam = fam
1391 , ifFamInstTys = map do_rough mb_tcs }
1393 do_rough Nothing = Nothing
1394 do_rough (Just n) = Just (toIfaceTyCon_name n)
1396 --------------------------
1397 toIfaceLetBndr id = IfLetBndr (occNameFS (getOccName id))
1398 (toIfaceType (idType id))
1401 -- Stripped-down version of tcIfaceIdInfo
1402 -- Change this if you want to export more IdInfo for
1403 -- non-top-level Ids. Don't forget to change
1404 -- CoreTidy.tidyLetBndr too!
1406 -- See Note [IdInfo on nested let-bindings] in IfaceSyn
1408 inline_prag = inlinePragInfo id_info
1409 prag_info | isAlwaysActive inline_prag = NoInfo
1410 | otherwise = HasInfo [HsInline inline_prag]
1412 --------------------------
1413 toIfaceIdInfo :: IdInfo -> [IfaceInfoItem]
1414 toIfaceIdInfo id_info
1415 = catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo,
1416 inline_hsinfo, wrkr_hsinfo, unfold_hsinfo]
1418 ------------ Arity --------------
1419 arity_info = arityInfo id_info
1420 arity_hsinfo | arity_info == 0 = Nothing
1421 | otherwise = Just (HsArity arity_info)
1423 ------------ Caf Info --------------
1424 caf_info = cafInfo id_info
1425 caf_hsinfo = case caf_info of
1426 NoCafRefs -> Just HsNoCafRefs
1429 ------------ Strictness --------------
1430 -- No point in explicitly exporting TopSig
1431 strict_hsinfo = case newStrictnessInfo id_info of
1432 Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
1435 ------------ Worker --------------
1436 work_info = workerInfo id_info
1437 has_worker = workerExists work_info
1438 wrkr_hsinfo = case work_info of
1439 HasWorker work_id wrap_arity ->
1440 Just (HsWorker ((idName work_id)) wrap_arity)
1443 ------------ Unfolding --------------
1444 -- The unfolding is redundant if there is a worker
1445 unfold_info = unfoldingInfo id_info
1446 rhs = unfoldingTemplate unfold_info
1447 no_unfolding = neverUnfold unfold_info
1448 -- The CoreTidy phase retains unfolding info iff
1449 -- we want to expose the unfolding, taking into account
1450 -- unconditional NOINLINE, etc. See TidyPgm.addExternal
1451 unfold_hsinfo | no_unfolding = Nothing
1452 | has_worker = Nothing -- Unfolding is implicit
1453 | otherwise = Just (HsUnfold (toIfaceExpr rhs))
1455 ------------ Inline prag --------------
1456 inline_prag = inlinePragInfo id_info
1457 inline_hsinfo | isAlwaysActive inline_prag = Nothing
1458 | no_unfolding && not has_worker = Nothing
1459 -- If the iface file give no unfolding info, we
1460 -- don't need to say when inlining is OK!
1461 | otherwise = Just (HsInline inline_prag)
1463 --------------------------
1464 coreRuleToIfaceRule :: Module -> CoreRule -> IfaceRule
1465 coreRuleToIfaceRule mod (BuiltinRule { ru_fn = fn})
1466 = pprTrace "toHsRule: builtin" (ppr fn) $
1469 coreRuleToIfaceRule mod (Rule { ru_name = name, ru_fn = fn,
1470 ru_act = act, ru_bndrs = bndrs,
1471 ru_args = args, ru_rhs = rhs })
1472 = IfaceRule { ifRuleName = name, ifActivation = act,
1473 ifRuleBndrs = map toIfaceBndr bndrs,
1475 ifRuleArgs = map do_arg args,
1476 ifRuleRhs = toIfaceExpr rhs,
1479 -- For type args we must remove synonyms from the outermost
1480 -- level. Reason: so that when we read it back in we'll
1481 -- construct the same ru_rough field as we have right now;
1483 do_arg (Type ty) = IfaceType (toIfaceType (deNoteType ty))
1484 do_arg arg = toIfaceExpr arg
1486 -- Compute orphanhood. See Note [Orphans] in IfaceSyn
1487 -- A rule is an orphan only if none of the variables
1488 -- mentioned on its left-hand side are locally defined
1489 lhs_names = fn : nameSetToList (exprsFreeNames args)
1490 -- No need to delete bndrs, because
1491 -- exprsFreeNames finds only External names
1493 orph = case filter (nameIsLocalOrFrom mod) lhs_names of
1494 (n:ns) -> Just (nameOccName n)
1497 bogusIfaceRule :: Name -> IfaceRule
1498 bogusIfaceRule id_name
1499 = IfaceRule { ifRuleName = fsLit "bogus", ifActivation = NeverActive,
1500 ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [],
1501 ifRuleRhs = IfaceExt id_name, ifRuleOrph = Nothing }
1503 ---------------------
1504 toIfaceExpr :: CoreExpr -> IfaceExpr
1505 toIfaceExpr (Var v) = toIfaceVar v
1506 toIfaceExpr (Lit l) = IfaceLit l
1507 toIfaceExpr (Type ty) = IfaceType (toIfaceType ty)
1508 toIfaceExpr (Lam x b) = IfaceLam (toIfaceBndr x) (toIfaceExpr b)
1509 toIfaceExpr (App f a) = toIfaceApp f [a]
1510 toIfaceExpr (Case s x ty as) = IfaceCase (toIfaceExpr s) (getFS x) (toIfaceType ty) (map toIfaceAlt as)
1511 toIfaceExpr (Let b e) = IfaceLet (toIfaceBind b) (toIfaceExpr e)
1512 toIfaceExpr (Cast e co) = IfaceCast (toIfaceExpr e) (toIfaceType co)
1513 toIfaceExpr (Note n e) = IfaceNote (toIfaceNote n) (toIfaceExpr e)
1515 ---------------------
1516 toIfaceNote (SCC cc) = IfaceSCC cc
1517 toIfaceNote InlineMe = IfaceInlineMe
1518 toIfaceNote (CoreNote s) = IfaceCoreNote s
1520 ---------------------
1521 toIfaceBind (NonRec b r) = IfaceNonRec (toIfaceLetBndr b) (toIfaceExpr r)
1522 toIfaceBind (Rec prs) = IfaceRec [(toIfaceLetBndr b, toIfaceExpr r) | (b,r) <- prs]
1524 ---------------------
1525 toIfaceAlt (c,bs,r) = (toIfaceCon c, map getFS bs, toIfaceExpr r)
1527 ---------------------
1528 toIfaceCon (DataAlt dc) | isTupleTyCon tc = IfaceTupleAlt (tupleTyConBoxity tc)
1529 | otherwise = IfaceDataAlt (getName dc)
1531 tc = dataConTyCon dc
1533 toIfaceCon (LitAlt l) = IfaceLitAlt l
1534 toIfaceCon DEFAULT = IfaceDefault
1536 ---------------------
1537 toIfaceApp (App f a) as = toIfaceApp f (a:as)
1538 toIfaceApp (Var v) as
1539 = case isDataConWorkId_maybe v of
1540 -- We convert the *worker* for tuples into IfaceTuples
1541 Just dc | isTupleTyCon tc && saturated
1542 -> IfaceTuple (tupleTyConBoxity tc) tup_args
1544 val_args = dropWhile isTypeArg as
1545 saturated = val_args `lengthIs` idArity v
1546 tup_args = map toIfaceExpr val_args
1547 tc = dataConTyCon dc
1549 other -> mkIfaceApps (toIfaceVar v) as
1551 toIfaceApp e as = mkIfaceApps (toIfaceExpr e) as
1553 mkIfaceApps f as = foldl (\f a -> IfaceApp f (toIfaceExpr a)) f as
1555 ---------------------
1556 toIfaceVar :: Id -> IfaceExpr
1558 | Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType (idType v))
1559 -- Foreign calls have special syntax
1560 | isExternalName name = IfaceExt name
1561 | Just (TickBox m ix) <- isTickBoxOp_maybe v
1563 | otherwise = IfaceLcl (getFS name)