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