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