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