[project @ 2000-10-25 15:57:33 by simonpj]
[ghc-hetmet.git] / ghc / compiler / main / MkIface.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[MkIface]{Print an interface for a module}
5
6 \begin{code}
7 module MkIface ( 
8         mkModDetails, mkModDetailsFromIface, completeIface, writeIface
9   ) where
10
11 #include "HsVersions.h"
12
13 import HsSyn
14 import HsCore           ( HsIdInfo(..), UfExpr(..), toUfExpr, toUfBndr )
15 import HsTypes          ( toHsTyVars )
16 import BasicTypes       ( Fixity(..), NewOrData(..),
17                           Version, bumpVersion, isLoopBreaker
18                         )
19 import RnMonad
20 import RnHsSyn          ( RenamedInstDecl, RenamedTyClDecl )
21 import TcHsSyn          ( TypecheckedRuleDecl )
22 import HscTypes         ( VersionInfo(..), IfaceDecls(..), ModIface(..), ModDetails(..),
23                           TyThing(..), DFunId, TypeEnv, isTyClThing
24                         )
25
26 import CmdLineOpts
27 import Id               ( Id, idType, idInfo, omitIfaceSigForId, isUserExportedId, hasNoBinding,
28                           idSpecialisation, idName, setIdInfo
29                         )
30 import Var              ( isId )
31 import VarSet
32 import DataCon          ( StrictnessMark(..), dataConSig, dataConFieldLabels, dataConStrictMarks )
33 import IdInfo           -- Lots
34 import CoreSyn          ( CoreExpr, CoreBind, Bind(..), CoreRule(..), IdCoreRule, 
35                           isBuiltinRule, rulesRules, rulesRhsFreeVars, emptyCoreRules,
36                           bindersOfBinds
37                         )
38 import CoreFVs          ( exprSomeFreeVars, ruleSomeLhsFreeVars, ruleSomeFreeVars )
39 import CoreUnfold       ( okToUnfoldInHiFile, mkTopUnfolding, neverUnfold, unfoldingTemplate, noUnfolding )
40 import Name             ( isLocallyDefined, getName, 
41                           Name, NamedThing(..),
42                           plusNameEnv, lookupNameEnv, emptyNameEnv, mkNameEnv,
43                           extendNameEnv, lookupNameEnv_NF, nameEnvElts
44                         )
45 import TyCon            ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon,
46                           tyConTheta, tyConTyVars, tyConDataCons, tyConFamilySize
47                         )
48 import Class            ( classExtraBigSig, DefMeth(..) )
49 import FieldLabel       ( fieldLabelType )
50 import Type             ( splitSigmaTy, tidyTopType, deNoteType )
51 import SrcLoc           ( noSrcLoc )
52 import Outputable
53
54 import List             ( partition )
55 \end{code}
56
57
58 %************************************************************************
59 %*                                                                      *
60 \subsection{Write a new interface file}
61 %*                                                                      *
62 %************************************************************************
63
64 \begin{code}
65 mkModDetails :: TypeEnv -> [DFunId]     -- From typechecker
66              -> [CoreBind] -> [Id]      -- Final bindings, plus the top-level Ids from the
67                                         -- code generator; they have authoritative arity info
68              -> [IdCoreRule]            -- Tidy orphan rules
69              -> ModDetails
70 mkModDetails type_env dfun_ids tidy_binds stg_ids orphan_rules
71   = ModDetails { md_types = new_type_env,
72                  md_rules = rule_dcls,
73                  md_insts = dfun_ids }
74   where
75         -- The competed type environment is gotten from
76         --      a) keeping the types and classes
77         --      b) removing all Ids, and Ids with correct IdInfo
78         --              gotten from the bindings
79     new_type_env = mkNameEnv [(getName tycl, tycl) | tycl <- orig_type_env, isTyClThing tycl]
80                         `plusNameEnv`
81                    mkNameEnv [(idName id, AnId id) | id <- final_ids]
82
83     orig_type_env = nameEnvElts type_env
84
85     final_ids = bindsToIds (mkVarSet dfun_ids `unionVarSet` orphan_rule_ids)
86                            (mkVarSet stg_ids)
87                            tidy_binds
88
89         -- The complete rules are gotten by combining
90         --      a) the orphan rules
91         --      b) rules embedded in the top-level Ids
92     rule_dcls | opt_OmitInterfacePragmas = []
93               | otherwise                 = getRules orphan_rules tidy_binds (mkVarSet final_ids)
94
95     orphan_rule_ids = unionVarSets [ ruleSomeFreeVars interestingId rule 
96                                    | (_, rule) <- orphan_rules]
97
98
99 -- This version is used when we are re-linking a module
100 -- so we've only run the type checker on its previous interface 
101 mkModDetailsFromIface :: TypeEnv -> [DFunId]    -- From typechecker
102                       -> [TypecheckedRuleDecl]
103                       -> ModDetails
104 mkModDetailsFromIface type_env dfun_ids rules
105   = ModDetails { md_types = type_env,
106                  md_rules = rule_dcls,
107                  md_insts = dfun_ids }
108   where
109     rule_dcls = [(id,rule) | IfaceRuleOut id rule <- rules]
110         -- All the rules from an interface are of the IfaceRuleOut form
111
112
113 completeIface :: Maybe ModIface         -- The old interface, if we have it
114               -> ModIface               -- The new one, minus the decls and versions
115               -> ModDetails             -- The ModDetails for this module
116               -> Maybe (ModIface, SDoc) -- The new one, complete with decls and versions
117                                         -- The SDoc is a debug document giving differences
118                                         -- Nothing => no change
119
120         -- NB: 'Nothing' means that even the usages havn't changed, so there's no
121         --     need to write a new interface file.  But even if the usages have
122         --     changed, the module version may not have.
123         --
124         -- The IO in the type is solely for debug output
125         -- In particular, dumping a record of what has changed
126 completeIface maybe_old_iface new_iface mod_details 
127   = addVersionInfo maybe_old_iface (new_iface { mi_decls = new_decls })
128   where
129      new_decls = IfaceDecls { dcl_tycl  = ty_cls_dcls,
130                               dcl_insts = inst_dcls,
131                               dcl_rules = rule_dcls }
132
133      inst_dcls   = map ifaceInstance (md_insts mod_details)
134      ty_cls_dcls = map ifaceTyCls (nameEnvElts (md_types mod_details))
135      rule_dcls   = map ifaceRule (md_rules mod_details)
136 \end{code}
137
138
139 %************************************************************************
140 %*                                                                      *
141 \subsection{Types and classes}
142 %*                                                                      *
143 %************************************************************************
144
145 \begin{code}
146 ifaceTyCls :: TyThing -> RenamedTyClDecl
147 ifaceTyCls (AClass clas)
148   = ClassDecl (toHsContext sc_theta)
149               (getName clas)
150               (toHsTyVars clas_tyvars)
151               (toHsFDs clas_fds)
152               (map toClassOpSig op_stuff)
153               EmptyMonoBinds
154               [] noSrcLoc
155   where
156      (clas_tyvars, clas_fds, sc_theta, _, op_stuff) = classExtraBigSig clas
157
158      toClassOpSig (sel_id, def_meth)
159         = ASSERT(sel_tyvars == clas_tyvars)
160           ClassOpSig (getName sel_id) (Just def_meth') (toHsType op_ty) noSrcLoc
161         where
162           (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
163           def_meth' = case def_meth of
164                          NoDefMeth  -> NoDefMeth
165                          GenDefMeth -> GenDefMeth
166                          DefMeth id -> DefMeth (getName id)
167
168 ifaceTyCls (ATyCon tycon)
169   | isSynTyCon tycon
170   = TySynonym (getName tycon)(toHsTyVars tyvars) (toHsType ty) noSrcLoc
171   where
172     (tyvars, ty) = getSynTyConDefn tycon
173
174 ifaceTyCls (ATyCon tycon)
175   | isAlgTyCon tycon
176   = TyData new_or_data (toHsContext (tyConTheta tycon))
177            (getName tycon)
178            (toHsTyVars tyvars)
179            (map ifaceConDecl (tyConDataCons tycon))
180            (tyConFamilySize tycon)
181            Nothing noSrcLoc (panic "gen1") (panic "gen2")
182   where
183     tyvars = tyConTyVars tycon
184     new_or_data | isNewTyCon tycon = NewType
185                 | otherwise        = DataType
186
187     ifaceConDecl data_con 
188         = ConDecl (getName data_con) (error "ifaceConDecl")
189                   (toHsTyVars ex_tyvars)
190                   (toHsContext ex_theta)
191                   details noSrcLoc
192         where
193           (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
194           field_labels   = dataConFieldLabels data_con
195           strict_marks   = dataConStrictMarks data_con
196           details | null field_labels
197                   = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
198                     VanillaCon (zipWith mk_bang_ty strict_marks arg_tys)
199
200                   | otherwise
201                   = RecCon (zipWith mk_field strict_marks field_labels)
202
203     mk_bang_ty NotMarkedStrict     ty = Unbanged (toHsType ty)
204     mk_bang_ty (MarkedUnboxed _ _) ty = Unpacked (toHsType ty)
205     mk_bang_ty MarkedStrict        ty = Banged   (toHsType ty)
206
207     mk_field strict_mark field_label
208         = ([getName field_label], mk_bang_ty strict_mark (fieldLabelType field_label))
209
210 ifaceTyCls (ATyCon tycon) = pprPanic "ifaceTyCls" (ppr tycon)
211
212 ifaceTyCls (AnId id) 
213   = IfaceSig (getName id) (toHsType id_type) hs_idinfo noSrcLoc
214   where
215     id_type = idType id
216     id_info = idInfo id
217
218     hs_idinfo | opt_OmitInterfacePragmas = []
219               | otherwise                = arity_hsinfo  ++ caf_hsinfo  ++ cpr_hsinfo ++ 
220                                            strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
221
222     ------------  Arity  --------------
223     arity_hsinfo = case arityInfo id_info of
224                         a@(ArityExactly n) -> [HsArity a]
225                         other              -> []
226
227     ------------ Caf Info --------------
228     caf_hsinfo = case cafInfo id_info of
229                    NoCafRefs -> [HsNoCafRefs]
230                    otherwise -> []
231
232     ------------ CPR Info --------------
233     cpr_hsinfo = case cprInfo id_info of
234                    ReturnsCPR -> [HsCprInfo]
235                    NoCPRInfo  -> []
236
237     ------------  Strictness  --------------
238     strict_hsinfo = case strictnessInfo id_info of
239                         NoStrictnessInfo -> []
240                         info             -> [HsStrictness info]
241
242
243     ------------  Worker  --------------
244     wrkr_hsinfo = case workerInfo id_info of
245                     HasWorker work_id wrap_arity -> [HsWorker (getName work_id)]
246                     NoWorker                     -> []
247
248     ------------  Unfolding  --------------
249     unfold_info = unfoldingInfo id_info
250     inline_prag = inlinePragInfo id_info
251     rhs         = unfoldingTemplate unfold_info
252     unfold_hsinfo | neverUnfold unfold_info = []
253                   | otherwise               = [HsUnfold inline_prag (toUfExpr rhs)]
254 \end{code}
255
256
257 %************************************************************************
258 %*                                                                      *
259 \subsection{Instances and rules}
260 %*                                                                      *
261 %************************************************************************
262
263 \begin{code}                     
264 ifaceInstance :: DFunId -> RenamedInstDecl
265 ifaceInstance dfun_id
266   = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc                      
267   where
268     tidy_ty = tidyTopType (deNoteType (idType dfun_id))
269                 -- The deNoteType is very important.   It removes all type
270                 -- synonyms from the instance type in interface files.
271                 -- That in turn makes sure that when reading in instance decls
272                 -- from interface files that the 'gating' mechanism works properly.
273                 -- Otherwise you could have
274                 --      type Tibble = T Int
275                 --      instance Foo Tibble where ...
276                 -- and this instance decl wouldn't get imported into a module
277                 -- that mentioned T but not Tibble.
278
279 ifaceRule (id, BuiltinRule _)
280   = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
281
282 ifaceRule (id, Rule name bndrs args rhs)
283   = IfaceRule name (map toUfBndr bndrs) (getName id)
284               (map toUfExpr args) (toUfExpr rhs) noSrcLoc
285
286 bogusIfaceRule id
287   = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
288 \end{code}
289
290
291 %************************************************************************
292 %*                                                                      *
293 \subsection{Compute final Ids}
294 %*                                                                      * 
295 %************************************************************************
296
297 A "final Id" has exactly the IdInfo for going into an interface file, or
298 exporting to another module.
299
300 \begin{code}
301 bindsToIds :: IdSet             -- These Ids are needed already
302            -> IdSet             -- Ids used at code-gen time; they have better pragma info!
303            -> [CoreBind]        -- In dependency order, later depend on earlier
304            -> [Id]              -- Set of Ids actually spat out, complete with exactly the IdInfo
305                                 -- they need for exporting to another module
306
307 bindsToIds needed_ids codegen_ids binds
308   = go needed_ids (reverse binds) []
309                 -- Reverse so that later things will 
310                 -- provoke earlier ones to be emitted
311   where
312         -- The 'needed' set contains the Ids that are needed by earlier
313         -- interface file emissions.  If the Id isn't in this set, and isn't
314         -- exported, there's no need to emit anything
315     need_id needed_set id = id `elemVarSet` needed_set || isUserExportedId id 
316
317     go needed [] emitted
318         | not (isEmptyVarSet needed) = pprTrace "ifaceBinds: free vars:" 
319                                           (sep (map ppr (varSetElems needed)))
320                                        emitted
321         | otherwise                  = emitted
322
323     go needed (NonRec id rhs : binds) emitted
324         | need_id needed id
325         = if omitIfaceSigForId id then
326             go (needed `delVarSet` id) binds (id:emitted)
327           else
328             go ((needed `unionVarSet` extras) `delVarSet` id)
329                binds
330                (new_id:emitted)
331         | otherwise
332         = go needed binds emitted
333         where
334           (new_id, extras) = mkFinalId codegen_ids False id rhs
335
336         -- Recursive groups are a bit more of a pain.  We may only need one to
337         -- start with, but it may call out the next one, and so on.  So we
338         -- have to look for a fixed point.  We don't want necessarily them all, 
339         -- because without -O we may only need the first one (if we don't emit
340         -- its unfolding)
341     go needed (Rec pairs : binds) emitted
342         = go needed' binds emitted' 
343         where
344           (new_emitted, extras) = go_rec needed pairs
345           needed'  = (needed `unionVarSet` extras) `minusVarSet` mkVarSet (map fst pairs) 
346           emitted' = new_emitted ++ emitted 
347
348     go_rec :: IdSet -> [(Id,CoreExpr)] -> ([Id], IdSet)
349     go_rec needed pairs
350         | null needed_prs = ([], emptyVarSet)
351         | otherwise       = (emitted ++           more_emitted,
352                              extras `unionVarSet` more_extras)
353         where
354           (needed_prs,leftover_prs)   = partition is_needed pairs
355           (emitted, extras_s)         = unzip [ mkFinalId codegen_ids True id rhs 
356                                               | (id,rhs) <- needed_prs, not (omitIfaceSigForId id)]
357           extras                      = unionVarSets extras_s
358           (more_emitted, more_extras) = go_rec extras leftover_prs
359
360           is_needed (id,_) = need_id needed id
361 \end{code}
362
363
364
365 \begin{code}
366 mkFinalId :: IdSet              -- The Ids with arity info from the code generator
367           -> Bool                       -- True <=> recursive, so don't include unfolding
368           -> Id
369           -> CoreExpr           -- The Id's right hand side
370           -> (Id, IdSet)                -- The emitted id, plus any *extra* needed Ids
371
372 mkFinalId codegen_ids is_rec id rhs
373   = (id `setIdInfo` new_idinfo, new_needed_ids)
374   where
375     core_idinfo = idInfo id
376     stg_idinfo  = case lookupVarSet codegen_ids id of
377                         Just id' -> idInfo id'
378                         Nothing  -> pprTrace "ifaceBinds not found:" (ppr id) $
379                                     idInfo id
380
381     new_idinfo | opt_OmitInterfacePragmas
382                = vanillaIdInfo
383                | otherwise                
384                = core_idinfo `setArityInfo`      arity_info
385                              `setCafInfo`        cafInfo stg_idinfo
386                              `setUnfoldingInfo`  unfold_info
387                              `setWorkerInfo`     worker_info
388                              `setSpecInfo`       emptyCoreRules
389         -- We zap the specialisations because they are
390         -- passed on separately through the modules IdCoreRules
391
392     ------------  Arity  --------------
393     arity_info = arityInfo stg_idinfo
394     stg_arity  = arityLowerBound arity_info
395
396     ------------  Worker  --------------
397         -- We only treat a function as having a worker if
398         -- the exported arity (which is now the number of visible lambdas)
399         -- is the same as the arity at the moment of the w/w split
400         -- If so, we can safely omit the unfolding inside the wrapper, and
401         -- instead re-generate it from the type/arity/strictness info
402         -- But if the arity has changed, we just take the simple path and
403         -- put the unfolding into the interface file, forgetting the fact
404         -- that it's a wrapper.  
405         --
406         -- How can this happen?  Sometimes we get
407         --      f = coerce t (\x y -> $wf x y)
408         -- at the moment of w/w split; but the eta reducer turns it into
409         --      f = coerce t $wf
410         -- which is perfectly fine except that the exposed arity so far as
411         -- the code generator is concerned (zero) differs from the arity
412         -- when we did the split (2).  
413         --
414         -- All this arises because we use 'arity' to mean "exactly how many
415         -- top level lambdas are there" in interface files; but during the
416         -- compilation of this module it means "how many things can I apply
417         -- this to".
418     worker_info = case workerInfo core_idinfo of
419                      info@(HasWorker work_id wrap_arity)
420                         | wrap_arity == stg_arity -> info
421                         | otherwise               -> pprTrace "ifaceId: arity change:" (ppr id) 
422                                                      NoWorker
423                      NoWorker                     -> NoWorker
424
425     has_worker = case worker_info of
426                    HasWorker _ _ -> True
427                    other         -> False
428
429     HasWorker work_id _ = worker_info
430
431     ------------  Unfolding  --------------
432     inline_pragma  = inlinePragInfo core_idinfo
433     dont_inline    = isNeverInlinePrag inline_pragma
434     loop_breaker   = isLoopBreaker (occInfo core_idinfo)
435     bottoming_fn   = isBottomingStrictness (strictnessInfo core_idinfo)
436
437     unfolding    = mkTopUnfolding rhs
438     rhs_is_small = neverUnfold unfolding
439
440     unfold_info | show_unfold = unfolding
441                 | otherwise   = noUnfolding
442
443     show_unfold = not has_worker         &&     -- Not unnecessary
444                   not bottoming_fn       &&     -- Not necessary
445                   not dont_inline        &&
446                   not loop_breaker       &&
447                   rhs_is_small           &&     -- Small enough
448                   okToUnfoldInHiFile rhs        -- No casms etc
449
450
451     ------------  Extra free Ids  --------------
452     new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
453                    | otherwise                = worker_ids      `unionVarSet`
454                                                 unfold_ids      `unionVarSet`
455                                                 spec_ids
456
457     spec_ids = filterVarSet interestingId (rulesRhsFreeVars (specInfo core_idinfo))
458
459     worker_ids | has_worker && interestingId work_id = unitVarSet work_id
460                         -- Conceivably, the worker might come from
461                         -- another module
462                | otherwise = emptyVarSet
463
464     unfold_ids | show_unfold = find_fvs rhs
465                | otherwise   = emptyVarSet
466
467     find_fvs expr = exprSomeFreeVars interestingId expr
468
469 interestingId id = isId id && isLocallyDefined id && not (hasNoBinding id)
470 \end{code}
471
472
473 \begin{code}
474 getRules :: [IdCoreRule]        -- Orphan rules
475          -> [CoreBind]          -- Bindings, with rules in the top-level Ids
476          -> IdSet               -- Ids that are exported, so we need their rules
477          -> [IdCoreRule]
478 getRules orphan_rules binds emitted
479   = orphan_rules ++ local_rules
480   where
481     local_rules  = [ (fn, rule)
482                    | fn <- bindersOfBinds binds,
483                      fn `elemVarSet` emitted,
484                      rule <- rulesRules (idSpecialisation fn),
485                      not (isBuiltinRule rule),
486                                 -- We can't print builtin rules in interface files
487                                 -- Since they are built in, an importing module
488                                 -- will have access to them anyway
489
490                         -- Sept 00: I've disabled this test.  It doesn't stop many, if any, rules
491                         -- from coming out, and to make it work properly we need to add ????
492                         --      (put it back in for now)
493                      all (`elemVarSet` emitted) (varSetElems (ruleSomeLhsFreeVars interestingId rule))
494                                 -- Spit out a rule only if all its lhs free vars are emitted
495                                 -- This is a good reason not to do it when we emit the Id itself
496                    ]
497 \end{code}
498
499
500 %************************************************************************
501 %*                                                                      *
502 \subsection{Checking if the new interface is up to date
503 %*                                                                      *
504 %************************************************************************
505
506 \begin{code}
507 addVersionInfo :: Maybe ModIface                -- The old interface, read from M.hi
508                -> ModIface                      -- The new interface decls
509                -> Maybe (ModIface, SDoc)        -- Nothing => no change; no need to write new Iface
510                                                 -- Just mi => Here is the new interface to write
511                                                 --            with correct version numbers
512
513 -- NB: the fixities, declarations, rules are all assumed
514 -- to be sorted by increasing order of hsDeclName, so that 
515 -- we can compare for equality
516
517 addVersionInfo Nothing new_iface
518 -- No old interface, so definitely write a new one!
519   = Just (new_iface, text "No old interface available")
520
521 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version, 
522                                            mi_decls   = old_decls,
523                                            mi_fixities = old_fixities }))
524                new_iface@(ModIface { mi_decls = new_decls,
525                                      mi_fixities = new_fixities })
526
527   | no_output_change && no_usage_change
528   = Nothing
529
530   | otherwise           -- Add updated version numbers
531   = Just (final_iface, pp_tc_diffs)
532         
533   where
534     final_iface = new_iface { mi_version = new_version }
535     new_version = VersionInfo { vers_module  = bumpVersion no_output_change (vers_module  old_version),
536                                 vers_exports = bumpVersion no_export_change (vers_exports old_version),
537                                 vers_rules   = bumpVersion no_rule_change   (vers_rules   old_version),
538                                 vers_decls   = tc_vers }
539
540     no_output_change = no_tc_change && no_rule_change && no_export_change
541     no_usage_change  = mi_usages old_iface == mi_usages new_iface
542
543     no_export_change = mi_exports old_iface == mi_exports new_iface             -- Kept sorted
544     no_rule_change   = dcl_rules old_decls  == dcl_rules  new_decls             -- Ditto
545
546         -- Fill in the version number on the new declarations by looking at the old declarations.
547         -- Set the flag if anything changes. 
548         -- Assumes that the decls are sorted by hsDeclName.
549     old_vers_decls = vers_decls old_version
550     (no_tc_change,  pp_tc_diffs,  tc_vers) = diffDecls old_vers_decls old_fixities new_fixities
551                                                        (dcl_tycl old_decls) (dcl_tycl new_decls)
552
553
554
555 diffDecls :: NameEnv Version                            -- Old version map
556           -> NameEnv Fixity -> NameEnv Fixity           -- Old and new fixities
557           -> [RenamedTyClDecl] -> [RenamedTyClDecl]     -- Old and new decls
558           -> (Bool,             -- True <=> no change
559               SDoc,             -- Record of differences
560               NameEnv Version)  -- New version
561
562 diffDecls old_vers old_fixities new_fixities old new
563   = diff True empty emptyNameEnv old new
564   where
565         -- When seeing if two decls are the same, 
566         -- remember to check whether any relevant fixity has changed
567     eq_tc  d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
568     same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
569
570     diff ok_so_far pp new_vers []  []      = (ok_so_far, pp, new_vers)
571     diff ok_so_far pp new_vers old []      = (False,     pp, new_vers)
572     diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers [] nds
573     diff ok_so_far pp new_vers (od:ods) (nd:nds)
574         = case od_name `compare` nd_name of
575                 LT -> diff False (pp $$ only_old od) new_vers ods      (nd:nds)
576                 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
577                 EQ | od `eq_tc` nd -> diff ok_so_far pp                    new_vers  ods nds
578                    | otherwise     -> diff False     (pp $$ changed od nd) new_vers' ods nds
579         where
580           od_name = tyClDeclName od
581           nd_name = tyClDeclName nd
582           new_vers' = extendNameEnv new_vers nd_name 
583                                     (bumpVersion True (lookupNameEnv_NF old_vers od_name))
584
585     only_old d   = ptext SLIT("Only in old iface:") <+> ppr d
586     only_new d   = ptext SLIT("Only in new iface:") <+> ppr d
587     changed d nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr d) $$ 
588                                                          (ptext SLIT("New:") <+> ppr nd))
589 \end{code}
590
591
592
593 %************************************************************************
594 %*                                                                      *
595 \subsection{Writing an interface file}
596 %*                                                                      *
597 %************************************************************************
598
599 \begin{code}
600 writeIface :: Finder -> ModIface -> IO ()
601 writeIface finder mod_iface
602   = do  { let filename = error "... find the right file..."
603         ; if_hdl <- openFile filename WriteMode
604         ; printForIface if_hdl (pprIface mod_iface)
605         ; hClose if_hdl
606         }
607
608 pprIface iface
609  = vcat [ ptext SLIT("__interface")
610                 <+> doubleQuotes (ptext opt_InPackage)
611                 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
612                 <+> pp_sub_vers
613                 <+> (if mi_orphan iface then char '!' else empty)
614                 <+> int opt_HiVersion
615                 <+> ptext SLIT("where")
616
617         , pprExports (mi_exports iface)
618         , vcat (map pprUsage (mi_usages iface))
619
620         , pprIfaceDecls (vers_decls version_info) 
621                         (mi_fixities iface)
622                         (mi_decls iface)
623
624         , pprDeprecs (mi_deprecs iface)
625         ]
626   where
627     version_info = mi_version mod_iface
628     exp_vers     = vers_exports version_info
629     rule_vers    = vers_rules version_info
630
631     pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
632                 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
633 \end{code}
634
635 When printing export lists, we print like this:
636         Avail   f               f
637         AvailTC C [C, x, y]     C(x,y)
638         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
639
640 \begin{code}
641 pprExport :: (ModuleName, Avails) -> SDoc
642 pprExport (mod, items)
643  = hsep [ ptext SLIT("__export "), ppr mod, hsep (map upp_avail items) ] <> semi
644   where
645     pp_avail :: RdrAvailInfo -> SDoc
646     pp_avail (Avail name)      = pprOccName name
647     pp_avail (AvailTC name []) = empty
648     pp_avail (AvailTC name ns) = hcat [pprOccName name, bang, upp_export ns']
649                                 where
650                                   bang | name `elem` ns = empty
651                                        | otherwise      = char '|'
652                                   ns' = filter (/= name) ns
653     
654     pp_export []    = empty
655     pp_export names = braces (hsep (map pprOccName names))
656 \end{code}
657
658
659 \begin{code}
660 pprUsage :: ImportVersion Name -> SDoc
661 pprUsage (m, has_orphans, is_boot, whats_imported)
662   = hsep [ptext SLIT("import"), pprModuleName m, 
663           pp_orphan, pp_boot,
664           pp_versions whats_imported
665     ] <> semi
666   where
667     pp_orphan | has_orphans = char '!'
668               | otherwise   = empty
669     pp_boot   | is_boot     = char '@'
670               | otherwise   = empty
671
672         -- Importing the whole module is indicated by an empty list
673     pp_versions NothingAtAll                = empty
674     pp_versions (Everything v)              = dcolon <+> int v
675     pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr 
676                                               <+> hsep [ ppr n <+> int v | (n,v) <- nvs ]
677
678         -- HACK for the moment: print the export-list version even if
679         -- we don't use it, so that syntax of interface files doesn't change
680     pp_export_version Nothing  = int 1
681     pp_export_version (Just v) = int v
682 \end{code}
683
684 \begin{code}
685 pprIfaceDecls version_map fixity_map decls
686   = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
687          , vcat (map ppr_decl (dcl_tycl decls))
688          , pprRules (dcl_rules decls)
689          ]
690   where
691     ppr_decl d  = (ppr_vers d <+> ppr d <> semi) $$ ppr_fixes d
692
693         -- Print the version for the decl
694     ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
695                    Nothing -> empty
696                    Just v  -> int v
697
698         -- Print fixities relevant to the decl
699     ppr_fixes d = vcat (map ppr_fix (fixities d))
700     fixities d  = [ ppr fix <+> ppr n <> semi
701                   | n <- tyClDeclNames d, 
702                     [Just fix] <- lookupNameEnv fixity_map n
703                   ]
704 \end{code}
705
706 \begin{code}
707 pprRules []    = empty
708 pprRules rules = hsep [ptext SLIT("{-## __R"), vcat (map ppr rules), ptext SLIT("##-}")]
709
710 pprDeprecs []   = empty
711 pprDeprecs deps = hsep [ ptext SLIT("{-## __D"), guts, ptext SLIT("##-}")]
712                 where
713                   guts = hsep [ ppr ie <+> doubleQuotes (ppr txt) <> semi 
714                               | Deprecation ie txt _ <- deps ]
715 \end{code}