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