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