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