Interface file optimisation and removal of nameParent
[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
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 FamInstEnv       ( FamInst(..) )
204 import TcRnMonad
205 import HscTypes         ( ModIface(..), ModDetails(..), 
206                           ModGuts(..), HscEnv(..), hscEPS, Dependencies(..),
207                           FixItem(..), 
208                           ModSummary(..), msHiFilePath, 
209                           mkIfaceDepCache, mkIfaceFixCache, mkIfaceVerCache,
210                           typeEnvElts,
211                           GenAvailInfo(..), availName, AvailInfo,
212                           ExternalPackageState(..),
213                           Usage(..), IsBootInterface,
214                           Deprecs(..), IfaceDeprecs, Deprecations,
215                           lookupIfaceByModule, isImplicitTyThing
216                         )
217
218
219 import DynFlags         ( GhcMode(..), DynFlags(..), DynFlag(..), dopt )
220 import Name             ( Name, nameModule, nameModule_maybe, nameOccName,
221                           isExternalName, isInternalName, isWiredInName,
222                           NamedThing(..) )
223 import NameEnv
224 import NameSet
225 import OccName          ( OccName, OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
226                           extendOccEnv_C,
227                           OccSet, emptyOccSet, elemOccSet, occSetElts, 
228                           extendOccSet, extendOccSetList, mkOccSet,
229                           isEmptyOccSet, intersectOccSet, intersectsOccSet,
230                           unionOccSets, unitOccSet,
231                           occNameFS, isTcOcc )
232 import Module
233 import BinIface         ( readBinIface, writeBinIface, v_IgnoreHiWay )
234 import Unique           ( Unique, Uniquable(..) )
235 import ErrUtils         ( dumpIfSet_dyn, showPass )
236 import Digraph          ( stronglyConnComp, SCC(..) )
237 import SrcLoc           ( SrcSpan )
238 import PackageConfig    ( PackageId )
239 import Outputable
240 import BasicTypes       hiding ( SuccessFlag(..) )
241 import UniqFM
242 import Util             hiding ( eqListBy )
243 import FiniteMap
244 import FastString
245
246 import Data.List        ( partition )
247 import DATA_IOREF       ( writeIORef )
248 import Monad            ( when )
249 import List             ( insert )
250 import Maybes           ( orElse, mapCatMaybes, isNothing, isJust, 
251                           expectJust, catMaybes, MaybeErr(..) )
252 \end{code}
253
254
255
256 %************************************************************************
257 %*                                                                      *
258 \subsection{Completing an interface}
259 %*                                                                      *
260 %************************************************************************
261
262 \begin{code}
263 mkIface :: HscEnv
264         -> Maybe ModIface       -- The old interface, if we have it
265         -> ModGuts              -- Usages, deprecations, etc
266         -> ModDetails           -- The trimmed, tidied interface
267         -> IO (ModIface,        -- The new one, complete with decls and versions
268                Bool)            -- True <=> there was an old Iface, and the new one
269                                 --          is identical, so no need to write it
270
271 mkIface hsc_env maybe_old_iface 
272         (ModGuts{     mg_module    = this_mod,
273                       mg_boot      = is_boot,
274                       mg_usages    = usages,
275                       mg_deps      = deps,
276                       mg_rdr_env   = rdr_env,
277                       mg_fix_env   = fix_env,
278                       mg_deprecs   = src_deprecs })
279         (ModDetails{  md_insts     = insts, 
280                       md_fam_insts = fam_insts,
281                       md_rules     = rules,
282                       md_types     = type_env,
283                       md_exports   = exports })
284         
285 -- NB:  notice that mkIface does not look at the bindings
286 --      only at the TypeEnv.  The previous Tidy phase has
287 --      put exactly the info into the TypeEnv that we want
288 --      to expose in the interface
289
290   = do  { eps <- hscEPS hsc_env
291         ; let   { entities = typeEnvElts type_env ;
292                   decls  = [ tyThingToIfaceDecl entity
293                            | entity <- entities,
294                              not (isImplicitTyThing entity
295                                   || isWiredInName (getName entity)) ]
296                         -- Don't put implicit Ids and class tycons in
297                         -- the interface file, Nor wired-in things; the
298                         -- compiler knows about them anyhow
299
300                 ; fixities    = [(occ,fix) | FixItem occ fix _ <- nameEnvElts fix_env]
301                 ; deprecs     = mkIfaceDeprec src_deprecs
302                 ; iface_rules = map coreRuleToIfaceRule rules
303                 ; iface_insts = map instanceToIfaceInst insts
304                 ; iface_fam_insts = map famInstToIfaceFamInst fam_insts
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= sortLe le_fam_inst iface_fam_insts,
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                 ; ext_ver_fn = mkParentVerFun hsc_env eps
334                 ; (new_iface, no_change_at_all, pp_diffs, pp_orphs) 
335                         = _scc_ "versioninfo" 
336                          addVersionInfo ext_ver_fn maybe_old_iface
337                                          intermediate_iface decls
338                 }
339
340                 -- Debug printing
341         ; when (isJust pp_orphs && dopt Opt_WarnOrphans dflags) 
342                (printDump (expectJust "mkIface" pp_orphs))
343         ; when (dopt Opt_D_dump_hi_diffs dflags) (printDump pp_diffs)
344         ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE" 
345                         (pprModIface new_iface)
346
347         ; return (new_iface, no_change_at_all) }
348   where
349      r1 `le_rule`     r2      = ifRuleName        r1 <= ifRuleName        r2
350      i1 `le_inst`     i2      = ifDFun            i1 <= ifDFun            i2
351      i1 `le_fam_inst` i2      = ifFamInstTyConOcc i1 <= ifFamInstTyConOcc i2
352
353      dflags = hsc_dflags hsc_env
354      deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
355      ifFamInstTyConOcc = nameOccName . ifaceTyConName . ifFamInstTyCon
356
357                                               
358 -----------------------------
359 writeIfaceFile :: DynFlags -> ModLocation -> ModIface -> IO ()
360 writeIfaceFile dflags location new_iface
361     = do createDirectoryHierarchy (directoryOf hi_file_path)
362          writeBinIface dflags hi_file_path new_iface
363     where hi_file_path = ml_hi_file location
364
365
366 -- -----------------------------------------------------------------------------
367 -- Look up parents and versions of Names
368
369 -- This is like a global version of the mi_ver_fn field in each ModIface.
370 -- Given a Name, it finds the ModIface, and then uses mi_ver_fn to get
371 -- the parent and version info.
372
373 mkParentVerFun
374         :: HscEnv                       -- needed to look up versions
375         -> ExternalPackageState         -- ditto
376         -> (Name -> (OccName,Version))
377 mkParentVerFun hsc_env eps
378   = \name -> 
379       let 
380         mod = nameModule name
381         occ = nameOccName name
382         iface = lookupIfaceByModule (hsc_dflags hsc_env) hpt pit mod `orElse` 
383                    pprPanic "lookupVers2" (ppr mod <+> ppr occ)
384       in  
385         mi_ver_fn iface occ `orElse` 
386                  pprPanic "lookupVers1" (ppr mod <+> ppr occ)
387   where
388       hpt = hsc_HPT hsc_env
389       pit = eps_PIT eps
390
391 -----------------------------------------------------------------------------
392 -- Compute version numbers for local decls
393
394 addVersionInfo
395         :: (Name -> (OccName,Version))  -- lookup parents and versions of names
396         -> Maybe ModIface  -- The old interface, read from M.hi
397         -> ModIface        -- The new interface (lacking decls)
398         -> [IfaceDecl]     -- The new decls
399         -> (ModIface,   -- Updated interface
400             Bool,          -- True <=> no changes at all; no need to write Iface
401             SDoc,          -- Differences
402             Maybe SDoc) -- Warnings about orphans
403
404 addVersionInfo ver_fn Nothing new_iface new_decls
405 -- No old interface, so definitely write a new one!
406   = (new_iface { mi_orphan = anyNothing ifInstOrph (mi_insts new_iface)
407                                 || anyNothing ifRuleOrph (mi_rules new_iface),
408                 mi_decls  = [(initialVersion, decl) | decl <- new_decls],
409                 mi_ver_fn = mkIfaceVerCache (zip (repeat initialVersion) new_decls)},
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_decls     = decls_w_vers,
438                 mi_ver_fn    = mkIfaceVerCache decls_w_vers }
439
440     decls_w_vers = [(add_vers decl, decl) | decl <- new_decls]
441
442     -------------------
443     (old_non_orph_insts, old_orph_insts) = 
444         mkOrphMap ifInstOrph (mi_insts old_iface)
445     (new_non_orph_insts, new_orph_insts) = 
446         mkOrphMap ifInstOrph (mi_insts new_iface)
447     same_insts occ = eqMaybeBy  (eqListBy eqIfInst) 
448                                 (lookupOccEnv old_non_orph_insts occ)
449                                 (lookupOccEnv new_non_orph_insts occ)
450   
451     (old_non_orph_rules, old_orph_rules) = 
452         mkOrphMap ifRuleOrph (mi_rules old_iface)
453     (new_non_orph_rules, new_orph_rules) = 
454         mkOrphMap ifRuleOrph (mi_rules new_iface)
455     same_rules occ = eqMaybeBy  (eqListBy eqIfRule)
456                                 (lookupOccEnv old_non_orph_rules occ)
457                                 (lookupOccEnv new_non_orph_rules occ)
458     -------------------
459     -- Computing what changed
460     no_output_change = no_decl_change   && no_rule_change && 
461                        no_export_change && no_deprec_change
462     no_export_change = mi_exports new_iface == mi_exports old_iface
463                                 -- Kept sorted
464     no_decl_change   = isEmptyOccSet changed_occs
465     no_rule_change   = not (changedWrtNames changed_occs (eqListBy eqIfRule old_orph_rules new_orph_rules)
466                          || changedWrtNames changed_occs (eqListBy eqIfInst old_orph_insts new_orph_insts))
467     no_deprec_change = mi_deprecs new_iface == mi_deprecs old_iface
468
469         -- If the usages havn't changed either, we don't need to write the interface file
470     no_other_changes = mi_usages new_iface == mi_usages old_iface && 
471                        mi_deps new_iface == mi_deps old_iface
472     no_change_at_all = no_output_change && no_other_changes
473  
474     pp_diffs = vcat [pp_change no_export_change "Export list" 
475                         (ppr old_exp_vers <+> arrow <+> ppr (mi_exp_vers final_iface)),
476                      pp_change no_rule_change "Rules"
477                         (ppr old_rule_vers <+> arrow <+> ppr (mi_rule_vers final_iface)),
478                      pp_change no_deprec_change "Deprecations" empty,
479                      pp_change no_other_changes  "Usages" empty,
480                      pp_decl_diffs]
481     pp_change True  what info = empty
482     pp_change False what info = text what <+> ptext SLIT("changed") <+> info
483
484     -------------------
485     old_decl_env = mkOccEnv [(ifName decl, decl) | (_,decl) <- old_decls]
486     same_fixity n = bool (old_fixities n == new_fixities n)
487
488     -------------------
489     -- Adding version info
490     new_version = bumpVersion old_mod_vers
491                         -- Start from the old module version, not from
492                         -- zero so that if you remove f, and then add
493                         -- it again, you don't thereby reduce f's
494                         -- version number
495
496     add_vers decl | occ `elemOccSet` changed_occs = new_version
497                   | otherwise = snd (expectJust "add_vers" (old_decl_vers occ))
498                                 -- If it's unchanged, there jolly well 
499                   where         -- should be an old version number
500                     occ = ifName decl
501
502     -------------------
503     -- Deciding which declarations have changed
504             
505     -- For each local decl, the IfaceEq gives the list of things that
506     -- must be unchanged for the declaration as a whole to be unchanged.
507     eq_info :: [(OccName, IfaceEq)]
508     eq_info = map check_eq new_decls
509     check_eq new_decl
510          | Just old_decl <- lookupOccEnv old_decl_env occ 
511          = (occ, new_decl `eqIfDecl` old_decl &&& eq_indirects new_decl)
512          | otherwise {- No corresponding old decl -}      
513          = (occ, NotEqual)      
514         where
515           occ = ifName new_decl
516
517     eq_indirects :: IfaceDecl -> IfaceEq
518                 -- When seeing if two decls are the same, remember to
519                 -- check whether any relevant fixity or rules have changed
520     eq_indirects (IfaceId {ifName = occ}) = eq_ind_occ occ
521     eq_indirects (IfaceClass {ifName = cls_occ, ifSigs = sigs})
522         = same_insts cls_occ &&& 
523           eq_ind_occs [op | IfaceClassOp op _ _ <- sigs] 
524     eq_indirects (IfaceData {ifName = tc_occ, ifCons = cons})
525         = same_insts tc_occ &&& same_fixity tc_occ &&&  -- The TyCon can have a fixity too
526           eq_ind_occs (map ifConOcc (visibleIfConDecls cons))
527     eq_indirects other = Equal  -- Synonyms and foreign declarations
528
529     eq_ind_occ :: OccName -> IfaceEq    -- For class ops and Ids; check fixity and rules
530     eq_ind_occ occ = same_fixity occ &&& same_rules occ
531     eq_ind_occs = foldr ((&&&) . eq_ind_occ) Equal 
532      
533     -- The Occs of declarations that changed.
534     changed_occs :: OccSet
535     changed_occs = computeChangedOccs ver_fn (mi_module new_iface)
536                          (mi_usages old_iface) eq_info
537
538     -------------------
539     -- Diffs
540     pp_decl_diffs :: SDoc       -- Nothing => no changes
541     pp_decl_diffs 
542         | isEmptyOccSet changed_occs = empty
543         | otherwise 
544         = vcat [ptext SLIT("Changed occs:") <+> ppr (occSetElts changed_occs),
545                 ptext SLIT("Version change for these decls:"),
546                 nest 2 (vcat (map show_change new_decls))]
547
548     eq_env = mkOccEnv eq_info
549     show_change new_decl
550         | not (occ `elemOccSet` changed_occs) = empty
551         | otherwise
552         = vcat [ppr occ <+> ppr (old_decl_vers occ) <+> arrow <+> ppr new_version, 
553                 nest 2 why]
554         where
555           occ = ifName new_decl
556           why = case lookupOccEnv eq_env occ of
557                     Just (EqBut names) -> sep [ppr occ <> colon, ptext SLIT("Free vars (only) changed:"),
558                                               nest 2 (braces (fsep (map ppr (occSetElts 
559                                                 (occs `intersectOccSet` changed_occs)))))]
560                            where occs = mkOccSet (map nameOccName (nameSetToList names))
561                     Just NotEqual  
562                         | Just old_decl <- lookupOccEnv old_decl_env occ 
563                         -> vcat [ptext SLIT("Old:") <+> ppr old_decl,
564                          ptext SLIT("New:") <+> ppr new_decl]
565                         | otherwise 
566                         -> ppr occ <+> ptext SLIT("only in new interface")
567                     other -> pprPanic "MkIface.show_change" (ppr occ)
568         
569     pp_orphs = pprOrphans new_orph_insts new_orph_rules
570
571
572 pprOrphans insts rules
573   | null insts && null rules = Nothing
574   | otherwise
575   = Just $ vcat [
576         if null insts then empty else
577              hang (ptext SLIT("Warning: orphan instances:"))
578                 2 (vcat (map ppr insts)),
579         if null rules then empty else
580              hang (ptext SLIT("Warning: orphan rules:"))
581                 2 (vcat (map ppr rules))
582     ]
583
584 computeChangedOccs
585         :: (Name -> (OccName,Version))     -- get parents and versions
586         -> Module                       -- This module
587         -> [Usage]                      -- Usages from old iface
588         -> [(OccName, IfaceEq)]         -- decl names, equality conditions
589         -> OccSet                       -- set of things that have changed
590 computeChangedOccs ver_fn this_module old_usages eq_info
591   = foldl add_changes emptyOccSet (stronglyConnComp edges)
592   where
593
594     -- return True if an external name has changed
595     name_changed :: Name -> Bool
596     name_changed nm
597         | Just ents <- lookupUFM usg_modmap (moduleName mod) 
598         = case lookupUFM ents parent_occ of
599                 Nothing -> pprPanic "computeChangedOccs" (ppr nm)
600                 Just v  -> v < new_version
601         | otherwise = False -- must be in another package
602       where
603          mod = nameModule nm
604          (parent_occ, new_version) = ver_fn nm
605
606     -- Turn the usages from the old ModIface into a mapping
607     usg_modmap = listToUFM [ (usg_mod usg, listToUFM (usg_entities usg))
608                            | usg <- old_usages ]
609
610     get_local_eq_info :: GenIfaceEq NameSet -> GenIfaceEq OccSet
611     get_local_eq_info Equal = Equal
612     get_local_eq_info NotEqual = NotEqual
613     get_local_eq_info (EqBut ns) = foldNameSet f Equal ns
614         where f name eq | nameModule name == this_module =         
615                           EqBut (unitOccSet (nameOccName name)) `and_occifeq` eq
616                         | name_changed name = NotEqual
617                         | otherwise = eq
618
619     local_eq_infos = mapSnd get_local_eq_info eq_info
620
621     edges :: [((OccName, OccIfaceEq), Unique, [Unique])]
622     edges = [ (node, getUnique occ, map getUnique occs)
623             | node@(occ, iface_eq) <- local_eq_infos
624             , let occs = case iface_eq of
625                            EqBut occ_set -> occSetElts occ_set
626                            other -> [] ]
627
628     -- Changes in declarations
629     add_changes :: OccSet -> SCC (OccName, OccIfaceEq) -> OccSet
630     add_changes so_far (AcyclicSCC (occ, iface_eq)) 
631         | changedWrt so_far iface_eq -- This one has changed
632         = extendOccSet so_far occ
633     add_changes so_far (CyclicSCC pairs)
634         | changedWrt so_far (foldr1 and_occifeq iface_eqs)
635                 -- One of this group has changed
636         = extendOccSetList so_far occs
637         where (occs, iface_eqs) = unzip pairs
638     add_changes so_far other = so_far
639
640 type OccIfaceEq = GenIfaceEq OccSet
641
642 changedWrt :: OccSet -> OccIfaceEq -> Bool
643 changedWrt so_far Equal        = False
644 changedWrt so_far NotEqual     = True
645 changedWrt so_far (EqBut kids) = so_far `intersectsOccSet` kids
646
647 changedWrtNames :: OccSet -> IfaceEq -> Bool
648 changedWrtNames so_far Equal        = False
649 changedWrtNames so_far NotEqual     = True
650 changedWrtNames so_far (EqBut kids) = 
651   so_far `intersectsOccSet` mkOccSet (map nameOccName (nameSetToList kids))
652
653 and_occifeq :: OccIfaceEq -> OccIfaceEq -> OccIfaceEq
654 Equal       `and_occifeq` x         = x
655 NotEqual    `and_occifeq` x         = NotEqual
656 EqBut nms   `and_occifeq` Equal       = EqBut nms
657 EqBut nms   `and_occifeq` NotEqual    = NotEqual
658 EqBut nms1  `and_occifeq` EqBut nms2  = EqBut (nms1 `unionOccSets` nms2)
659
660 ----------------------
661 -- mkOrphMap partitions instance decls or rules into
662 --      (a) an OccEnv for ones that are not orphans, 
663 --          mapping the local OccName to a list of its decls
664 --      (b) a list of orphan decls
665 mkOrphMap :: (decl -> Maybe OccName)    -- (Just occ) for a non-orphan decl, keyed by occ
666                                         -- Nothing for an orphan decl
667           -> [decl]                     -- Sorted into canonical order
668           -> (OccEnv [decl],            -- Non-orphan decls associated with their key;
669                                         --      each sublist in canonical order
670               [decl])                   -- Orphan decls; in canonical order
671 mkOrphMap get_key decls
672   = foldl go (emptyOccEnv, []) decls
673   where
674     go (non_orphs, orphs) d
675         | Just occ <- get_key d
676         = (extendOccEnv_C (\ ds _ -> d:ds) non_orphs occ [d], orphs)
677         | otherwise = (non_orphs, d:orphs)
678
679 anyNothing :: (a -> Maybe b) -> [a] -> Bool
680 anyNothing p []     = False
681 anyNothing p (x:xs) = isNothing (p x) || anyNothing p xs
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 module (need to recompile if its
747     --          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       = Nothing                 -- Record no usage info
755     
756       | otherwise       
757       = Just (Usage { usg_name     = mod_name,
758                       usg_mod      = mod_vers,
759                       usg_exports  = export_vers,
760                       usg_entities = fmToList ent_vers,
761                       usg_rules    = rules_vers })
762       where
763         maybe_iface  = lookupIfaceByModule dflags hpt pit mod
764                 -- In one-shot mode, the interfaces for home-package 
765                 -- modules accumulate in the PIT not HPT.  Sigh.
766
767         mod = mkModule (thisPackage dflags) mod_name
768
769         Just iface   = maybe_iface
770         orphan_mod   = mi_orphan    iface
771         version_env  = mi_ver_fn    iface
772         mod_vers     = mi_mod_vers  iface
773         rules_vers   = mi_rule_vers iface
774         export_vers | depend_on_exports mod = Just (mi_exp_vers iface)
775                     | otherwise             = Nothing
776     
777         used_occs = lookupModuleEnv ent_map mod `orElse` []
778
779         -- Making a FiniteMap here ensures that (a) we remove duplicates
780         -- when we have usages on several subordinates of a single parent,
781         -- and (b) that the usages emerge in a canonical order, which
782         -- is why we use FiniteMap rather than OccEnv: FiniteMap works
783         -- using Ord on the OccNames, which is a lexicographic ordering.
784         ent_vers :: FiniteMap OccName Version
785         ent_vers = listToFM (map lookup_occ used_occs)
786         
787         lookup_occ occ = 
788             case version_env occ of
789                 Nothing -> pprTrace "hmm, strange" (ppr mod <+> ppr occ) $
790                            (occ, initialVersion) -- does this ever happen?
791                 Just (parent, version) -> (parent, version)
792 \end{code}
793
794 \begin{code}
795 mkIfaceExports :: [AvailInfo]
796                -> [(Module, [GenAvailInfo OccName])]
797   -- Group by module and sort by occurrence
798   -- This keeps the list in canonical order
799 mkIfaceExports exports
800   = [ (mod, eltsFM avails)
801     | (mod, avails) <- fmToList groupFM
802     ]
803   where
804         -- Deliberately use FiniteMap rather than UniqFM so we
805         -- get a canonical ordering
806     groupFM :: ModuleEnv (FiniteMap FastString (GenAvailInfo OccName))
807     groupFM = foldl add emptyModuleEnv exports
808
809     add env avail
810       = extendModuleEnv_C add_avail env mod (unitFM avail_fs avail_occ)
811       where
812         avail_occ = availToOccs avail
813         mod  = nameModule (availName avail)
814         avail_fs = occNameFS (availName avail_occ)
815         add_avail avail_fm _ = addToFM avail_fm avail_fs avail_occ
816
817     availToOccs (Avail n) = Avail (nameOccName n)
818     availToOccs (AvailTC tc ns) = AvailTC (nameOccName tc) (map nameOccName ns)
819 \end{code}
820
821
822 %************************************************************************
823 %*                                                                      *
824         Load the old interface file for this module (unless
825         we have it aleady), and check whether it is up to date
826         
827 %*                                                                      *
828 %************************************************************************
829
830 \begin{code}
831 checkOldIface :: HscEnv
832               -> ModSummary
833               -> Bool                   -- Source unchanged
834               -> Maybe ModIface         -- Old interface from compilation manager, if any
835               -> IO (RecompileRequired, Maybe ModIface)
836
837 checkOldIface hsc_env mod_summary source_unchanged maybe_iface
838   = do  { showPass (hsc_dflags hsc_env) 
839                    ("Checking old interface for " ++ 
840                         showSDoc (ppr (ms_mod mod_summary))) ;
841
842         ; initIfaceCheck hsc_env $
843           check_old_iface hsc_env mod_summary source_unchanged maybe_iface
844      }
845
846 check_old_iface hsc_env mod_summary source_unchanged maybe_iface
847  =  do  -- CHECK WHETHER THE SOURCE HAS CHANGED
848     { ifM (not source_unchanged)
849            (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
850
851      -- If the source has changed and we're in interactive mode, avoid reading
852      -- an interface; just return the one we might have been supplied with.
853     ; ghc_mode <- getGhcMode
854     ; if (ghc_mode == Interactive || ghc_mode == JustTypecheck) 
855          && not source_unchanged then
856          return (outOfDate, maybe_iface)
857       else
858       case maybe_iface of {
859         Just old_iface -> do -- Use the one we already have
860           { traceIf (text "We already have the old interface for" <+> ppr (ms_mod mod_summary))
861           ; recomp <- checkVersions hsc_env source_unchanged old_iface
862           ; return (recomp, Just old_iface) }
863
864       ; Nothing -> do
865
866         -- Try and read the old interface for the current module
867         -- from the .hi file left from the last time we compiled it
868     { let iface_path = msHiFilePath mod_summary
869     ; read_result <- readIface (ms_mod mod_summary) iface_path False
870     ; case read_result of {
871          Failed err -> do       -- Old interface file not found, or garbled; give up
872                 { traceIf (text "FYI: cannot read old interface file:"
873                                  $$ nest 4 err)
874                 ; return (outOfDate, Nothing) }
875
876       ;  Succeeded iface -> do
877
878         -- We have got the old iface; check its versions
879     { traceIf (text "Read the interface file" <+> text iface_path)
880     ; recomp <- checkVersions hsc_env source_unchanged iface
881     ; returnM (recomp, Just iface)
882     }}}}}
883 \end{code}
884
885 @recompileRequired@ is called from the HscMain.   It checks whether
886 a recompilation is required.  It needs access to the persistent state,
887 finder, etc, because it may have to load lots of interface files to
888 check their versions.
889
890 \begin{code}
891 type RecompileRequired = Bool
892 upToDate  = False       -- Recompile not required
893 outOfDate = True        -- Recompile required
894
895 checkVersions :: HscEnv
896               -> Bool           -- True <=> source unchanged
897               -> ModIface       -- Old interface
898               -> IfG RecompileRequired
899 checkVersions hsc_env source_unchanged iface
900   | not source_unchanged
901   = returnM outOfDate
902   | otherwise
903   = do  { traceHiDiffs (text "Considering whether compilation is required for" <+> 
904                         ppr (mi_module iface) <> colon)
905
906         -- Source code unchanged and no errors yet... carry on 
907
908         -- First put the dependent-module info, read from the old interface, into the envt, 
909         -- so that when we look for interfaces we look for the right one (.hi or .hi-boot)
910         -- 
911         -- It's just temporary because either the usage check will succeed 
912         -- (in which case we are done with this module) or it'll fail (in which
913         -- case we'll compile the module from scratch anyhow).
914         --      
915         -- We do this regardless of compilation mode, although in --make mode
916         -- all the dependent modules should be in the HPT already, so it's
917         -- quite redundant
918         ; updateEps_ $ \eps  -> eps { eps_is_boot = mod_deps }
919
920         ; let this_pkg = thisPackage (hsc_dflags hsc_env)
921         ; checkList [checkModUsage this_pkg u | u <- mi_usages iface]
922     }
923   where
924         -- This is a bit of a hack really
925     mod_deps :: ModuleNameEnv (ModuleName, IsBootInterface)
926     mod_deps = mkModDeps (dep_mods (mi_deps iface))
927
928 checkModUsage :: PackageId ->Usage -> IfG RecompileRequired
929 -- Given the usage information extracted from the old
930 -- M.hi file for the module being compiled, figure out
931 -- whether M needs to be recompiled.
932
933 checkModUsage this_pkg (Usage { usg_name = mod_name, usg_mod = old_mod_vers,
934                                 usg_rules = old_rule_vers,
935                                 usg_exports = maybe_old_export_vers, 
936                                 usg_entities = old_decl_vers })
937   =     -- Load the imported interface is possible
938     let
939         doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
940     in
941     traceHiDiffs (text "Checking usages for module" <+> ppr mod_name) `thenM_`
942
943     let
944         mod = mkModule this_pkg mod_name
945     in
946     loadInterface doc_str mod ImportBySystem            `thenM` \ mb_iface ->
947         -- Load the interface, but don't complain on failure;
948         -- Instead, get an Either back which we can test
949
950     case mb_iface of {
951         Failed exn ->  (out_of_date (sep [ptext SLIT("Can't find version number for module"), 
952                                        ppr mod_name]));
953                 -- Couldn't find or parse a module mentioned in the
954                 -- old interface file.  Don't complain -- it might just be that
955                 -- the current module doesn't need that import and it's been deleted
956
957         Succeeded iface -> 
958     let
959         new_mod_vers    = mi_mod_vers  iface
960         new_decl_vers   = mi_ver_fn    iface
961         new_export_vers = mi_exp_vers  iface
962         new_rule_vers   = mi_rule_vers iface
963     in
964         -- CHECK MODULE
965     checkModuleVersion old_mod_vers new_mod_vers        `thenM` \ recompile ->
966     if not recompile then
967         returnM upToDate
968     else
969                                  
970         -- CHECK EXPORT LIST
971     if checkExportList maybe_old_export_vers new_export_vers then
972         out_of_date_vers (ptext SLIT("  Export list changed"))
973                          (expectJust "checkModUsage" maybe_old_export_vers) 
974                          new_export_vers
975     else
976
977         -- CHECK RULES
978     if old_rule_vers /= new_rule_vers then
979         out_of_date_vers (ptext SLIT("  Rules changed")) 
980                          old_rule_vers new_rule_vers
981     else
982
983         -- CHECK ITEMS ONE BY ONE
984     checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers]   `thenM` \ recompile ->
985     if recompile then
986         returnM outOfDate       -- This one failed, so just bail out now
987     else
988         up_to_date (ptext SLIT("  Great!  The bits I use are up to date"))
989     }
990
991 ------------------------
992 checkModuleVersion old_mod_vers new_mod_vers
993   | new_mod_vers == old_mod_vers
994   = up_to_date (ptext SLIT("Module version unchanged"))
995
996   | otherwise
997   = out_of_date_vers (ptext SLIT("  Module version has changed"))
998                      old_mod_vers new_mod_vers
999
1000 ------------------------
1001 checkExportList Nothing  new_vers = upToDate
1002 checkExportList (Just v) new_vers = v /= new_vers
1003
1004 ------------------------
1005 checkEntityUsage new_vers (name,old_vers)
1006   = case new_vers name of
1007
1008         Nothing       ->        -- We used it before, but it ain't there now
1009                           out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
1010
1011         Just (_, new_vers)      -- It's there, but is it up to date?
1012           | new_vers == old_vers -> traceHiDiffs (text "  Up to date" <+> ppr name <+> parens (ppr new_vers)) `thenM_`
1013                                     returnM upToDate
1014           | otherwise            -> out_of_date_vers (ptext SLIT("  Out of date:") <+> ppr name)
1015                                                      old_vers new_vers
1016
1017 up_to_date  msg = traceHiDiffs msg `thenM_` returnM upToDate
1018 out_of_date msg = traceHiDiffs msg `thenM_` returnM outOfDate
1019 out_of_date_vers msg old_vers new_vers 
1020   = out_of_date (hsep [msg, ppr old_vers, ptext SLIT("->"), ppr new_vers])
1021
1022 ----------------------
1023 checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
1024 -- This helper is used in two places
1025 checkList []             = returnM upToDate
1026 checkList (check:checks) = check        `thenM` \ recompile ->
1027                            if recompile then 
1028                                 returnM outOfDate
1029                            else
1030                                 checkList checks
1031 \end{code}
1032
1033 %************************************************************************
1034 %*                                                                      *
1035                 Converting things to their Iface equivalents
1036 %*                                                                      *
1037 %************************************************************************
1038
1039 \begin{code}
1040 tyThingToIfaceDecl :: TyThing -> IfaceDecl
1041 -- Assumption: the thing is already tidied, so that locally-bound names
1042 --             (lambdas, for-alls) already have non-clashing OccNames
1043 -- Reason: Iface stuff uses OccNames, and the conversion here does
1044 --         not do tidying on the way
1045 tyThingToIfaceDecl (AnId id)
1046   = IfaceId { ifName   = getOccName id,
1047               ifType   = toIfaceType (idType id),
1048               ifIdInfo = info }
1049   where
1050     info = case toIfaceIdInfo (idInfo id) of
1051                 []    -> NoInfo
1052                 items -> HasInfo items
1053
1054 tyThingToIfaceDecl (AClass clas)
1055   = IfaceClass { ifCtxt   = toIfaceContext sc_theta,
1056                  ifName   = getOccName clas,
1057                  ifTyVars = toIfaceTvBndrs clas_tyvars,
1058                  ifFDs    = map toIfaceFD clas_fds,
1059                  ifATs    = map (tyThingToIfaceDecl . ATyCon) clas_ats,
1060                  ifSigs   = map toIfaceClassOp op_stuff,
1061                  ifRec    = boolToRecFlag (isRecursiveTyCon tycon) }
1062   where
1063     (clas_tyvars, clas_fds, sc_theta, _, clas_ats, op_stuff) 
1064       = classExtraBigSig clas
1065     tycon = classTyCon clas
1066
1067     toIfaceClassOp (sel_id, def_meth)
1068         = ASSERT(sel_tyvars == clas_tyvars)
1069           IfaceClassOp (getOccName sel_id) def_meth (toIfaceType op_ty)
1070         where
1071                 -- Be careful when splitting the type, because of things
1072                 -- like         class Foo a where
1073                 --                op :: (?x :: String) => a -> a
1074                 -- and          class Baz a where
1075                 --                op :: (Ord a) => a -> a
1076           (sel_tyvars, rho_ty) = splitForAllTys (idType sel_id)
1077           op_ty                = funResultTy rho_ty
1078
1079     toIfaceFD (tvs1, tvs2) = (map getFS tvs1, map getFS tvs2)
1080
1081 tyThingToIfaceDecl (ATyCon tycon)
1082   | isSynTyCon tycon
1083   = IfaceSyn {  ifName   = getOccName tycon,
1084                 ifTyVars = toIfaceTvBndrs tyvars,
1085                 ifOpenSyn = syn_isOpen,
1086                 ifSynRhs  = toIfaceType syn_tyki }
1087
1088   | isAlgTyCon tycon
1089   = IfaceData { ifName    = getOccName tycon,
1090                 ifTyVars  = toIfaceTvBndrs tyvars,
1091                 ifCtxt    = toIfaceContext (tyConStupidTheta tycon),
1092                 ifCons    = ifaceConDecls (algTyConRhs tycon),
1093                 ifRec     = boolToRecFlag (isRecursiveTyCon tycon),
1094                 ifGadtSyntax = isGadtSyntaxTyCon tycon,
1095                 ifGeneric = tyConHasGenerics tycon,
1096                 ifFamInst = famInstToIface (tyConFamInst_maybe tycon)}
1097
1098   | isForeignTyCon tycon
1099   = IfaceForeign { ifName    = getOccName tycon,
1100                    ifExtName = tyConExtName tycon }
1101
1102   | isPrimTyCon tycon || isFunTyCon tycon
1103         -- Needed in GHCi for ':info Int#', for example
1104   = IfaceData { ifName    = getOccName tycon,
1105                 ifTyVars  = toIfaceTvBndrs (take (tyConArity tycon) alphaTyVars),
1106                 ifCtxt    = [],
1107                 ifCons    = IfAbstractTyCon,
1108                 ifGadtSyntax = False,
1109                 ifGeneric = False,
1110                 ifRec     = NonRecursive,
1111                 ifFamInst = Nothing }
1112
1113   | otherwise = pprPanic "toIfaceDecl" (ppr tycon)
1114   where
1115     tyvars = tyConTyVars tycon
1116     (syn_isOpen, syn_tyki) = case synTyConRhs tycon of
1117                                OpenSynTyCon ki -> (True , ki)
1118                                SynonymTyCon ty -> (False, ty)
1119
1120     ifaceConDecls (NewTyCon { data_con = con })    = 
1121       IfNewTyCon  (ifaceConDecl con)
1122     ifaceConDecls (DataTyCon { data_cons = cons }) = 
1123       IfDataTyCon (map ifaceConDecl cons)
1124     ifaceConDecls OpenDataTyCon                    = IfOpenDataTyCon
1125     ifaceConDecls OpenNewTyCon                     = IfOpenNewTyCon
1126     ifaceConDecls AbstractTyCon                    = IfAbstractTyCon
1127         -- The last case happens when a TyCon has been trimmed during tidying
1128         -- Furthermore, tyThingToIfaceDecl is also used
1129         -- in TcRnDriver for GHCi, when browsing a module, in which case the
1130         -- AbstractTyCon case is perfectly sensible.
1131
1132     ifaceConDecl data_con 
1133         = IfCon   { ifConOcc     = getOccName (dataConName data_con),
1134                     ifConInfix   = dataConIsInfix data_con,
1135                     ifConUnivTvs = toIfaceTvBndrs (dataConUnivTyVars data_con),
1136                     ifConExTvs   = toIfaceTvBndrs (dataConExTyVars data_con),
1137                     ifConEqSpec  = to_eq_spec (dataConEqSpec data_con),
1138                     ifConCtxt    = toIfaceContext (dataConTheta data_con),
1139                     ifConArgTys  = map toIfaceType (dataConOrigArgTys data_con),
1140                     ifConFields  = map getOccName 
1141                                        (dataConFieldLabels data_con),
1142                     ifConStricts = dataConStrictMarks data_con }
1143
1144     to_eq_spec spec = [(getOccName tv, toIfaceType ty) | (tv,ty) <- spec]
1145
1146     famInstToIface Nothing                    = Nothing
1147     famInstToIface (Just (famTyCon, instTys)) = 
1148       Just (toIfaceTyCon famTyCon, map toIfaceType instTys)
1149
1150 tyThingToIfaceDecl (ADataCon dc)
1151  = pprPanic "toIfaceDecl" (ppr dc)      -- Should be trimmed out earlier
1152
1153
1154 getFS x = occNameFS (getOccName x)
1155
1156 --------------------------
1157 instanceToIfaceInst :: Instance -> IfaceInst
1158 instanceToIfaceInst ispec@(Instance { is_dfun = dfun_id, is_flag = oflag,
1159                                       is_cls = cls, is_tcs = mb_tcs, 
1160                                       is_orph = orph })
1161   = IfaceInst { ifDFun    = getName dfun_id,
1162                 ifOFlag   = oflag,
1163                 ifInstCls = cls,
1164                 ifInstTys = map do_rough mb_tcs,
1165                 ifInstOrph = orph }
1166   where
1167     do_rough Nothing  = Nothing
1168     do_rough (Just n) = Just (toIfaceTyCon_name n)
1169
1170 --------------------------
1171 famInstToIfaceFamInst :: FamInst -> IfaceFamInst
1172 famInstToIfaceFamInst fi@(FamInst { fi_tycon = tycon,
1173                                             fi_fam = fam, fi_tcs = mb_tcs })
1174   = IfaceFamInst { ifFamInstTyCon  = toIfaceTyCon tycon
1175                  , ifFamInstFam    = fam
1176                  , ifFamInstTys    = map do_rough mb_tcs }
1177   where
1178     do_rough Nothing  = Nothing
1179     do_rough (Just n) = Just (toIfaceTyCon_name n)
1180
1181 --------------------------
1182 toIfaceIdInfo :: IdInfo -> [IfaceInfoItem]
1183 toIfaceIdInfo id_info
1184   = catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo, 
1185                inline_hsinfo, wrkr_hsinfo,  unfold_hsinfo] 
1186   where
1187     ------------  Arity  --------------
1188     arity_info = arityInfo id_info
1189     arity_hsinfo | arity_info == 0 = Nothing
1190                  | otherwise       = Just (HsArity arity_info)
1191
1192     ------------ Caf Info --------------
1193     caf_info   = cafInfo id_info
1194     caf_hsinfo = case caf_info of
1195                    NoCafRefs -> Just HsNoCafRefs
1196                    _other    -> Nothing
1197
1198     ------------  Strictness  --------------
1199         -- No point in explicitly exporting TopSig
1200     strict_hsinfo = case newStrictnessInfo id_info of
1201                         Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
1202                         _other                        -> Nothing
1203
1204     ------------  Worker  --------------
1205     work_info   = workerInfo id_info
1206     has_worker  = case work_info of { HasWorker _ _ -> True; other -> False }
1207     wrkr_hsinfo = case work_info of
1208                     HasWorker work_id wrap_arity -> 
1209                         Just (HsWorker ((idName work_id)) wrap_arity)
1210                     NoWorker -> Nothing
1211
1212     ------------  Unfolding  --------------
1213     -- The unfolding is redundant if there is a worker
1214     unfold_info  = unfoldingInfo id_info
1215     rhs          = unfoldingTemplate unfold_info
1216     no_unfolding = neverUnfold unfold_info
1217                         -- The CoreTidy phase retains unfolding info iff
1218                         -- we want to expose the unfolding, taking into account
1219                         -- unconditional NOINLINE, etc.  See TidyPgm.addExternal
1220     unfold_hsinfo | no_unfolding = Nothing                      
1221                   | has_worker   = Nothing      -- Unfolding is implicit
1222                   | otherwise    = Just (HsUnfold (toIfaceExpr rhs))
1223                                         
1224     ------------  Inline prag  --------------
1225     inline_prag = inlinePragInfo id_info
1226     inline_hsinfo | isAlwaysActive inline_prag     = Nothing
1227                   | no_unfolding && not has_worker = Nothing
1228                         -- If the iface file give no unfolding info, we 
1229                         -- don't need to say when inlining is OK!
1230                   | otherwise                      = Just (HsInline inline_prag)
1231
1232 --------------------------
1233 coreRuleToIfaceRule :: CoreRule -> IfaceRule
1234 coreRuleToIfaceRule (BuiltinRule { ru_fn = fn})
1235   = pprTrace "toHsRule: builtin" (ppr fn) $
1236     bogusIfaceRule fn
1237
1238 coreRuleToIfaceRule (Rule { ru_name = name, ru_fn = fn, 
1239                             ru_act = act, ru_bndrs = bndrs,
1240                             ru_args = args, ru_rhs = rhs, ru_orph = orph })
1241   = IfaceRule { ifRuleName  = name, ifActivation = act, 
1242                 ifRuleBndrs = map toIfaceBndr bndrs,
1243                 ifRuleHead  = fn, 
1244                 ifRuleArgs  = map do_arg args,
1245                 ifRuleRhs   = toIfaceExpr rhs,
1246                 ifRuleOrph  = orph }
1247   where
1248         -- For type args we must remove synonyms from the outermost
1249         -- level.  Reason: so that when we read it back in we'll
1250         -- construct the same ru_rough field as we have right now;
1251         -- see tcIfaceRule
1252     do_arg (Type ty) = IfaceType (toIfaceType (deNoteType ty))
1253     do_arg arg       = toIfaceExpr arg
1254
1255 bogusIfaceRule :: Name -> IfaceRule
1256 bogusIfaceRule id_name
1257   = IfaceRule { ifRuleName = FSLIT("bogus"), ifActivation = NeverActive,  
1258         ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [], 
1259         ifRuleRhs = IfaceExt id_name, ifRuleOrph = Nothing }
1260
1261 ---------------------
1262 toIfaceExpr :: CoreExpr -> IfaceExpr
1263 toIfaceExpr (Var v)       = toIfaceVar v
1264 toIfaceExpr (Lit l)       = IfaceLit l
1265 toIfaceExpr (Type ty)     = IfaceType (toIfaceType ty)
1266 toIfaceExpr (Lam x b)     = IfaceLam (toIfaceBndr x) (toIfaceExpr b)
1267 toIfaceExpr (App f a)     = toIfaceApp f [a]
1268 toIfaceExpr (Case s x ty as) = IfaceCase (toIfaceExpr s) (getFS x) (toIfaceType ty) (map toIfaceAlt as)
1269 toIfaceExpr (Let b e)     = IfaceLet (toIfaceBind b) (toIfaceExpr e)
1270 toIfaceExpr (Cast e co)   = IfaceCast (toIfaceExpr e) (toIfaceType co)
1271 toIfaceExpr (Note n e)    = IfaceNote (toIfaceNote n) (toIfaceExpr e)
1272
1273 ---------------------
1274 toIfaceNote (SCC cc)      = IfaceSCC cc
1275 toIfaceNote InlineMe      = IfaceInlineMe
1276 toIfaceNote (CoreNote s)  = IfaceCoreNote s
1277
1278 ---------------------
1279 toIfaceBind (NonRec b r) = IfaceNonRec (toIfaceIdBndr b) (toIfaceExpr r)
1280 toIfaceBind (Rec prs)    = IfaceRec [(toIfaceIdBndr b, toIfaceExpr r) | (b,r) <- prs]
1281
1282 ---------------------
1283 toIfaceAlt (c,bs,r) = (toIfaceCon c, map getFS bs, toIfaceExpr r)
1284
1285 ---------------------
1286 toIfaceCon (DataAlt dc) | isTupleTyCon tc = IfaceTupleAlt (tupleTyConBoxity tc)
1287                         | otherwise       = IfaceDataAlt (getName dc)
1288                         where
1289                           tc = dataConTyCon dc
1290            
1291 toIfaceCon (LitAlt l) = IfaceLitAlt l
1292 toIfaceCon DEFAULT    = IfaceDefault
1293
1294 ---------------------
1295 toIfaceApp (App f a) as = toIfaceApp f (a:as)
1296 toIfaceApp (Var v) as
1297   = case isDataConWorkId_maybe v of
1298         -- We convert the *worker* for tuples into IfaceTuples
1299         Just dc |  isTupleTyCon tc && saturated 
1300                 -> IfaceTuple (tupleTyConBoxity tc) tup_args
1301           where
1302             val_args  = dropWhile isTypeArg as
1303             saturated = val_args `lengthIs` idArity v
1304             tup_args  = map toIfaceExpr val_args
1305             tc        = dataConTyCon dc
1306
1307         other -> mkIfaceApps (toIfaceVar v) as
1308
1309 toIfaceApp e as = mkIfaceApps (toIfaceExpr e) as
1310
1311 mkIfaceApps f as = foldl (\f a -> IfaceApp f (toIfaceExpr a)) f as
1312
1313 ---------------------
1314 toIfaceVar :: Id -> IfaceExpr
1315 toIfaceVar v 
1316   | Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType (idType v))
1317           -- Foreign calls have special syntax
1318   | isExternalName name             = IfaceExt name
1319   | otherwise                       = IfaceLcl (getFS name)
1320   where
1321     name = idName v
1322 \end{code}