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