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