2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
4 \section[MkIface]{Print an interface for a module}
7 #include "HsVersions.h"
22 IMPORT_1_3(IO(Handle,hPutStr,openFile,hClose,IOMode(..)))
24 import Bag ( bagToList )
25 import Class ( GenClass(..){-instance NamedThing-}, GenClassOp(..) )
26 import CmdLineOpts ( opt_ProduceHi )
27 import FieldLabel ( FieldLabel{-instance NamedThing-} )
28 import FiniteMap ( emptyFM, addToFM, lookupFM, fmToList, eltsFM, FiniteMap )
30 import Id ( idType, dataConRawArgTys, dataConFieldLabels,
31 dataConStrictMarks, StrictnessMark(..),
32 GenId{-instance NamedThing/Outputable-}
34 import Maybes ( maybeToBool )
35 import Name ( origName, nameOf, moduleOf,
36 exportFlagOn, nameExportFlag, ExportFlag(..),
37 isLexSym, isLocallyDefined, isWiredInName,
38 RdrName(..){-instance Outputable-},
39 OrigName(..){-instance Ord-},
40 Name{-instance NamedThing-}
42 import ParseUtils ( UsagesMap(..), VersionsMap(..) )
43 import PprEnv -- not sure how much...
44 import PprStyle ( PprStyle(..) )
45 import PprType -- most of it (??)
46 --import PrelMods ( modulesWithBuiltins )
47 import PrelInfo ( builtinNameInfo )
48 import Pretty ( prettyToUn )
49 import Unpretty -- ditto
50 import RnHsSyn ( isRnConstr, SYN_IE(RenamedHsModule), RnName{-instance NamedThing-} )
51 import TcModule ( SYN_IE(TcIfaceInfo) )
52 import TcInstUtil ( InstInfo(..) )
53 import TyCon ( TyCon(..){-instance NamedThing-}, NewOrData(..) )
54 import Type ( mkSigmaTy, mkDictTy, getAppTyCon, splitForAllTy )
55 import Util ( sortLt, removeDups, zipWithEqual, zipWith3Equal, assertPanic, panic{-ToDo:rm-}, pprTrace{-ToDo:rm-} )
57 uppSemid x = uppBeside (prettyToUn (ppr PprInterface x)) uppSemi -- micro util
58 ppr_ty ty = prettyToUn (pprType PprInterface ty)
59 ppr_tyvar tv = prettyToUn (ppr PprInterface tv)
61 = case (origName "ppr_name" n) of { OrigName m s ->
62 uppBesides [uppPStr m, uppChar '.', uppPStr s] }
65 We have a function @startIface@ to open the output file and put
66 (something like) ``interface Foo'' in it. It gives back a handle
67 for subsequent additions to the interface file.
69 We then have one-function-per-block-of-interface-stuff, e.g.,
70 @ifaceExportList@ produces the @__exports__@ section; it appends
71 to the handle provided by @startIface@.
75 -> IO (Maybe Handle) -- Nothing <=> don't do an interface
76 endIface :: Maybe Handle -> IO ()
87 -> (Name -> ExportFlag)
98 ifaceDecls :: Maybe Handle
99 -> TcIfaceInfo -- info produced by typechecker, for interfaces
103 -> TcIfaceInfo -- as above
108 ifacePragmas = panic "ifacePragmas" -- stub
113 = case opt_ProduceHi of
114 Nothing -> return Nothing -- not producing any .hi file
116 openFile fn WriteMode >>= \ if_hdl ->
117 hPutStr if_hdl ("interface "++ _UNPK_ mod) >>
120 endIface Nothing = return ()
121 endIface (Just if_hdl) = hPutStr if_hdl "\n" >> hClose if_hdl
125 ifaceUsages Nothing{-no iface handle-} _ = return ()
127 ifaceUsages (Just if_hdl) usages
131 = hPutStr if_hdl "\n__usages__\n" >>
132 hPutStr if_hdl (uppShow 0 (uppAboves (map upp_uses usages_list)))
134 usages_list = fmToList usages -- NO: filter has_no_builtins (...)
136 -- has_no_builtins (m, _)
137 -- = m `notElem` modulesWithBuiltins
138 -- -- Don't *have* to do this; save gratuitous spillage in
139 -- -- every interface. Could be flag-controlled...
141 upp_uses (m, (mv, versions))
142 = uppBesides [uppPStr m, uppSP, uppInt mv, uppPStr SLIT(" :: "),
143 upp_versions (fmToList versions), uppSemi]
146 = uppIntersperse uppSP [ uppCat [uppPStr n, uppInt v] | (n,v) <- nvs ]
150 ifaceVersions Nothing{-no iface handle-} _ = return ()
152 ifaceVersions (Just if_hdl) version_info
156 = hPutStr if_hdl "\n__versions__\n" >>
157 hPutStr if_hdl (uppShow 0 (upp_versions version_list))
158 -- NB: when compiling Prelude.hs, this will spew out
159 -- stuff for [], (), (,), etc. [i.e., builtins], which
160 -- we'd rather it didn't. The version-mangling in
161 -- the driver will ignore them.
163 version_list = fmToList version_info
166 = uppAboves [ uppPStr n | (n,v) <- nvs ]
170 ifaceInstanceModules Nothing{-no iface handle-} _ = return ()
171 ifaceInstanceModules (Just _) [] = return ()
173 ifaceInstanceModules (Just if_hdl) imods
174 = hPutStr if_hdl "\n__instance_modules__\n" >>
175 hPutStr if_hdl (uppShow 0 (uppCat (map uppPStr imods)))
178 Export list: grab the Names of things that are marked Exported, sort
179 (so the interface file doesn't ``wobble'' from one compilation to the
180 next...), and print. Note that the ``module'' now contains all the
181 imported things that we are dealing with, thus including any entities
182 that we are re-exporting from somewhere else.
184 ifaceExportList Nothing{-no iface handle-} _ _ = return ()
186 ifaceExportList (Just if_hdl)
187 export_fn -- sadly, just the HsModule isn't enough,
188 -- because it will have no record of exported
190 (HsModule _ _ _ _ _ typedecls _ classdecls _ _ _ binds sigs _)
192 (vals_wired, tcs_wired)
193 = case builtinNameInfo of { ((vals_fm,tcs_fm), _, _) ->
194 (eltsFM vals_fm, eltsFM tcs_fm) }
196 name_flag_pairs :: FiniteMap OrigName ExportFlag
198 = foldr (from_wired True{-val-ish-})
199 (foldr (from_wired False{-tycon-ish-})
203 (from_binds binds emptyFM{-init accum-})
210 sorted_pairs = sortLt lexical_lt (fmToList name_flag_pairs)
213 hPutStr if_hdl "\n__exports__\n" >>
214 hPutStr if_hdl (uppShow 0 (uppAboves (map upp_pair sorted_pairs)))
216 from_ty (TyData _ n _ _ _ _ _) acc = maybe_add acc n
217 from_ty (TyNew _ n _ _ _ _ _) acc = maybe_add acc n
218 from_ty (TySynonym n _ _ _) acc = maybe_add acc n
220 from_cls (ClassDecl _ n _ _ _ _ _) acc = maybe_add acc n
222 from_sig (Sig n _ _ _) acc = maybe_add acc n
224 from_binds bs acc = maybe_add_list acc (collectTopLevelBinders bs)
227 from_wired is_val_ish rn acc
228 | on_in_acc = acc -- if already in acc (presumably from real decl),
229 -- don't take the dubious export flag from the
231 | is_val_ish && isRnConstr rn
232 = acc -- these things don't cause export-ery
233 | exportFlagOn ef = addToFM acc on ef
238 on = origName "from_wired" n
239 (OrigName _ str) = on
240 on_in_acc = maybeToBool (lookupFM acc on)
243 maybe_add :: FiniteMap OrigName ExportFlag -> RnName -> FiniteMap OrigName ExportFlag
246 | on_in_acc = trace "maybe_add?" acc -- surprising!
247 | exportFlagOn ef = addToFM acc on ef
250 ef = nameExportFlag n
252 on = origName "maybe_add" n
253 on_in_acc = maybeToBool (lookupFM acc on)
256 maybe_add_list acc [] = acc
257 maybe_add_list acc (n:ns) = maybe_add (maybe_add_list acc ns) n
260 lexical_lt (n1,_) (n2,_) = n1 < n2
263 upp_pair (OrigName m n, ef)
264 = uppBesides [uppPStr m, uppSP, uppPStr n, uppSP, upp_export ef]
266 upp_export ExportAll = uppPStr SLIT("(..)")
267 upp_export ExportAbs = uppNil
271 ifaceFixities Nothing{-no iface handle-} _ = return ()
273 ifaceFixities (Just if_hdl) (HsModule _ _ _ _ fixities _ _ _ _ _ _ _ _ _)
275 pp_fixities = foldr go [] fixities
277 if null pp_fixities then
280 hPutStr if_hdl "\n__fixities__\n" >>
281 hPutStr if_hdl (uppShow 0 (uppAboves pp_fixities))
283 go (InfixL v i) acc = (if isLocallyDefined v then (:) (print_fix "l" i v) else id) acc
284 go (InfixR v i) acc = (if isLocallyDefined v then (:) (print_fix "r" i v) else id) acc
285 go (InfixN v i) acc = (if isLocallyDefined v then (:) (print_fix "" i v) else id) acc
287 print_fix suff prec var
288 = uppBesides [uppPStr SLIT("infix"), uppStr suff, uppSP, uppInt prec, uppSP, ppr_name var, uppSemi]
292 non_wired x = not (isWiredInName (getName x)) --ToDo:move?
294 ifaceDecls Nothing{-no iface handle-} _ = return ()
296 ifaceDecls (Just if_hdl) (vals, tycons, classes, _)
297 = ASSERT(all isLocallyDefined vals)
298 ASSERT(all isLocallyDefined tycons)
299 ASSERT(all isLocallyDefined classes)
301 nonwired_classes = filter non_wired classes
302 nonwired_tycons = filter non_wired tycons
303 nonwired_vals = filter non_wired vals
305 lt_lexical a b = origName "lt_lexical" a < origName "lt_lexical" b
307 sorted_classes = sortLt lt_lexical nonwired_classes
308 sorted_tycons = sortLt lt_lexical nonwired_tycons
309 sorted_vals = sortLt lt_lexical nonwired_vals
311 if (null sorted_classes && null sorted_tycons && null sorted_vals) then
312 -- You could have a module with just (re-)exports/instances in it
315 hPutStr if_hdl "\n__declarations__\n" >>
316 hPutStr if_hdl (uppShow 0 (uppAboves [
317 uppAboves (map ppr_class sorted_classes),
318 uppAboves (map ppr_tycon sorted_tycons),
319 uppAboves [ppr_val v (idType v) | v <- sorted_vals]]))
323 ifaceInstances Nothing{-no iface handle-} _ = return ()
325 ifaceInstances (Just if_hdl) (_, _, _, insts)
327 togo_insts = filter is_togo_inst (bagToList insts)
329 sorted_insts = sortLt lt_inst togo_insts
331 if null togo_insts then
334 hPutStr if_hdl "\n__instances__\n" >>
335 hPutStr if_hdl (uppShow 0 (uppAboves (map pp_inst sorted_insts)))
337 is_togo_inst (InstInfo clas _ ty _ _ _ _ _ from_here _ _ _)
338 = from_here -- && ...
341 lt_inst (InstInfo clas1 _ ty1 _ _ _ _ _ _ _ _ _)
342 (InstInfo clas2 _ ty2 _ _ _ _ _ _ _ _ _)
344 tycon1 = fst (getAppTyCon ty1)
345 tycon2 = fst (getAppTyCon ty2)
347 case (origName "lt_inst" clas1 `cmp` origName "lt_inst" clas2) of
350 EQ_ -> origName "lt_inst2" tycon1 < origName "lt_inst2" tycon2
353 pp_inst (InstInfo clas tvs ty theta _ _ _ _ _ _ _ _)
355 forall_ty = mkSigmaTy tvs theta (mkDictTy clas ty)
356 renumbered_ty = initNmbr (nmbrType forall_ty)
358 case (splitForAllTy renumbered_ty) of { (rtvs, rrho_ty) ->
359 uppBesides [uppPStr SLIT("instance "), ppr_forall rtvs, ppr_ty rrho_ty, uppSemi] }
362 %************************************************************************
364 \subsection{Printing tycons, classes, ...}
366 %************************************************************************
369 ppr_class :: Class -> Unpretty
372 = --pprTrace "ppr_class:" (ppr PprDebug c) $
373 case (initNmbr (nmbrClass c)) of { -- renumber it!
374 Class _ n tyvar super_classes sdsels ops sels defms insts links ->
376 uppCat [uppPStr SLIT("class"), ppr_context tyvar super_classes,
377 ppr_name n, ppr_tyvar tyvar,
380 else uppCat [uppStr "where {", uppCat (map ppr_op ops), uppStr "};"]]
383 ppr_context :: TyVar -> [Class] -> Unpretty
385 ppr_context tv [] = uppNil
386 -- ppr_context tv [sc] = uppBeside (ppr_assert tv sc) (uppPStr SLIT(" =>"))
387 ppr_context tv super_classes
388 = uppBesides [uppStr "{{",
389 uppIntersperse upp'SP{-'-} (map (ppr_assert tv) super_classes),
392 ppr_assert tv (Class _ n _ _ _ _ _ _ _ _) = uppCat [ppr_name n, ppr_tyvar tv]
394 clas_mod = moduleOf (origName "ppr_class" c)
396 ppr_op (ClassOp o _ ty) = pp_sig (Qual clas_mod o) ty
400 ppr_val v ty -- renumber the type first!
401 = --pprTrace "ppr_val:" (ppr PprDebug v) $
402 pp_sig v (initNmbr (nmbrType ty))
405 = case (splitForAllTy ty) of { (tvs, rho_ty) ->
406 uppBesides [ppr_name op, uppPStr SLIT(" :: "), ppr_forall tvs, ppr_ty rho_ty, uppSemi] }
408 ppr_forall [] = uppNil
409 ppr_forall tvs = uppBesides [ uppStr "__forall__ [", uppInterleave uppComma (map ppr_tyvar tvs), uppStr "] " ]
414 = --pprTrace "ppr_tycon:" (ppr PprDebug tycon) $
415 ppr_tc (initNmbr (nmbrTyCon tycon))
417 ------------------------
418 ppr_tc (PrimTyCon _ n _ _)
419 = uppCat [ uppStr "{- data", ppr_name n, uppStr " *built-in* -}" ]
422 = uppCat [ uppStr "{- data", ppr_name FunTyCon, uppStr " *built-in* -}" ]
424 ppr_tc (TupleTyCon _ n _)
425 = uppCat [ uppStr "{- ", ppr_name n, uppStr "-}" ]
427 ppr_tc (SynTyCon _ n _ _ tvs expand)
429 pp_tyvars = map ppr_tyvar tvs
431 uppBesides [uppPStr SLIT("type "), ppr_name n, uppSP, uppIntersperse uppSP pp_tyvars,
432 uppPStr SLIT(" = "), ppr_ty expand, uppSemi]
434 ppr_tc this_tycon@(DataTyCon u n k tvs ctxt cons derivings data_or_new)
435 = uppCat [pp_data_or_new,
438 uppIntersperse uppSP (map ppr_tyvar tvs),
439 uppEquals, pp_condecls,
441 -- NB: we do not print deriving info in interfaces
443 pp_data_or_new = case data_or_new of
444 DataType -> uppPStr SLIT("data")
445 NewType -> uppPStr SLIT("newtype")
447 ppr_context [] = uppNil
448 -- ppr_context [(c,t)] = uppCat [ppr_name c, ppr_ty t, uppPStr SLIT("=>")]
450 = uppBesides[uppStr "{{",
451 uppInterleave uppComma [uppCat [ppr_name c, ppr_ty t] | (c,t) <- cs],
452 uppStr "}}", uppPStr SLIT(" =>")]
458 uppCat ((ppr_con c) : (map ppr_next_con cs))
460 ppr_next_con con = uppCat [uppChar '|', ppr_con con]
464 con_arg_tys = dataConRawArgTys con
465 labels = dataConFieldLabels con -- none if not a record
466 strict_marks = dataConStrictMarks con
468 uppCat [ppr_name con, ppr_fields labels strict_marks con_arg_tys]
470 ppr_fields labels strict_marks con_arg_tys
471 = if null labels then -- not a record thingy
472 uppIntersperse uppSP (zipWithEqual "ppr_fields" ppr_bang_ty strict_marks con_arg_tys)
474 uppCat [ uppChar '{',
475 uppInterleave uppComma (zipWith3Equal "ppr_field" ppr_field labels strict_marks con_arg_tys),
479 = uppBeside (case b of { MarkedStrict -> uppChar '!'; _ -> uppNil })
480 (prettyToUn (pprParendType PprInterface t))
483 = uppBesides [ppr_name l, uppPStr SLIT(" :: "),
484 case b of { MarkedStrict -> uppChar '!'; _ -> uppNil },