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