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