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