[project @ 2000-05-24 15:47:13 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         startIface, endIface, ifaceDecls
9     ) where
10
11 #include "HsVersions.h"
12
13 import IO               ( Handle, hPutStr, openFile, 
14                           hClose, hPutStrLn, IOMode(..) )
15
16 import HsSyn
17 import BasicTypes       ( Fixity(..), FixityDirection(..), NewOrData(..), 
18                           OccInfo, isLoopBreaker
19                         )
20 import RnMonad
21 import RnEnv            ( availName )
22
23 import TcInstUtil       ( InstInfo(..) )
24
25 import CmdLineOpts
26 import Id               ( Id, idType, idInfo, omitIfaceSigForId, isUserExportedId,
27                           idSpecialisation
28                         )
29 import Var              ( isId )
30 import VarSet
31 import DataCon          ( StrictnessMark(..), dataConSig, dataConFieldLabels, dataConStrictMarks )
32 import IdInfo           ( IdInfo, StrictnessInfo(..), ArityInfo, InlinePragInfo(..), inlinePragInfo,
33                           arityInfo, ppArityInfo, arityLowerBound,
34                           strictnessInfo, ppStrictnessInfo, isBottomingStrictness,
35                           cafInfo, ppCafInfo, specInfo,
36                           cprInfo, ppCprInfo, pprInlinePragInfo,
37                           occInfo, isNeverInlinePrag,
38                           workerExists, workerInfo, ppWorkerInfo, WorkerInfo(..)
39                         )
40 import CoreSyn          ( CoreExpr, CoreBind, Bind(..), rulesRules, rulesRhsFreeVars )
41 import CoreFVs          ( exprSomeFreeVars, ruleSomeLhsFreeVars, ruleSomeFreeVars )
42 import CoreUnfold       ( okToUnfoldInHiFile, couldBeSmallEnoughToInline )
43 import Module           ( moduleString, pprModule, pprModuleName )
44 import Name             ( isLocallyDefined, isWiredInName, nameRdrName, nameModule,
45                           Name, NamedThing(..)
46                         )
47 import OccName          ( OccName, pprOccName )
48 import TyCon            ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon,
49                           tyConTheta, tyConTyVars, tyConDataCons
50                         )
51 import Class            ( Class, classExtraBigSig )
52 import FieldLabel       ( fieldLabelName, fieldLabelType )
53 import Type             ( mkSigmaTy, splitSigmaTy, mkDictTy, tidyTopType,
54                           deNoteType, classesToPreds,
55                           Type, ThetaType, PredType(..), ClassContext
56                         )
57
58 import PprType
59 import PprCore          ( pprIfaceUnfolding, pprCoreRule )
60 import FunDeps          ( pprFundeps )
61 import Rules            ( pprProtoCoreRule, ProtoCoreRule(..) )
62
63 import Bag              ( bagToList, isEmptyBag )
64 import Maybes           ( catMaybes, maybeToBool )
65 import FiniteMap        ( emptyFM, addToFM, addToFM_C, fmToList, FiniteMap )
66 import UniqFM           ( lookupUFM, listToUFM )
67 import UniqSet          ( uniqSetToList )
68 import Util             ( sortLt, mapAccumL )
69 import Bag
70 import Outputable
71 \end{code}
72
73 We have a function @startIface@ to open the output file and put
74 (something like) ``interface Foo'' in it.  It gives back a handle
75 for subsequent additions to the interface file.
76
77 We then have one-function-per-block-of-interface-stuff, e.g.,
78 @ifaceExportList@ produces the @__exports__@ section; it appends
79 to the handle provided by @startIface@.
80
81 NOTE: ALWAYS remember that ghc-iface.lprl rewrites the interface file,
82 so you have to keep it in synch with the code below. Otherwise you'll
83 lose the happiest years of your life, believe me...  -- SUP
84
85 \begin{code}
86 startIface  :: Module -> InterfaceDetails
87             -> IO (Maybe Handle) -- Nothing <=> don't do an interface
88
89 ifaceDecls :: Maybe Handle
90            -> [TyCon] -> [Class]
91            -> Bag InstInfo 
92            -> [Id]              -- Ids used at code-gen time; they have better pragma info!
93            -> [CoreBind]        -- In dependency order, later depend on earlier
94            -> [ProtoCoreRule]   -- Rules
95            -> [Deprecation Name]
96            -> IO ()
97
98 endIface    :: Maybe Handle -> IO ()
99 \end{code}
100
101 \begin{code}
102 startIface mod (InterfaceDetails has_orphans import_usages (ExportEnv avails fixities _) _)
103   = case opt_ProduceHi of
104       Nothing -> return Nothing ; -- not producing any .hi file
105
106       Just fn -> do 
107         if_hdl <- openFile fn WriteMode
108         hPutStr         if_hdl ("__interface \"" ++ show opt_InPackage ++ "\" " ++ moduleString mod)
109         hPutStr         if_hdl (' ' : orphan_indicator)
110         hPutStrLn       if_hdl " where"
111         ifaceExports    if_hdl avails
112         ifaceImports    if_hdl import_usages
113         ifaceFixities   if_hdl fixities
114         return (Just if_hdl)
115   where
116     orphan_indicator | has_orphans = " !"
117                      | otherwise   = ""
118
119 endIface Nothing        = return ()
120 endIface (Just if_hdl)  = hPutStr if_hdl "\n" >> hClose if_hdl
121 \end{code}
122
123
124 \begin{code}
125 ifaceDecls Nothing tycons classes inst_info final_ids simplified rules _ = return ()
126 ifaceDecls (Just hdl)
127            tycons classes
128            inst_infos
129            final_ids
130            binds
131            orphan_rules         -- Rules defined locally for an Id that is *not* defined locally
132            deprecations
133   | null_decls = return ()               
134         --  You could have a module with just (re-)exports/instances in it
135   | otherwise
136   = ifaceClasses hdl classes                    >>
137     ifaceInstances hdl inst_infos               >>= \ inst_ids ->
138     ifaceTyCons hdl tycons                      >>
139     ifaceBinds hdl (inst_ids `unionVarSet` orphan_rule_ids)
140                final_ids binds                  >>= \ emitted_ids ->
141     ifaceRules hdl orphan_rules emitted_ids     >>
142     ifaceDeprecations hdl deprecations
143   where
144      orphan_rule_ids = unionVarSets [ ruleSomeFreeVars interestingId rule 
145                                     | ProtoCoreRule _ _ rule <- orphan_rules]
146
147      null_decls = null binds            && 
148                   null tycons           &&
149                   null classes          && 
150                   isEmptyBag inst_infos &&
151                   null orphan_rules     &&
152                   null deprecations
153 \end{code}
154
155 \begin{code}
156 ifaceImports :: Handle -> VersionInfo Name -> IO ()
157 ifaceImports if_hdl import_usages
158   = hPutCol if_hdl upp_uses (sortLt lt_imp_vers import_usages)
159   where
160     upp_uses (m, mv, has_orphans, is_boot, whats_imported)
161       = hsep [ptext SLIT("import"), pprModuleName m, 
162               int mv, pp_orphan, pp_boot,
163               upp_import_versions whats_imported
164         ] <> semi
165       where
166         pp_orphan | has_orphans = ptext SLIT("!")
167                   | otherwise   = empty
168         pp_boot   | is_boot     = ptext SLIT("@")
169                   | otherwise   = empty
170
171         -- Importing the whole module is indicated by an empty list
172     upp_import_versions Everything = empty
173
174         -- For imported versions we do print the version number
175     upp_import_versions (Specifically nvs)
176       = dcolon <+> hsep [ hsep [ppr_unqual_name n, int v] | (n,v) <- sort_versions nvs ]
177
178 {- SUP: What's this??
179 ifaceModuleDeps if_hdl [] = return ()
180 ifaceModuleDeps if_hdl mod_deps
181   = let 
182         lines = map ppr_mod_dep mod_deps
183         ppr_mod_dep (mod, contains_orphans) 
184            | contains_orphans = pprModuleName mod <+> ptext SLIT("!")
185            | otherwise        = pprModuleName mod
186     in 
187     printForIface if_hdl (ptext SLIT("__depends") <+> vcat lines <> ptext SLIT(" ;")) >>
188     hPutStr if_hdl "\n"
189 -}
190
191 ifaceExports :: Handle -> Avails -> IO ()
192 ifaceExports if_hdl [] = return ()
193 ifaceExports if_hdl avails
194   = hPutCol if_hdl do_one_module (fmToList export_fm)
195   where
196         -- Sort them into groups by module
197     export_fm :: FiniteMap Module [AvailInfo]
198     export_fm = foldr insert emptyFM avails
199
200     insert avail efm = addToFM_C (++) efm mod [avail] 
201                      where
202                        mod = nameModule (availName avail)
203
204         -- Print one module's worth of stuff
205     do_one_module :: (Module, [AvailInfo]) -> SDoc
206     do_one_module (mod_name, avails@(avail1:_))
207         = ptext SLIT("__export ") <>
208           hsep [pprModule mod_name,
209                 hsep (map upp_avail (sortLt lt_avail avails))
210           ] <> semi
211
212 ifaceFixities :: Handle -> Fixities -> IO ()
213 ifaceFixities if_hdl [] = return ()
214 ifaceFixities if_hdl fixities 
215   = hPutCol if_hdl upp_fixity fixities
216
217 ifaceRules :: Handle -> [ProtoCoreRule] -> IdSet -> IO ()
218 ifaceRules if_hdl rules emitted
219   |  opt_OmitInterfacePragmas   -- Don't emit rules if we are suppressing
220                                 -- interface pragmas
221   || (null orphan_rule_pretties && null local_id_pretties)
222   = return ()
223   | otherwise
224   = printForIface if_hdl (vcat [
225                 ptext SLIT("{-## __R"),
226                 vcat orphan_rule_pretties,
227                 vcat local_id_pretties,
228                 ptext SLIT("##-}")
229        ])
230   where
231     orphan_rule_pretties =  [ pprCoreRule (Just fn) rule
232                             | ProtoCoreRule _ fn rule <- rules
233                             ]
234     local_id_pretties = [ pprCoreRule (Just fn) rule
235                         | fn <- varSetElems emitted, 
236                           rule <- rulesRules (idSpecialisation fn),
237                           all (`elemVarSet` emitted) (varSetElems (ruleSomeLhsFreeVars interestingId rule))
238                                 -- Spit out a rule only if all its lhs free vars are emitted
239                                 -- This is a good reason not to do it when we emit the Id itself
240                         ]
241
242 ifaceDeprecations :: Handle -> [Deprecation Name] -> IO ()
243 ifaceDeprecations if_hdl [] = return ()
244 ifaceDeprecations if_hdl deprecations
245   = printForIface if_hdl (vcat [
246                 ptext SLIT("{-## __D"),
247                 vcat [ pprIE ie <+> doubleQuotes (ppr txt) <> semi | Deprecation ie txt <- deprecations ],
248                 ptext SLIT("##-}")
249        ])
250   where
251     pprIE (IEVar            n   ) = ppr n
252     pprIE (IEThingAbs       n   ) = ppr n
253     pprIE (IEThingAll       n   ) = hcat [ppr n, text "(..)"]
254     pprIE (IEThingWith      n ns) = ppr n <> parens (hcat (punctuate comma (map ppr ns)))
255     pprIE (IEModuleContents _   ) = empty
256 \end{code}
257
258 %************************************************************************
259 %*                                                                      *
260 \subsection{Instance declarations}
261 %*                                                                      *
262 %************************************************************************
263
264
265 \begin{code}                     
266 ifaceInstances :: Handle -> Bag InstInfo -> IO IdSet            -- The IdSet is the needed dfuns
267 ifaceInstances if_hdl inst_infos
268   | null togo_insts = return emptyVarSet                 
269   | otherwise       = hPutCol if_hdl pp_inst (sortLt lt_inst togo_insts) >>
270                       return needed_ids
271   where                          
272     togo_insts  = filter is_togo_inst (bagToList inst_infos)
273     needed_ids  = mkVarSet [dfun_id | InstInfo _ _ _ _ dfun_id _ _ _ <- togo_insts]
274     is_togo_inst (InstInfo _ _ _ _ dfun_id _ _ _) = isLocallyDefined dfun_id
275                                  
276     -------                      
277     lt_inst (InstInfo _ _ _ _ dfun_id1 _ _ _)
278             (InstInfo _ _ _ _ dfun_id2 _ _ _)
279       = getOccName dfun_id1 < getOccName dfun_id2
280         -- The dfuns are assigned names df1, df2, etc, in order of original textual
281         -- occurrence, and this makes as good a sort order as any
282
283     -------                      
284     pp_inst (InstInfo clas tvs tys theta dfun_id _ _ _)
285       = let                      
286                 -- The deNoteType is very important.   It removes all type
287                 -- synonyms from the instance type in interface files.
288                 -- That in turn makes sure that when reading in instance decls
289                 -- from interface files that the 'gating' mechanism works properly.
290                 -- Otherwise you could have
291                 --      type Tibble = T Int
292                 --      instance Foo Tibble where ...
293                 -- and this instance decl wouldn't get imported into a module
294                 -- that mentioned T but not Tibble.
295             forall_ty     = mkSigmaTy tvs (classesToPreds theta)
296                                       (deNoteType (mkDictTy clas tys))
297             renumbered_ty = tidyTopType forall_ty
298         in                       
299         hcat [ptext SLIT("instance "), pprType renumbered_ty, 
300                     ptext SLIT(" = "), ppr_unqual_name dfun_id, semi]
301 \end{code}
302
303
304 %************************************************************************
305 %*                                                                      *
306 \subsection{Printing values}
307 %*                                                                      *
308 %************************************************************************
309
310 \begin{code}
311 ifaceId :: (Id -> IdInfo)               -- This function "knows" the extra info added
312                                         -- by the STG passes.  Sigh
313
314             -> IdSet                    -- Set of Ids that are needed by earlier interface
315                                         -- file emissions.  If the Id isn't in this set, and isn't
316                                         -- exported, there's no need to emit anything
317             -> Bool                     -- True <=> recursive, so don't print unfolding
318             -> Id
319             -> CoreExpr                 -- The Id's right hand side
320             -> Maybe (SDoc, IdSet)      -- The emitted stuff, plus any *extra* needed Ids
321
322 ifaceId get_idinfo needed_ids is_rec id rhs
323   | not (id `elemVarSet` needed_ids ||          -- Needed [no id in needed_ids has omitIfaceSigForId]
324          (isUserExportedId id && not (omitIfaceSigForId id)))   -- or exported and not to be omitted
325   = Nothing             -- Well, that was easy!
326
327 ifaceId get_idinfo needed_ids is_rec id rhs
328   = ASSERT2( arity_matches_strictness, ppr id )
329     Just (hsep [sig_pretty, prag_pretty, char ';'], new_needed_ids)
330   where
331     core_idinfo = idInfo id
332     stg_idinfo  = get_idinfo id
333
334     ty_pretty  = pprType (idType id)
335     sig_pretty = hsep [ppr (getOccName id), dcolon, ty_pretty]
336
337     prag_pretty 
338      | opt_OmitInterfacePragmas = empty
339      | otherwise                = hsep [ptext SLIT("{-##"),
340                                         arity_pretty, 
341                                         caf_pretty,
342                                         cpr_pretty,
343                                         strict_pretty,
344                                         wrkr_pretty,
345                                         unfold_pretty, 
346                                         ptext SLIT("##-}")]
347
348     ------------  Arity  --------------
349     arity_info    = arityInfo stg_idinfo
350     arity_pretty  = ppArityInfo arity_info
351
352     ------------ Caf Info --------------
353     caf_pretty = ppCafInfo (cafInfo stg_idinfo)
354
355     ------------ CPR Info --------------
356     cpr_pretty = ppCprInfo (cprInfo core_idinfo)
357
358     ------------  Strictness  --------------
359     strict_info   = strictnessInfo core_idinfo
360     bottoming_fn  = isBottomingStrictness strict_info
361     strict_pretty = ppStrictnessInfo strict_info
362
363     ------------  Worker  --------------
364     work_info     = workerInfo core_idinfo
365     has_worker    = workerExists work_info
366     wrkr_pretty   = ppWorkerInfo work_info
367     HasWorker work_id wrap_arity = work_info
368
369
370     ------------  Occ info  --------------
371     loop_breaker  = isLoopBreaker (occInfo core_idinfo)
372
373     ------------  Unfolding  --------------
374     inline_pragma  = inlinePragInfo core_idinfo
375     dont_inline    = isNeverInlinePrag inline_pragma
376
377     unfold_pretty | show_unfold = ptext SLIT("__U") <> pprInlinePragInfo inline_pragma <+> pprIfaceUnfolding rhs
378                   | otherwise   = empty
379
380     show_unfold = not has_worker         &&     -- Not unnecessary
381                   not bottoming_fn       &&     -- Not necessary
382                   not dont_inline        &&
383                   not loop_breaker       &&
384                   rhs_is_small           &&     -- Small enough
385                   okToUnfoldInHiFile rhs        -- No casms etc
386
387     rhs_is_small = couldBeSmallEnoughToInline opt_UF_HiFileThreshold rhs
388
389     ------------  Specialisations --------------
390     spec_info   = specInfo core_idinfo
391     
392     ------------  Extra free Ids  --------------
393     new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
394                    | otherwise                = worker_ids      `unionVarSet`
395                                                 unfold_ids      `unionVarSet`
396                                                 spec_ids
397
398     worker_ids | has_worker && interestingId work_id = unitVarSet work_id
399                         -- Conceivably, the worker might come from
400                         -- another module
401                | otherwise                         = emptyVarSet
402
403     spec_ids = filterVarSet interestingId (rulesRhsFreeVars spec_info)
404
405     unfold_ids | show_unfold = find_fvs rhs
406                | otherwise   = emptyVarSet
407
408     find_fvs expr = exprSomeFreeVars interestingId expr
409
410     ------------ Sanity checking --------------
411         -- The arity of a wrapper function should match its strictness,
412         -- or else an importing module will get very confused indeed.
413     arity_matches_strictness = not has_worker || 
414                                wrap_arity == arityLowerBound arity_info
415     
416 interestingId id = isId id && isLocallyDefined id &&
417                    not (omitIfaceSigForId id)
418 \end{code}
419
420 \begin{code}
421 ifaceBinds :: Handle
422            -> IdSet             -- These Ids are needed already
423            -> [Id]              -- Ids used at code-gen time; they have better pragma info!
424            -> [CoreBind]        -- In dependency order, later depend on earlier
425            -> IO IdSet          -- Set of Ids actually spat out
426
427 ifaceBinds hdl needed_ids final_ids binds
428   = mapIO (printForIface hdl) (bagToList pretties)      >>
429     hPutStr hdl "\n"                                    >>
430     return emitted
431   where
432     final_id_map  = listToUFM [(id,id) | id <- final_ids]
433     get_idinfo id = case lookupUFM final_id_map id of
434                         Just id' -> idInfo id'
435                         Nothing  -> pprTrace "ifaceBinds not found:" (ppr id) $
436                                     idInfo id
437
438     (pretties, emitted) = go needed_ids (reverse binds) emptyBag emptyVarSet 
439                         -- Reverse so that later things will 
440                         -- provoke earlier ones to be emitted
441     go needed [] pretties emitted
442         | not (isEmptyVarSet needed) = pprTrace "ifaceBinds: free vars:" 
443                                           (sep (map ppr (varSetElems needed)))
444                                        (pretties, emitted)
445         | otherwise                  = (pretties, emitted)
446
447     go needed (NonRec id rhs : binds) pretties emitted
448         = case ifaceId get_idinfo needed False id rhs of
449                 Nothing               -> go needed binds pretties emitted
450                 Just (pretty, extras) -> let
451                         needed' = (needed `unionVarSet` extras) `delVarSet` id
452                         -- 'extras' can include the Id itself via a rule
453                         emitted' = emitted `extendVarSet` id
454                         in
455                         go needed' binds (pretty `consBag` pretties) emitted'
456
457         -- Recursive groups are a bit more of a pain.  We may only need one to
458         -- start with, but it may call out the next one, and so on.  So we
459         -- have to look for a fixed point.
460     go needed (Rec pairs : binds) pretties emitted
461         = go needed' binds pretties' emitted' 
462         where
463           (new_pretties, new_emitted, extras) = go_rec needed pairs
464           pretties' = new_pretties `unionBags` pretties
465           needed'   = (needed `unionVarSet` extras) `minusVarSet` mkVarSet (map fst pairs) 
466           emitted'  = emitted `unionVarSet` new_emitted
467
468     go_rec :: IdSet -> [(Id,CoreExpr)] -> (Bag SDoc, IdSet, IdSet)
469     go_rec needed pairs
470         | null pretties = (emptyBag, emptyVarSet, emptyVarSet)
471         | otherwise     = (more_pretties `unionBags`   listToBag pretties, 
472                            more_emitted  `unionVarSet` mkVarSet emitted,
473                            more_extras   `unionVarSet` extras)
474         where
475           maybes               = map do_one pairs
476           emitted              = [id   | ((id,_), Just _)  <- pairs `zip` maybes]
477           reduced_pairs        = [pair | (pair,   Nothing) <- pairs `zip` maybes]
478           (pretties, extras_s) = unzip (catMaybes maybes)
479           extras               = unionVarSets extras_s
480           (more_pretties, more_emitted, more_extras) = go_rec extras reduced_pairs
481
482           do_one (id,rhs) = ifaceId get_idinfo needed True id rhs
483 \end{code}
484
485
486 %************************************************************************
487 %*                                                                      *
488 \subsection{Random small things}
489 %*                                                                      *
490 %************************************************************************
491
492 \begin{code}
493 ifaceTyCons hdl tycons   = hPutCol hdl upp_tycon (sortLt (<) (filter (for_iface_name . getName) tycons))
494 ifaceClasses hdl classes = hPutCol hdl upp_class (sortLt (<) (filter (for_iface_name . getName) classes))
495
496 for_iface_name name = isLocallyDefined name && 
497                       not (isWiredInName name)
498
499 upp_tycon tycon = ifaceTyCon tycon
500 upp_class clas  = ifaceClass clas
501 \end{code}
502
503
504 \begin{code}
505 ifaceTyCon :: TyCon -> SDoc
506 ifaceTyCon tycon
507   | isSynTyCon tycon
508   = hsep [ ptext SLIT("type"),
509            ppr (getName tycon),
510            pprTyVarBndrs tyvars,
511            ptext SLIT("="),
512            ppr ty,
513            semi
514     ]
515   where
516     (tyvars, ty) = getSynTyConDefn tycon
517
518 ifaceTyCon tycon
519   | isAlgTyCon tycon
520   = hsep [ ptext keyword,
521            ppr_decl_class_context (tyConTheta tycon),
522            ppr (getName tycon),
523            pprTyVarBndrs (tyConTyVars tycon),
524            ptext SLIT("="),
525            hsep (punctuate (ptext SLIT(" | ")) (map ppr_con (tyConDataCons tycon))),
526            semi
527     ]
528   where
529     keyword | isNewTyCon tycon = SLIT("newtype")
530             | otherwise        = SLIT("data")
531
532     tyvars = tyConTyVars tycon
533
534     ppr_con data_con 
535         | null field_labels
536         = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
537           hsep [  ppr_ex ex_tyvars ex_theta,
538                   ppr name,
539                   hsep (map ppr_arg_ty (strict_marks `zip` arg_tys))
540                 ]
541
542         | otherwise
543         = hsep [  ppr_ex ex_tyvars ex_theta,
544                   ppr name,
545                   braces $ hsep $ punctuate comma (map ppr_field (strict_marks `zip` field_labels))
546                 ]
547           where
548            (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
549            field_labels   = dataConFieldLabels data_con
550            strict_marks   = dataConStrictMarks data_con
551            name           = getName            data_con
552
553     ppr_ex [] ex_theta = ASSERT( null ex_theta ) empty
554     ppr_ex ex_tvs ex_theta = ptext SLIT("__forall") <+> brackets (pprTyVarBndrs ex_tvs)
555                              <+> pprIfaceClasses ex_theta <+> ptext SLIT("=>")
556
557     ppr_arg_ty (strict_mark, ty) = ppr_strict_mark strict_mark <> pprParendType ty
558
559     ppr_strict_mark NotMarkedStrict        = empty
560     ppr_strict_mark (MarkedUnboxed _ _)    = ptext SLIT("! ! ")
561     ppr_strict_mark MarkedStrict           = ptext SLIT("! ")
562
563     ppr_field (strict_mark, field_label)
564         = hsep [ ppr (fieldLabelName field_label),
565                   dcolon,
566                   ppr_strict_mark strict_mark <> pprParendType (fieldLabelType field_label)
567                 ]
568
569 ifaceTyCon tycon
570   = pprPanic "pprIfaceTyDecl" (ppr tycon)
571
572 ifaceClass clas
573   = hsep [ptext SLIT("class"),
574            ppr_decl_class_context sc_theta,
575            ppr clas,                    -- Print the name
576            pprTyVarBndrs clas_tyvars,
577            pprFundeps clas_fds,
578            pp_ops,
579            semi
580           ]
581    where
582      (clas_tyvars, clas_fds, sc_theta, _, op_stuff) = classExtraBigSig clas
583
584      pp_ops | null op_stuff  = empty
585             | otherwise      = hsep [ptext SLIT("where"),
586                                      braces (hsep (punctuate semi (map ppr_classop op_stuff)))
587                                ]
588
589      ppr_classop (sel_id, dm_id, explicit_dm)
590         = ASSERT( sel_tyvars == clas_tyvars)
591           hsep [ppr (getOccName sel_id),
592                 if explicit_dm then equals else empty,
593                 dcolon,
594                 ppr op_ty
595           ]
596         where
597           (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
598
599 ppr_decl_context :: ThetaType -> SDoc
600 ppr_decl_context []    = empty
601 ppr_decl_context theta = pprIfaceTheta theta <+> ptext SLIT(" =>")
602
603 ppr_decl_class_context :: ClassContext -> SDoc
604 ppr_decl_class_context []    = empty
605 ppr_decl_class_context ctxt  = pprIfaceClasses ctxt <+> ptext SLIT(" =>")
606
607 pprIfaceTheta :: ThetaType -> SDoc      -- Use braces rather than parens in interface files
608 pprIfaceTheta []    = empty
609 pprIfaceTheta theta = braces (hsep (punctuate comma [pprIfacePred p | p <- theta]))
610
611 -- ZZ - not sure who uses this - i.e. whether IParams really show up or not
612 -- (it's not used to print normal value signatures)
613 pprIfacePred :: PredType -> SDoc
614 pprIfacePred (Class clas tys) = pprConstraint clas tys
615 pprIfacePred (IParam n ty)    = char '?' <> ppr n <+> ptext SLIT("::") <+> ppr ty
616
617 pprIfaceClasses :: ClassContext -> SDoc
618 pprIfaceClasses []    = empty
619 pprIfaceClasses theta = braces (hsep (punctuate comma [pprConstraint c tys | (c,tys) <- theta]))
620 \end{code}
621
622 %************************************************************************
623 %*                                                                      *
624 \subsection{Random small things}
625 %*                                                                      *
626 %************************************************************************
627
628 When printing export lists, we print like this:
629         Avail   f               f
630         AvailTC C [C, x, y]     C(x,y)
631         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
632
633 \begin{code}
634 upp_avail :: AvailInfo -> SDoc
635 upp_avail (Avail name)      = pprOccName (getOccName name)
636 upp_avail (AvailTC name []) = empty
637 upp_avail (AvailTC name ns) = hcat [pprOccName (getOccName name), bang, upp_export ns']
638                             where
639                               bang | name `elem` ns = empty
640                                    | otherwise      = char '|'
641                               ns' = filter (/= name) ns
642
643 upp_export :: [Name] -> SDoc
644 upp_export []    = empty
645 upp_export names = braces (hsep (map (pprOccName . getOccName) names)) 
646
647 upp_fixity :: (Name, Fixity) -> SDoc
648 upp_fixity (name, fixity) = hsep [ptext SLIT("0"), ppr fixity, ppr name, semi]
649         -- Dummy version number!
650
651 ppr_unqual_name :: NamedThing a => a -> SDoc            -- Just its occurrence name
652 ppr_unqual_name name = pprOccName (getOccName name)
653 \end{code}
654
655
656 %************************************************************************
657 %*                                                                      *
658 \subsection{Comparisons}
659 %*                                                                      *
660 %************************************************************************
661                                  
662
663 The various sorts above simply prevent unnecessary "wobbling" when
664 things change that don't have to.  We therefore compare lexically, not
665 by unique
666
667 \begin{code}
668 lt_avail :: AvailInfo -> AvailInfo -> Bool
669
670 a1 `lt_avail` a2 = availName a1 `lt_name` availName a2
671
672 lt_name :: Name -> Name -> Bool
673 n1 `lt_name` n2 = nameRdrName n1 < nameRdrName n2
674
675 lt_lexical :: NamedThing a => a -> a -> Bool
676 lt_lexical a1 a2 = getName a1 `lt_name` getName a2
677
678 lt_imp_vers :: ImportVersion a -> ImportVersion a -> Bool
679 lt_imp_vers (m1,_,_,_,_) (m2,_,_,_,_) = m1 < m2
680
681 sort_versions vs = sortLt lt_vers vs
682
683 lt_vers :: LocalVersion Name -> LocalVersion Name -> Bool
684 lt_vers (n1,v1) (n2,v2) = n1 `lt_name` n2
685 \end{code}
686
687
688 \begin{code}
689 hPutCol :: Handle 
690         -> (a -> SDoc)
691         -> [a]
692         -> IO ()
693 hPutCol hdl fmt xs = mapIO (printForIface hdl . fmt) xs
694
695 mapIO :: (a -> IO b) -> [a] -> IO ()
696 mapIO f []     = return ()
697 mapIO f (x:xs) = f x >> mapIO f xs
698 \end{code}