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