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