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