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