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