%
-% (c) The GRASP/AQUA Project, Glasgow University, 1993-1995
+% (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
%
\section[MkIface]{Print an interface for a module}
\begin{code}
#include "HsVersions.h"
-module MkIface {-( mkInterface )-} where
-
-import Ubiq{-uitous-}
-
-import Bag ( emptyBag, snocBag, bagToList )
-import Class ( GenClass{-instance NamedThing-} )
+module MkIface (
+ startIface, endIface,
+ ifaceUsages,
+ ifaceVersions,
+ ifaceExportList,
+ ifaceFixities,
+ ifaceInstanceModules,
+ ifaceDecls,
+ ifaceInstances,
+ ifacePragmas
+ ) where
+
+IMP_Ubiq(){-uitous-}
+IMPORT_1_3(IO(Handle,hPutStr,openFile,hClose,IOMode(..)))
+
+import Bag ( bagToList )
+import Class ( GenClass(..){-instance NamedThing-}, GenClassOp(..) )
import CmdLineOpts ( opt_ProduceHi )
+import FieldLabel ( FieldLabel{-instance NamedThing-} )
+import FiniteMap ( emptyFM, addToFM, lookupFM, fmToList, eltsFM, FiniteMap )
import HsSyn
-import Id ( GenId{-instance NamedThing/Outputable-} )
-import Name ( nameOrigName, origName,
+import Id ( idType, dataConRawArgTys, dataConFieldLabels, isDataCon,
+ dataConStrictMarks, StrictnessMark(..),
+ GenId{-instance NamedThing/Outputable-}
+ )
+import Maybes ( maybeToBool )
+import Name ( origName, nameOf, moduleOf,
exportFlagOn, nameExportFlag, ExportFlag(..),
- ltLexical, isExported,
- RdrName{-instance Outputable-}
+ isLexSym, isLexCon, isLocallyDefined, isWiredInName,
+ RdrName(..){-instance Outputable-},
+ OrigName(..){-instance Ord-},
+ Name{-instance NamedThing-}
)
+import ParseUtils ( UsagesMap(..), VersionsMap(..) )
+import PprEnv -- not sure how much...
import PprStyle ( PprStyle(..) )
-import PprType ( pprType, TyCon{-instance Outputable-}, GenClass{-ditto-} )
-import Pretty -- quite a bit
-import RnHsSyn ( RenamedHsModule(..), RnName{-instance NamedThing-} )
-import RnIfaces ( VersionInfo(..) )
-import TcModule ( TcIfaceInfo(..) )
+import PprType -- most of it (??)
+--import PrelMods ( modulesWithBuiltins )
+import PrelInfo ( builtinValNamesMap, builtinTcNamesMap )
+import Pretty ( prettyToUn )
+import Unpretty -- ditto
+import RnHsSyn ( isRnConstr, SYN_IE(RenamedHsModule), RnName(..) )
+import RnUtils ( SYN_IE(RnEnv), pprRnEnv{-ToDo:rm-} )
+import TcModule ( SYN_IE(TcIfaceInfo) )
import TcInstUtil ( InstInfo(..) )
-import TyCon ( TyCon{-instance NamedThing-} )
-import Type ( mkSigmaTy, mkDictTy, getAppTyCon )
-import Util ( sortLt, assertPanic )
-
-ppSemid x = ppBeside (ppr PprInterface x) ppSemi -- micro util
+import TyCon ( TyCon(..){-instance NamedThing-}, NewOrData(..) )
+import Type ( mkSigmaTy, mkDictTy, getAppTyCon, splitForAllTy )
+import Util ( sortLt, removeDups, zipWithEqual, zipWith3Equal, assertPanic, panic{-ToDo:rm-}, pprTrace{-ToDo:rm-} )
+
+uppSemid x = uppBeside (prettyToUn (ppr PprInterface x)) uppSemi -- micro util
+ppr_ty ty = prettyToUn (pprType PprInterface ty)
+ppr_tyvar tv = prettyToUn (ppr PprInterface tv)
+ppr_name n
+ = case (origName "ppr_name" n) of { OrigName m s ->
+ uppBesides [uppPStr m, uppChar '.', uppPStr s] }
\end{code}
We have a function @startIface@ to open the output file and put
-(something like) ``interface Foo N'' in it. It gives back a handle
+(something like) ``interface Foo'' in it. It gives back a handle
for subsequent additions to the interface file.
We then have one-function-per-block-of-interface-stuff, e.g.,
startIface :: Module
-> IO (Maybe Handle) -- Nothing <=> don't do an interface
endIface :: Maybe Handle -> IO ()
+ifaceUsages
+ :: Maybe Handle
+ -> UsagesMap
+ -> IO ()
ifaceVersions
:: Maybe Handle
- -> VersionInfo
+ -> VersionsMap
-> IO ()
ifaceExportList
:: Maybe Handle
- -> RenamedHsModule
+ -> (Name -> ExportFlag, ([(Name,ExportFlag)], [(Name,ExportFlag)]))
+ -> RnEnv
-> IO ()
ifaceFixities
:: Maybe Handle
:: Maybe Handle
-> TcIfaceInfo -- as above
-> IO ()
---ifacePragmas
+ifacePragmas
+ :: Maybe Handle
+ -> IO ()
+ifacePragmas = panic "ifacePragmas" -- stub
\end{code}
\begin{code}
Nothing -> return Nothing -- not producing any .hi file
Just fn ->
openFile fn WriteMode >>= \ if_hdl ->
- hPutStr if_hdl ("interface "++ _UNPK_ mod ++" 1\n") >>
+ hPutStr if_hdl ("interface "++ _UNPK_ mod) >>
return (Just if_hdl)
endIface Nothing = return ()
\end{code}
\begin{code}
+ifaceUsages Nothing{-no iface handle-} _ = return ()
+
+ifaceUsages (Just if_hdl) usages
+ | null usages_list
+ = return ()
+ | otherwise
+ = hPutStr if_hdl "\n__usages__\n" >>
+ hPutStr if_hdl (uppShow 0 (uppAboves (map upp_uses usages_list)))
+ where
+ usages_list = fmToList usages -- NO: filter has_no_builtins (...)
+
+-- has_no_builtins (m, _)
+-- = m `notElem` modulesWithBuiltins
+-- -- Don't *have* to do this; save gratuitous spillage in
+-- -- every interface. Could be flag-controlled...
+
+ upp_uses (m, (mv, versions))
+ = uppBesides [uppPStr m, uppSP, uppInt mv, uppPStr SLIT(" :: "),
+ upp_versions (fmToList versions), uppSemi]
+
+ upp_versions nvs
+ = uppIntersperse uppSP [ uppCat [uppPStr n, uppInt v] | (n,v) <- nvs ]
+\end{code}
+
+\begin{code}
ifaceVersions Nothing{-no iface handle-} _ = return ()
ifaceVersions (Just if_hdl) version_info
- = hPutStr if_hdl "__versions__\nFoo(1)" -- a stub, obviously
+ | null version_list
+ = return ()
+ | otherwise
+ = hPutStr if_hdl "\n__versions__\n" >>
+ hPutStr if_hdl (uppShow 0 (upp_versions version_list))
+ -- NB: when compiling Prelude.hs, this will spew out
+ -- stuff for [], (), (,), etc. [i.e., builtins], which
+ -- we'd rather it didn't. The version-mangling in
+ -- the driver will ignore them.
+ where
+ version_list = fmToList version_info
+
+ upp_versions nvs
+ = uppAboves [ uppPStr n | (n,v) <- nvs ]
\end{code}
\begin{code}
ifaceInstanceModules (Just if_hdl) imods
= hPutStr if_hdl "\n__instance_modules__\n" >>
- hPutStr if_hdl (ppShow 100 (ppCat (map ppPStr imods)))
+ hPutStr if_hdl (uppShow 0 (uppCat (map uppPStr imods)))
\end{code}
Export list: grab the Names of things that are marked Exported, sort
(so the interface file doesn't ``wobble'' from one compilation to the
-next...), and print. Note that the ``module'' now contains all the
-imported things that we are dealing with, thus including any entities
-that we are re-exporting from somewhere else.
+next...), and print. We work from the renamer's final ``RnEnv'',
+which has all the names we might possibly be interested in.
+(Note that the ``module X'' export items can cause a lot of grief.)
\begin{code}
-ifaceExportList Nothing{-no iface handle-} _ = return ()
+ifaceExportList Nothing{-no iface handle-} _ _ = return ()
ifaceExportList (Just if_hdl)
- (HsModule _ _ _ _ _ typedecls _ classdecls _ _ _ binds sigs _)
+ (export_fn, (dotdot_vals, dotdot_tcs))
+ rn_env@((qual, unqual, tc_qual, tc_unqual), _)
= let
- name_flag_pairs :: Bag (Name, ExportFlag)
+ name_flag_pairs :: FiniteMap OrigName ExportFlag
name_flag_pairs
- = foldr from_ty
- (foldr from_cls
- (foldr from_sig
- (from_binds binds emptyBag{-init accum-})
- sigs)
- classdecls)
- typedecls
-
- sorted_pairs = sortLt lexical_lt (bagToList name_flag_pairs)
+ = foldr (from_wired True{-val-ish-})
+ (foldr (from_wired False{-tycon-ish-})
+ (foldr (from_dotdot True{-val-ish-})
+ (foldr (from_dotdot False{-tycon-ish-})
+ (foldr from_val
+ (foldr from_val
+ (foldr from_tc
+ (foldr from_tc emptyFM{-init accum-}
+ (eltsFM tc_unqual))
+ (eltsFM tc_qual))
+ (eltsFM unqual))
+ (eltsFM qual))
+ dotdot_tcs)
+ dotdot_vals)
+ (eltsFM builtinTcNamesMap))
+ (eltsFM builtinValNamesMap)
+
+ sorted_pairs = sortLt lexical_lt (fmToList name_flag_pairs)
in
+ --pprTrace "Exporting:" (pprRnEnv PprDebug rn_env) $
hPutStr if_hdl "\n__exports__\n" >>
- hPutStr if_hdl (ppShow 100 (ppAboves (map pp_pair sorted_pairs)))
+ hPutStr if_hdl (uppShow 0 (uppAboves (map upp_pair sorted_pairs)))
where
- from_ty (TyData _ n _ _ _ _ _) acc = maybe_add acc n
- from_ty (TyNew _ n _ _ _ _ _) acc = maybe_add acc n
- from_ty (TySynonym n _ _ _) acc = maybe_add acc n
-
- from_cls (ClassDecl _ n _ _ _ _ _) acc = maybe_add acc n
+ from_val rn acc
+ | fun_looking rn && exportFlagOn ef = addToFM acc on ef
+ | otherwise = acc
+ where
+ ef = export_fn n -- NB: using the export fn!
+ n = getName rn
+ on = origName "from_val" n
- from_sig (Sig n _ _ _) acc = maybe_add acc n
+ -- fun_looking: must avoid class ops and data constructors
+ -- and record fieldnames
+ fun_looking (RnName _) = True
+ fun_looking (WiredInId i) = not (isDataCon i)
+ fun_looking _ = False
- from_binds bs acc = maybe_add_list acc (collectTopLevelBinders bs)
+ from_tc rn acc
+ | exportFlagOn ef = addToFM acc on ef
+ | otherwise = acc
+ where
+ ef = export_fn n -- NB: using the export fn!
+ n = getName rn
+ on = origName "from_tc" n
- --------------
- maybe_add :: Bag (Name, ExportFlag) -> RnName -> Bag (Name, ExportFlag)
+ from_dotdot is_valish (n,ef) acc
+ | is_valish && isLexCon str = acc
+ | exportFlagOn ef = addToFM acc on ef
+ | otherwise = acc
+ where
+ on = origName "from_dotdot" n
+ (OrigName _ str) = on
- maybe_add acc rn
- | exportFlagOn ef = acc `snocBag` (n, ef)
+ from_wired is_val_ish rn acc
+ | is_val_ish && not (fun_looking rn)
+ = acc -- these things don't cause export-ery
+ | exportFlagOn ef = addToFM acc on ef
| otherwise = acc
where
n = getName rn
- ef = nameExportFlag n
-
- --------------
- maybe_add_list acc [] = acc
- maybe_add_list acc (n:ns) = maybe_add (maybe_add_list acc ns) n
+ ef = export_fn n
+ on = origName "from_wired" n
--------------
- lexical_lt (n1,_) (n2,_) = nameOrigName n1 < nameOrigName n2
+ lexical_lt (n1,_) (n2,_) = n1 < n2
--------------
- pp_pair (n, ef)
- = ppBeside (ppr PprInterface (nameOrigName n)) (pp_export ef)
+ upp_pair (OrigName m n, ef)
+ = uppBesides [uppPStr m, uppSP, uppPStr n, uppSP, upp_export ef]
where
- pp_export ExportAll = ppPStr SLIT("(..)")
- pp_export ExportAbs = ppNil
+ upp_export ExportAll = uppPStr SLIT("(..)")
+ upp_export ExportAbs = uppNil
\end{code}
\begin{code}
ifaceFixities Nothing{-no iface handle-} _ = return ()
ifaceFixities (Just if_hdl) (HsModule _ _ _ _ fixities _ _ _ _ _ _ _ _ _)
- = if null fixities then
+ = let
+ pp_fixities = foldr go [] fixities
+ in
+ if null pp_fixities then
return ()
else
hPutStr if_hdl "\n__fixities__\n" >>
- hPutStr if_hdl (ppShow 100 (ppAboves (map ppSemid fixities)))
+ hPutStr if_hdl (uppShow 0 (uppAboves pp_fixities))
+ where
+ go (InfixL v i) acc = (if isLocallyDefined v then (:) (print_fix "l" i v) else id) acc
+ go (InfixR v i) acc = (if isLocallyDefined v then (:) (print_fix "r" i v) else id) acc
+ go (InfixN v i) acc = (if isLocallyDefined v then (:) (print_fix "" i v) else id) acc
+
+ print_fix suff prec var
+ = uppBesides [uppPStr SLIT("infix"), uppStr suff, uppSP, uppInt prec, uppSP, ppr_name var, uppSemi]
\end{code}
\begin{code}
+non_wired x = not (isWiredInName (getName x)) --ToDo:move?
+
ifaceDecls Nothing{-no iface handle-} _ = return ()
ifaceDecls (Just if_hdl) (vals, tycons, classes, _)
- = let
- exported_classes = filter isExported classes
- exported_tycons = filter isExported tycons
- exported_vals = filter isExported vals
+ = ASSERT(all isLocallyDefined vals)
+ ASSERT(all isLocallyDefined tycons)
+ ASSERT(all isLocallyDefined classes)
+ let
+ nonwired_classes = filter non_wired classes
+ nonwired_tycons = filter non_wired tycons
+ nonwired_vals = filter non_wired vals
- sorted_classes = sortLt ltLexical exported_classes
- sorted_tycons = sortLt ltLexical exported_tycons
- sorted_vals = sortLt ltLexical exported_vals
- in
- ASSERT(not (null exported_classes && null exported_tycons && null exported_vals))
+ lt_lexical a b = origName "lt_lexical" a < origName "lt_lexical" b
+ sorted_classes = sortLt lt_lexical nonwired_classes
+ sorted_tycons = sortLt lt_lexical nonwired_tycons
+ sorted_vals = sortLt lt_lexical nonwired_vals
+ in
+ if (null sorted_classes && null sorted_tycons && null sorted_vals) then
+ -- You could have a module with just (re-)exports/instances in it
+ return ()
+ else
hPutStr if_hdl "\n__declarations__\n" >>
- hPutStr if_hdl (ppShow 100 (ppAboves [
- ppAboves (map ppSemid sorted_classes),
- ppAboves (map ppSemid sorted_tycons),
- ppAboves (map ppSemid sorted_vals)]))
+ hPutStr if_hdl (uppShow 0 (uppAboves [
+ uppAboves (map ppr_class sorted_classes),
+ uppAboves (map ppr_tycon sorted_tycons),
+ uppAboves [ppr_val v (idType v) | v <- sorted_vals]]))
\end{code}
\begin{code}
ifaceInstances (Just if_hdl) (_, _, _, insts)
= let
- exported_insts = filter is_exported_inst (bagToList insts)
+ togo_insts = filter is_togo_inst (bagToList insts)
- sorted_insts = sortLt lt_inst exported_insts
+ sorted_insts = sortLt lt_inst togo_insts
in
- if null exported_insts then
+ if null togo_insts then
return ()
else
hPutStr if_hdl "\n__instances__\n" >>
- hPutStr if_hdl (ppShow 100 (ppAboves (map pp_inst sorted_insts)))
+ hPutStr if_hdl (uppShow 0 (uppAboves (map pp_inst sorted_insts)))
where
- is_exported_inst (InstInfo clas _ ty _ _ _ _ _ from_here _ _ _)
+ is_togo_inst (InstInfo clas _ ty _ _ _ _ _ from_here _ _ _)
= from_here -- && ...
-------
tycon1 = fst (getAppTyCon ty1)
tycon2 = fst (getAppTyCon ty2)
in
- case (origName clas1 `cmp` origName clas2) of
+ case (origName "lt_inst" clas1 `cmp` origName "lt_inst" clas2) of
LT_ -> True
GT_ -> False
- EQ_ -> origName tycon1 < origName tycon2
+ EQ_ -> origName "lt_inst2" tycon1 < origName "lt_inst2" tycon2
-------
pp_inst (InstInfo clas tvs ty theta _ _ _ _ _ _ _ _)
- = ppBeside (ppPStr SLIT("instance "))
- (pprType PprInterface (mkSigmaTy tvs theta (mkDictTy clas ty)))
-\end{code}
-
-=== ALL OLD BELOW HERE ==============
-
-%************************************************************************
-%* *
-\subsection[main-MkIface]{Main routine for making interfaces}
-%* *
-%************************************************************************
-
-Misc points:
-\begin{enumerate}
-\item
-We get the general what-to-export information from the ``environments''
-produced by the typechecker (the \tr{[RenamedFixityDecl]} through
-\tr{Bag InstInfo} arguments).
-
-\item
-{\em However:} Whereas (for example) an \tr{InstInfo} will have
-\tr{Ids} in it that identify the constant methods for that instance,
-those particular \tr{Ids} {\em do not have} the best @IdInfos@!!!
-Those @IdInfos@ were figured out long after the \tr{InstInfo} was
-created.
-
-That's why we actually look at the final \tr{StgBindings} that go
-into the code-generator: they have the best @IdInfos@ on them.
-Whenever, we are about to print info about an @Id@, we look in the
-Ids-from-STG-bindings list to see if we have an ``equivalent'' @Id@
-with presumably-better @IdInfo@.
-
-\item
-We play this same game whether for values, classes (for their
-method-selectors and default-methods), or instances (for their
-@DictFunIds@ or constant-methods).
-
-Of course, for imported things, what we got from the typechecker is
-all we're gonna get.
-
-\item
-We {\em sort} things in the interface into some ``canonical'' order;
-otherwise, with heavily-recursive modules, you can have (unchanged)
-information ``move around'' in the interface file---deeply unfriendly
-to \tr{make}.
-\end{enumerate}
-
-\begin{code}
-{- OLD: to the end
-mkInterface :: FAST_STRING
- -> (FAST_STRING -> Bool, -- is something in export list, explicitly?
- FAST_STRING -> Bool) -- is a module among the "dotdot" exported modules?
- -> IdEnv UnfoldingDetails
- -> FiniteMap TyCon [(Bool, [Maybe Type])]
- -> ([RenamedFixityDecl], -- interface info from the typecheck
- [Id],
- CE,
- TCE,
- Bag InstInfo)
- -> [StgBinding]
- -> Pretty
-
-mkInterface modname export_list_fns inline_env tycon_specs
- (fixity_decls, global_ids, ce, tce, inst_infos)
- stg_binds
- = let
- -- first, gather up the things we want to export:
-
- exported_tycons = [ tc | tc <- rngTCE tce,
- isExported tc,
- is_exportable_tycon_or_class export_list_fns tc ]
- exported_classes = [ c | c <- rngCE ce,
- isExported c,
- is_exportable_tycon_or_class export_list_fns c ]
- exported_inst_infos = [ i | i <- bagToList inst_infos,
- is_exported_inst_info export_list_fns i ]
- exported_vals
- = [ v | v <- global_ids,
- isExported v && not (isDataCon v) && not (isClassOpId v) ]
-
- -- We also have to worry about TyCons/Classes that are
- -- *mentioned* in exported things (e.g., values' types or
- -- instances), so that we can be sure to do an import decl for
- -- them, for original-naming purposes:
-
- (mentioned_tycons, mentioned_classes)
- = foldr ( \ (tcs1, cls1) (tcs2, cls2)
- -> (tcs1 `unionBags` tcs2, cls1 `unionBags` cls2) )
- (emptyBag, emptyBag)
- (map getMentionedTyConsAndClassesFromClass exported_classes ++
- map getMentionedTyConsAndClassesFromTyCon exported_tycons ++
- map getMentionedTyConsAndClassesFromId exported_vals ++
- map getMentionedTyConsAndClassesFromInstInfo exported_inst_infos)
-
- mentionable_classes
- = filter is_mentionable (bagToList mentioned_classes)
- mentionable_tycons
- = [ tc | tc <- bagToList mentioned_tycons,
- is_mentionable tc,
- not (isPrimTyCon tc) ]
-
- nondup_mentioned_tycons = fst (removeDups cmp mentionable_tycons)
- nondup_mentioned_classes = fst (removeDups cmp mentionable_classes)
-
- -- Next: as discussed in the notes, we want the top-level
- -- Ids straight from the final STG code, so we can use
- -- their IdInfos to print pragmas; we slurp them out here,
- -- then pass them to the printing functions, which may
- -- use them.
-
- better_ids = collectExportedStgBinders stg_binds
-
- -- Make a lookup function for convenient access:
-
- better_id_fn i
- = if not (isLocallyDefined i)
- then i -- can't be among our "better_ids"
- else
- let
- eq_fn = if isTopLevId i -- can't trust uniqs
- then (\ x y -> origName x == origName y)
- else eqId
- in
- case [ x | x <- better_ids, x `eq_fn` i ] of
- [] -> pprPanic "better_id_fn:" (ppr PprShowAll i)
- i
- [x] -> x
- _ -> panic "better_id_fn"
-
- -- Finally, we sort everything lexically, so that we always
- -- get the same interface from the same information:
-
- sorted_mentioned_tycons = sortLt ltLexical nondup_mentioned_tycons
- sorted_mentioned_classes = sortLt ltLexical nondup_mentioned_classes
-
- sorted_tycons = sortLt ltLexical exported_tycons
- sorted_classes = sortLt ltLexical exported_classes
- sorted_vals = sortLt ltLexical exported_vals
- sorted_inst_infos = sortLt lt_lexical_inst_info exported_inst_infos
- in
- if (any_purely_local sorted_tycons sorted_classes sorted_vals) then
- -- this will be less of a HACK when we teach
- -- mkInterface to do I/O (WDP 94/10)
- error "Can't produce interface file because of errors!\n"
- else
- ppAboves
- [ppPStr SLIT("{-# GHC_PRAGMA INTERFACE VERSION 7 #-}"),
- ppCat [ppPStr SLIT("interface"), ppPStr modname, ppPStr SLIT("where")],
-
- do_import_decls modname
- sorted_vals sorted_mentioned_classes sorted_mentioned_tycons,
- -- Mustn't give the data constructors to do_import_decls,
- -- because they aren't explicitly imported; their tycon is.
-
- ppAboves (map do_fixity fixity_decls),
- ppAboves (map (pprIfaceClass better_id_fn inline_env) sorted_classes),
- ppAboves (map (do_tycon tycon_specs) sorted_tycons),
- ppAboves (map (do_value better_id_fn inline_env) sorted_vals),
- ppAboves (map (do_instance better_id_fn inline_env) sorted_inst_infos),
-
- ppChar '\n'
- ]
- where
- any_purely_local tycons classes vals
- = any bad_tc tycons || any bad_cl classes || any bad_id vals
- where
- bad_cl cl
- = case (maybePurelyLocalClass cl) of
- Nothing -> False
- Just xs -> naughty_trace cl xs
-
- bad_id id
- = case (maybePurelyLocalType (idType id)) of
- Nothing -> False
- Just xs -> naughty_trace id xs
-
- bad_tc tc
- = case (maybePurelyLocalTyCon tc) of
- Nothing -> False
- Just xs -> if exported_abs then False else naughty_trace tc xs
- where
- exported_abs = case (getExportFlag tc) of { ExportAbs -> True; _ -> False }
-
- naughty_trace x things
- = pprTrace "Can't export -- `"
- (ppBesides [ppr PprForUser x, ppStr "' mentions purely local things: ",
- ppInterleave pp'SP things])
- True
+ = let
+ forall_ty = mkSigmaTy tvs theta (mkDictTy clas ty)
+ renumbered_ty = initNmbr (nmbrType forall_ty)
+ in
+ case (splitForAllTy renumbered_ty) of { (rtvs, rrho_ty) ->
+ uppBesides [uppPStr SLIT("instance "), ppr_forall rtvs, ppr_ty rrho_ty, uppSemi] }
\end{code}
%************************************************************************
%* *
-\subsection[imports-MkIface]{Generating `import' declarations in an interface}
+\subsection{Printing tycons, classes, ...}
%* *
%************************************************************************
-We gather up lots of (module, name) pairs for which we might print an
-import declaration. We sort them, for the usual canonicalisation
-reasons. NB: We {\em assume} the lists passed in don't have duplicates in
-them! expect).
-
-All rather horribly turgid (WDP).
-
\begin{code}
-do_import_decls
- :: FAST_STRING
- -> [Id] -> [Class] -> [TyCon]
- -> Pretty
-
-do_import_decls mod_name vals classes tycons
- = let
- -- Conjure up (module, name) pairs for all
- -- the potentially import-decls things:
-
- vals_names, classes_names, tycons_names :: [(FAST_STRING, FAST_STRING, [Maybe FAST_STRING])]
- vals_names = map get_val_pair vals
- classes_names = map get_class_pair classes
- tycons_names = map get_tycon_pair tycons
-
- -- sort the (module, name) pairs and chop
- -- them into per-module groups:
-
- ie_list = sortLt lt (tycons_names ++ classes_names ++ vals_names)
-
- per_module_groups = runs same_module ie_list
- in
- ppAboves (map print_a_decl per_module_groups)
+ppr_class :: Class -> Unpretty
+
+ppr_class c
+ = --pprTrace "ppr_class:" (ppr PprDebug c) $
+ case (initNmbr (nmbrClass c)) of { -- renumber it!
+ Class _ n tyvar super_classes sdsels ops sels defms insts links ->
+
+ uppCat [uppPStr SLIT("class"), ppr_context tyvar super_classes,
+ ppr_name n, ppr_tyvar tyvar,
+ if null ops
+ then uppSemi
+ else uppCat [uppStr "where {", uppCat (map ppr_op ops), uppStr "};"]]
+ }
where
- lt, same_module :: (FAST_STRING, FAST_STRING)
- -> (FAST_STRING, FAST_STRING) -> Bool
-
- lt (m1, ie1, ie2)
- = case (_CMP_STRING_ m1 m2) of { LT_ -> True; EQ_ -> ie1 < ie2; GT__ -> False }
-
- same_module (m1, _, _) (m2, _, _) = m1 == m2
-
- compiling_the_prelude = opt_CompilingPrelude
-
- print_a_decl :: [(FAST_STRING, FAST_STRING, [Maybe FAST_STRING])] -> Pretty
- {-
- Obviously, if the module in question is this one,
- don't print an import declaration.
-
- If it's a Prelude* module, we don't print the TyCons/
- Classes, because the compiler supposedly knows about
- them already (and they are PreludeCore things anyway).
-
- But if we are compiling a Prelude module, then we
- try to do it as "normally" as possible.
- -}
- print_a_decl (ielist@((m,_,_) : _))
- | m == mod_name
- || (not compiling_the_prelude &&
- ({-OLD:m == pRELUDE_CORE ||-} m == pRELUDE_BUILTIN))
- = ppNil
-
- | otherwise
- = ppBesides [ppPStr SLIT("import "), ppPStr m, ppLparen,
- ppIntersperse pp'SP{-'-} (map pp_str [n | (_,n,_) <- ielist]),
- ppRparen
- ]
- where
- isnt_tycon_ish :: FAST_STRING -> Bool
- isnt_tycon_ish str = not (isLexCon str)
+ ppr_context :: TyVar -> [Class] -> Unpretty
- grab_non_Nothings :: [[Maybe FAST_STRING]] -> [FAST_STRING]
+ ppr_context tv [] = uppNil
+-- ppr_context tv [sc] = uppBeside (ppr_assert tv sc) (uppPStr SLIT(" =>"))
+ ppr_context tv super_classes
+ = uppBesides [uppStr "{{",
+ uppIntersperse upp'SP{-'-} (map (ppr_assert tv) super_classes),
+ uppStr "}} =>"]
- grab_non_Nothings rns = catMaybes (concat rns)
+ ppr_assert tv (Class _ n _ _ _ _ _ _ _ _) = uppCat [ppr_name n, ppr_tyvar tv]
- pp_str :: FAST_STRING -> Pretty
- pp_str pstr
- = if isLexVarSym pstr then ppStr ("("++str++")") else ppPStr pstr
- where
- str = _UNPK_ pstr
-\end{code}
-
-\begin{code}
-get_val_pair :: Id -> (FAST_STRING, FAST_STRING)
-get_class_pair :: Class -> (FAST_STRING, FAST_STRING)
-get_tycon_pair :: TyCon -> (FAST_STRING, FAST_STRING)
-
-get_val_pair id
- = generic_pair id
-
-get_class_pair clas
- = case (generic_pair clas) of { (orig_mod, orig_nm) ->
- let
- nm_to_print = case (getExportFlag clas) of
- ExportAll -> orig_nm _APPEND_ SLIT("(..)") -- nothing like a good HACK!
- ExportAbs -> orig_nm
- NotExported -> orig_nm
- in
- (orig_mod, nm_to_print) }
-
-get_tycon_pair tycon
- = case (generic_pair tycon) of { (orig_mod, orig_nm) ->
- let
- nm_to_print = case (getExportFlag tycon) of
- ExportAll -> orig_nm _APPEND_ SLIT("(..)") -- nothing like a good HACK!
- ExportAbs -> orig_nm
- NotExported -> orig_nm
+ clas_mod = moduleOf (origName "ppr_class" c)
- cons = tyConDataCons tycon
- in
- (orig_mod, nm_to_print) }
-
-generic_pair thing
- = case (moduleNamePair thing) of { (orig_mod, orig_nm) ->
- case (getOccName thing) of { occur_name ->
- (orig_mod, orig_nm) }}
+ ppr_op (ClassOp o _ ty) = pp_sig (Qual clas_mod o) ty
\end{code}
-%************************************************************************
-%* *
-\subsection[fixities-MkIface]{Generating fixity declarations in an interface}
-%* *
-%************************************************************************
-
-
\begin{code}
-do_fixity :: -> RenamedFixityDecl -> Pretty
+ppr_val v ty -- renumber the type first!
+ = --pprTrace "ppr_val:" (ppr PprDebug v) $
+ pp_sig v (initNmbr (nmbrType ty))
-do_fixity fixity_decl
- = case (isLocallyDefined name, getExportFlag name) of
- (True, ExportAll) -> ppr PprInterface fixity_decl
- _ -> ppNil
- where
- name = get_name fixity_decl
- get_name (InfixL n _) = n
- get_name (InfixR n _) = n
- get_name (InfixN n _) = n
-\end{code}
-
-%************************************************************************
-%* *
-\subsection[tycons-MkIface]{Generating tycon declarations in an interface}
-%* *
-%************************************************************************
-
-\begin{code}
-do_tycon :: FiniteMap TyCon [(Bool, [Maybe Type])] -> TyCon -> Pretty
+pp_sig op ty
+ = case (splitForAllTy ty) of { (tvs, rho_ty) ->
+ uppBesides [ppr_name op, uppPStr SLIT(" :: "), ppr_forall tvs, ppr_ty rho_ty, uppSemi] }
-do_tycon tycon_specs_map tycon
- = pprTyCon PprInterface tycon tycon_specs
- where
- tycon_specs = map snd (lookupWithDefaultFM tycon_specs_map [] tycon)
+ppr_forall [] = uppNil
+ppr_forall tvs = uppBesides [ uppStr "__forall__ [", uppInterleave uppComma (map ppr_tyvar tvs), uppStr "] " ]
\end{code}
-%************************************************************************
-%* *
-\subsection[values-MkIface]{Generating a value's signature in an interface}
-%* *
-%************************************************************************
-
\begin{code}
-do_value :: (Id -> Id)
- -> IdEnv UnfoldingDetails
- -> Id
- -> Pretty
-
-do_value better_id_fn inline_env val
- = let
- sty = PprInterface
- better_val = better_id_fn val
- name_str = getOccName better_val -- NB: not orig name!
-
- id_info = getIdInfo better_val
-
- val_ty = let
- orig_ty = idType val
- final_ty = idType better_val
- in
--- ASSERT (orig_ty == final_ty || mkLiftTy orig_ty == final_ty)
- ASSERT (if (orig_ty == final_ty || mkLiftTy orig_ty == final_ty) then True else pprTrace "do_value:" (ppCat [ppr PprDebug val, ppr PprDebug better_val]) False)
- orig_ty
-
- -- Note: We export the type of the original val
- -- The type of an unboxed val will have been *lifted* by the desugarer
- -- In this case we export an unlifted type, but id_info which assumes
- -- a lifted Id i.e. extracted from better_val (above)
- -- The importing module must lift the Id before using the imported id_info
-
- pp_id_info
- = if opt_OmitInterfacePragmas
- || boringIdInfo id_info
- then ppNil
- else ppCat [ppPStr SLIT("\t{-# GHC_PRAGMA"),
- ppIdInfo sty better_val True{-yes specs-}
- better_id_fn inline_env id_info,
- ppPStr SLIT("#-}")]
- in
- ppAbove (ppCat [ppr_non_op name_str,
- ppPStr SLIT("::"), pprGenType sty val_ty])
- pp_id_info
+ppr_tycon tycon
+ = --pprTrace "ppr_tycon:" (ppr PprDebug tycon) $
+ ppr_tc (initNmbr (nmbrTyCon tycon))
--- sadly duplicates Name.pprNonSym (ToDo)
+------------------------
+ppr_tc (PrimTyCon _ n _ _)
+ = uppCat [ uppStr "{- data", ppr_name n, uppStr " *built-in* -}" ]
-ppr_non_op str
- = if isLexVarSym str -- NOT NEEDED: || isAconop
- then ppBesides [ppLparen, ppPStr str, ppRparen]
- else ppPStr str
-\end{code}
+ppr_tc FunTyCon
+ = uppCat [ uppStr "{- data", ppr_name FunTyCon, uppStr " *built-in* -}" ]
-%************************************************************************
-%* *
-\subsection[instances-MkIface]{Generating instance declarations in an interface}
-%* *
-%************************************************************************
+ppr_tc (TupleTyCon _ n _)
+ = uppCat [ uppStr "{- ", ppr_name n, uppStr "-}" ]
-The types of ``dictionary functions'' (dfuns) have just the required
-info for instance declarations in interfaces. However, the dfuns that
-GHC really uses have {\em extra} dictionaries passed to them (for
-efficiency). When we print interfaces, we want to omit that
-dictionary information. (It can be reconsituted on the other end,
-from instance and class decls).
-
-\begin{code}
-do_instance :: (Id -> Id)
- -> IdEnv UnfoldingDetails
- -> InstInfo
- -> Pretty
-
-do_instance better_id_fn inline_env
- (InstInfo clas tv_tmpls ty inst_decl_theta dfun_theta dfun_id constm_ids _ from_here modname _ _)
+ppr_tc (SynTyCon _ n _ _ tvs expand)
= let
- sty = PprInterface
-
- better_dfun = better_id_fn dfun_id
- better_dfun_info = getIdInfo better_dfun
- better_constms = map better_id_fn constm_ids
-
- class_op_strs = map classOpString (classOps clas)
-
- pragma_begin
- = ppCat [ppPStr SLIT("\t{-# GHC_PRAGMA"), pp_modname, ppPStr SLIT("{-dfun-}"),
- ppIdInfo sty better_dfun False{-NO specs-}
- better_id_fn inline_env better_dfun_info]
-
- pragma_end = ppPStr SLIT("#-}")
-
- pp_modname = if _NULL_ modname
- then ppNil
- else ppCat [ppStr "_M_", ppPStr modname]
-
- name_pragma_pairs
- = pp_the_list [ ppCat [ppChar '\t', ppr_non_op op, ppEquals,
- ppChar '{' ,
- ppIdInfo sty constm True{-YES, specs-}
- better_id_fn inline_env
- (getIdInfo constm),
- ppChar '}' ]
- | (op, constm) <- class_op_strs `zip` better_constms ]
-
-#ifdef DEBUG
- pp_the_list [] = panic "MkIface: no class_ops or better_constms?"
-#endif
- pp_the_list [p] = p
- pp_the_list (p:ps) = ppAbove (ppBeside p ppComma) (pp_the_list ps)
-
- real_stuff
- = ppCat [ppPStr SLIT("instance"),
- ppr sty (mkSigmaTy tv_tmpls inst_decl_theta (mkDictTy clas ty))]
+ pp_tyvars = map ppr_tyvar tvs
in
- if opt_OmitInterfacePragmas
- || boringIdInfo better_dfun_info
- then real_stuff
- else ppAbove real_stuff
- ({-ppNest 8 -} -- ppNest does nothing
- if null better_constms
- then ppCat [pragma_begin, pragma_end]
- else ppAbove pragma_begin (ppCat [name_pragma_pairs, pragma_end])
- )
-\end{code}
-
-%************************************************************************
-%* *
-\subsection[utils-InstInfos]{Utility functions for @InstInfos@}
-%* *
-%************************************************************************
-
-ToDo: perhaps move.
-
-Classes/TyCons are ``known,'' more-or-less. Prelude TyCons are
-``completely'' known---they don't need to be mentioned in interfaces.
-Classes usually don't need to be mentioned in interfaces, but if we're
-compiling the prelude, then we treat them without special favours.
-\begin{code}
-is_exportable_tycon_or_class export_list_fns tc
- = if not (fromPreludeCore tc) then
- True
- else
- in_export_list_or_among_dotdot_modules
- opt_CompilingPrelude -- ignore M.. stuff if compiling prelude
- export_list_fns tc
-
-in_export_list_or_among_dotdot_modules ignore_Mdotdots (in_export_list, among_dotdot_modules) tc
- = if in_export_list (getOccName tc) then
- True
- else
--- pprTrace "in_export:" (ppAbove (ppr PprDebug ignore_Mdotdots) (ppPStr (getOccName tc))) (
- if ignore_Mdotdots then
- False
- else
- any among_dotdot_modules (getInformingModules tc)
--- )
-
-is_mentionable tc
- = not (from_PreludeCore_or_Builtin tc) || opt_CompilingPrelude
+ uppBesides [uppPStr SLIT("type "), ppr_name n, uppSP, uppIntersperse uppSP pp_tyvars,
+ uppPStr SLIT(" = "), ppr_ty expand, uppSemi]
+
+ppr_tc this_tycon@(DataTyCon u n k tvs ctxt cons derivings data_or_new)
+ = uppCat [pp_data_or_new,
+ ppr_context ctxt,
+ ppr_name n,
+ uppIntersperse uppSP (map ppr_tyvar tvs),
+ uppEquals, pp_condecls,
+ uppSemi]
+ -- NB: we do not print deriving info in interfaces
where
- from_PreludeCore_or_Builtin thing
+ pp_data_or_new = case data_or_new of
+ DataType -> uppPStr SLIT("data")
+ NewType -> uppPStr SLIT("newtype")
+
+ ppr_context [] = uppNil
+-- ppr_context [(c,t)] = uppCat [ppr_name c, ppr_ty t, uppPStr SLIT("=>")]
+ ppr_context cs
+ = uppBesides[uppStr "{{",
+ uppInterleave uppComma [uppCat [ppr_name c, ppr_ty t] | (c,t) <- cs],
+ uppStr "}}", uppPStr SLIT(" =>")]
+
+ pp_condecls
= let
- mod_name = fst (moduleNamePair thing)
+ (c:cs) = cons
in
- mod_name == pRELUDE_CORE || mod_name == pRELUDE_BUILTIN
-
-is_exported_inst_info export_list_fns
- (InstInfo clas _ ty _ _ _ _ _ from_here _ _ _)
- = let
- seems_exported = instanceIsExported clas ty from_here
- (tycon, _, _) = getAppTyCon ty
- in
- if (opt_OmitReexportedInstances && not from_here) then
- False -- Flag says to violate Haskell rules, blatantly
-
- else if not opt_CompilingPrelude
- || not (isFunTyCon tycon || fromPreludeCore tycon)
- || not (fromPreludeCore clas) then
- seems_exported -- take what we got
-
- else -- compiling Prelude & tycon/class are Prelude things...
- from_here
- || in_export_list_or_among_dotdot_modules True{-ignore M..s-} export_list_fns clas
- || in_export_list_or_among_dotdot_modules True{-ignore M..s-} export_list_fns tycon
-\end{code}
+ uppCat ((ppr_con c) : (map ppr_next_con cs))
-\begin{code}
-lt_lexical_inst_info (InstInfo _ _ _ _ _ dfun1 _ _ _ _ _ _) (InstInfo _ _ _ _ _ dfun2 _ _ _ _ _ _)
- = ltLexical dfun1 dfun2
-\end{code}
+ ppr_next_con con = uppCat [uppChar '|', ppr_con con]
-\begin{code}
-getMentionedTyConsAndClassesFromInstInfo (InstInfo clas _ ty _ dfun_theta _ _ _ _ _ _ _)
- = case (getMentionedTyConsAndClassesFromType ty) of { (ts, cs) ->
- case [ c | (c, _) <- dfun_theta ] of { theta_classes ->
- (ts, (cs `unionBags` listToBag theta_classes) `snocBag` clas)
- }}
-OLD from the beginning -}
+ ppr_con con
+ = let
+ con_arg_tys = dataConRawArgTys con
+ labels = dataConFieldLabels con -- none if not a record
+ strict_marks = dataConStrictMarks con
+ in
+ uppCat [ppr_name con, ppr_fields labels strict_marks con_arg_tys]
+
+ ppr_fields labels strict_marks con_arg_tys
+ = if null labels then -- not a record thingy
+ uppIntersperse uppSP (zipWithEqual "ppr_fields" ppr_bang_ty strict_marks con_arg_tys)
+ else
+ uppCat [ uppChar '{',
+ uppInterleave uppComma (zipWith3Equal "ppr_field" ppr_field labels strict_marks con_arg_tys),
+ uppChar '}' ]
+
+ ppr_bang_ty b t
+ = uppBeside (case b of { MarkedStrict -> uppChar '!'; _ -> uppNil })
+ (prettyToUn (pprParendType PprInterface t))
+
+ ppr_field l b t
+ = uppBesides [ppr_name l, uppPStr SLIT(" :: "),
+ case b of { MarkedStrict -> uppChar '!'; _ -> uppNil },
+ ppr_ty t]
\end{code}