X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=ghc%2Fcompiler%2Fmain%2FMkIface.lhs;h=d8ead0bcaa24d4c03741f85b918b9ec4a6610fcb;hb=f7ecf7234c224489be8a5e63fced903b655d92ee;hp=46bb220b58f14c3d2484d458a7ef92e16f521c1a;hpb=7d61cb61daa5e433a0cb85b34b7f0c58b2f961ff;p=ghc-hetmet.git diff --git a/ghc/compiler/main/MkIface.lhs b/ghc/compiler/main/MkIface.lhs index 46bb220..d8ead0b 100644 --- a/ghc/compiler/main/MkIface.lhs +++ b/ghc/compiler/main/MkIface.lhs @@ -1,566 +1,484 @@ % -% (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 PrelInfo ( mkLiftTy, pRELUDE_CORE, pRELUDE_BUILTIN ) -import HsSyn ( FixityDecl(..), RenamedFixityDecl(..), MonoBinds, - RenamedMonoBinds(..), Name, RenamedPat(..), Sig +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 ( idType, dataConRawArgTys, dataConFieldLabels, isDataCon, + dataConStrictMarks, StrictnessMark(..), + GenId{-instance NamedThing/Outputable-} + ) +import Maybes ( maybeToBool ) +import Name ( origName, nameOf, moduleOf, + exportFlagOn, nameExportFlag, ExportFlag(..), + isLexSym, isLexCon, isLocallyDefined, isWiredInName, + RdrName(..){-instance Outputable-}, + OrigName(..){-instance Ord-}, + Name{-instance NamedThing-} ) -import Type -import Bag -import FiniteMap -import Id -import IdInfo -- plenty from here -import Maybes ( catMaybes, Maybe(..) ) -import Outputable -import Pretty -import StgSyn -import TcInstDcls ( InstInfo(..) ) -import Util +import ParseUtils ( UsagesMap(..), VersionsMap(..) ) +import PprEnv -- not sure how much... +import PprStyle ( PprStyle(..) ) +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-}, 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} -%************************************************************************ -%* * -\subsection[main-MkIface]{Main routine for making interfaces} -%* * -%************************************************************************ +We have a function @startIface@ to open the output file and put +(something like) ``interface Foo'' in it. It gives back a handle +for subsequent additions to the interface file. -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} +We then have one-function-per-block-of-interface-stuff, e.g., +@ifaceExportList@ produces the @__exports__@ section; it appends +to the handle provided by @startIface@. \begin{code} -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 -> getOrigName x == getOrigName 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 +startIface :: Module + -> IO (Maybe Handle) -- Nothing <=> don't do an interface +endIface :: Maybe Handle -> IO () +ifaceUsages + :: Maybe Handle + -> UsagesMap + -> IO () +ifaceVersions + :: Maybe Handle + -> VersionsMap + -> IO () +ifaceExportList + :: Maybe Handle + -> (Name -> ExportFlag, ([(Name,ExportFlag)], [(Name,ExportFlag)])) + -> RnEnv + -> IO () +ifaceFixities + :: Maybe Handle + -> RenamedHsModule + -> IO () +ifaceInstanceModules + :: Maybe Handle + -> [Module] + -> IO () +ifaceDecls :: Maybe Handle + -> TcIfaceInfo -- info produced by typechecker, for interfaces + -> IO () +ifaceInstances + :: Maybe Handle + -> TcIfaceInfo -- as above + -> IO () +ifacePragmas + :: Maybe Handle + -> IO () +ifacePragmas = panic "ifacePragmas" -- stub \end{code} -%************************************************************************ -%* * -\subsection[imports-MkIface]{Generating `import' declarations in an interface} -%* * -%************************************************************************ +\begin{code} +startIface mod + = case opt_ProduceHi of + Nothing -> return Nothing -- not producing any .hi file + Just fn -> + openFile fn WriteMode >>= \ if_hdl -> + hPutStr if_hdl ("{-# GHC_PRAGMA INTERFACE VERSION 20 #-}\ninterface "++ _UNPK_ mod) >> + return (Just if_hdl) + +endIface Nothing = return () +endIface (Just if_hdl) = hPutStr if_hdl "\n" >> hClose if_hdl +\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... -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). + upp_uses (m, (mv, versions)) + = uppBesides [uppPStr m, uppSP, uppInt mv, uppPStr SLIT(" :: "), + upp_versions (fmToList versions), uppSemi] -All rather horribly turgid (WDP). + upp_versions nvs + = uppIntersperse uppSP [ uppCat [uppPStr n, uppInt v] | (n,v) <- nvs ] +\end{code} \begin{code} -do_import_decls - :: FAST_STRING - -> [Id] -> [Class] -> [TyCon] - -> Pretty +ifaceVersions Nothing{-no iface handle-} _ = return () + +ifaceVersions (Just if_hdl) version_info + | 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 -do_import_decls mod_name vals classes tycons - = let - -- Conjure up (module, name) pairs for all - -- the potentially import-decls things: + upp_versions nvs + = uppAboves [ uppPStr n | (n,v) <- nvs ] +\end{code} - 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 +\begin{code} +ifaceInstanceModules Nothing{-no iface handle-} _ = return () +ifaceInstanceModules (Just _) [] = return () - -- sort the (module, name) pairs and chop - -- them into per-module groups: +ifaceInstanceModules (Just if_hdl) imods + = hPutStr if_hdl "\n__instance_modules__\n" >> + hPutStr if_hdl (uppShow 0 (uppCat (map uppPStr imods))) +\end{code} - ie_list = sortLt lt (tycons_names ++ classes_names ++ vals_names) +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. 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 (Just if_hdl) + (export_fn, (dotdot_vals, dotdot_tcs)) + rn_env@((qual, unqual, tc_qual, tc_unqual), _) + = let + name_flag_pairs :: FiniteMap OrigName ExportFlag + 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) - per_module_groups = runs same_module ie_list in - ppAboves (map print_a_decl per_module_groups) + --pprTrace "Exporting:" (pprRnEnv PprDebug rn_env) $ + hPutStr if_hdl "\n__exports__\n" >> + hPutStr if_hdl (uppShow 0 (uppAboves (map upp_pair sorted_pairs))) 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 && - (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 - ] + 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 + + -- 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_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 + + from_dotdot is_valish (n,ef) acc + | is_valish && isLexCon str = acc + | exportFlagOn ef = addToFM acc on ef + | otherwise = acc where - isnt_tycon_ish :: FAST_STRING -> Bool - isnt_tycon_ish str = not (isConop str) + on = origName "from_dotdot" n + (OrigName _ str) = on + + 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 = export_fn n + on = origName "from_wired" n + + -------------- + lexical_lt (n1,_) (n2,_) = n1 < n2 - grab_non_Nothings :: [[Maybe FAST_STRING]] -> [FAST_STRING] + -------------- + upp_pair (OrigName m n, ef) + = uppBesides [uppPStr m, uppSP, uppPStr n, uppSP, upp_export ef] + where + upp_export ExportAll = uppPStr SLIT("(..)") + upp_export ExportAbs = uppNil +\end{code} - grab_non_Nothings rns = catMaybes (concat rns) +\begin{code} +ifaceFixities Nothing{-no iface handle-} _ = return () - pp_str :: FAST_STRING -> Pretty - pp_str pstr - = if isAvarop pstr then ppStr ("("++str++")") else ppPStr pstr - where - str = _UNPK_ pstr +ifaceFixities (Just if_hdl) (HsModule _ _ _ _ fixities _ _ _ _ _ _ _ _ _) + = let + pp_fixities = foldr go [] fixities + in + if null pp_fixities then + return () + else + hPutStr if_hdl "\n__fixities__\n" >> + 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} -get_val_pair :: Id -> (FAST_STRING, FAST_STRING) -get_class_pair :: Class -> (FAST_STRING, FAST_STRING) -get_tycon_pair :: TyCon -> (FAST_STRING, FAST_STRING) +non_wired x = not (isWiredInName (getName x)) --ToDo:move? -get_val_pair id - = generic_pair id +ifaceDecls Nothing{-no iface handle-} _ = return () -get_class_pair clas - = case (generic_pair clas) of { (orig_mod, orig_nm) -> +ifaceDecls (Just if_hdl) (vals, tycons, classes, _) + = ASSERT(all isLocallyDefined vals) + ASSERT(all isLocallyDefined tycons) + ASSERT(all isLocallyDefined classes) 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) } + nonwired_classes = filter non_wired classes + nonwired_tycons = filter non_wired tycons + nonwired_vals = filter non_wired vals -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 + lt_lexical a b = origName "lt_lexical" a < origName "lt_lexical" b - cons = tyConDataCons tycon + sorted_classes = sortLt lt_lexical nonwired_classes + sorted_tycons = sortLt lt_lexical nonwired_tycons + sorted_vals = sortLt lt_lexical nonwired_vals in - (orig_mod, nm_to_print) } - -generic_pair thing - = case (getOrigName thing) of { (orig_mod, orig_nm) -> - case (getOccurrenceName thing) of { occur_name -> - (orig_mod, orig_nm) }} + 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 (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} -%************************************************************************ -%* * -\subsection[fixities-MkIface]{Generating fixity declarations in an interface} -%* * -%************************************************************************ - - \begin{code} -do_fixity :: -> RenamedFixityDecl -> Pretty +ifaceInstances Nothing{-no iface handle-} _ = return () -do_fixity fixity_decl - = case (getExportFlag (get_name fixity_decl)) of - ExportAll -> ppr PprInterface fixity_decl - _ -> ppNil - where - get_name (InfixL n _) = n - get_name (InfixR n _) = n - get_name (InfixN n _) = n -\end{code} +ifaceInstances (Just if_hdl) (_, _, _, insts) + = let + togo_insts = filter is_togo_inst (bagToList insts) -%************************************************************************ -%* * -\subsection[tycons-MkIface]{Generating tycon declarations in an interface} -%* * -%************************************************************************ + sorted_insts = sortLt lt_inst togo_insts + in + if null togo_insts then + return () + else + hPutStr if_hdl "\n__instances__\n" >> + hPutStr if_hdl (uppShow 0 (uppAboves (map pp_inst sorted_insts))) + where + is_togo_inst (InstInfo clas _ ty _ _ _ _ _ from_here _ _ _) + = from_here -- && ... -\begin{code} -do_tycon :: FiniteMap TyCon [(Bool, [Maybe Type])] -> TyCon -> Pretty + ------- + lt_inst (InstInfo clas1 _ ty1 _ _ _ _ _ _ _ _ _) + (InstInfo clas2 _ ty2 _ _ _ _ _ _ _ _ _) + = let + tycon1 = fst (getAppTyCon ty1) + tycon2 = fst (getAppTyCon ty2) + in + case (origName "lt_inst" clas1 `cmp` origName "lt_inst" clas2) of + LT_ -> True + GT_ -> False + EQ_ -> origName "lt_inst2" tycon1 < origName "lt_inst2" tycon2 -do_tycon tycon_specs_map tycon - = pprTyCon PprInterface tycon tycon_specs - where - tycon_specs = map snd (lookupWithDefaultFM tycon_specs_map [] tycon) + ------- + pp_inst (InstInfo clas tvs ty theta _ _ _ _ _ _ _ _) + = 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[values-MkIface]{Generating a value's signature in an interface} +\subsection{Printing tycons, classes, ...} %* * %************************************************************************ \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 = getOccurrenceName 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_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 + ppr_context :: TyVar -> [Class] -> Unpretty --- sadly duplicates Outputable.pprNonOp (ToDo) + 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 "}} =>"] -ppr_non_op str - = if isAvarop str -- NOT NEEDED: || isAconop - then ppBesides [ppLparen, ppPStr str, ppRparen] - else ppPStr str -\end{code} + ppr_assert tv (Class _ n _ _ _ _ _ _ _ _) = uppCat [ppr_name n, ppr_tyvar tv] -%************************************************************************ -%* * -\subsection[instances-MkIface]{Generating instance declarations in an interface} -%* * -%************************************************************************ + clas_mod = moduleOf (origName "ppr_class" c) -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). + ppr_op (ClassOp o _ ty) = pp_sig (Qual clas_mod o) ty +\end{code} \begin{code} -do_instance :: (Id -> Id) - -> IdEnv UnfoldingDetails - -> InstInfo - -> Pretty +ppr_val v ty -- renumber the type first! + = --pprTrace "ppr_val:" (ppr PprDebug v) $ + pp_sig v (initNmbr (nmbrType ty)) -do_instance better_id_fn inline_env - (InstInfo clas tv_tmpls ty inst_decl_theta dfun_theta dfun_id constm_ids _ from_here modname _ _) - = 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 getClassOpString (getClassOps 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))] - 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]) - ) +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] } + +ppr_forall [] = uppNil +ppr_forall tvs = uppBesides [ uppStr "__forall__ [", uppInterleave uppComma (map ppr_tyvar tvs), uppStr "] " ] \end{code} -%************************************************************************ -%* * -\subsection[utils-InstInfos]{Utility functions for @InstInfos@} -%* * -%************************************************************************ +\begin{code} +ppr_tycon tycon + = --pprTrace "ppr_tycon:" (ppr PprDebug tycon) $ + ppr_tc (initNmbr (nmbrTyCon tycon)) -ToDo: perhaps move. +------------------------ +ppr_tc (PrimTyCon _ n _ _) + = uppCat [ uppStr "{- data", ppr_name n, uppStr " *built-in* -}" ] -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 +ppr_tc FunTyCon + = uppCat [ uppStr "{- data", ppr_name FunTyCon, uppStr " *built-in* -}" ] -in_export_list_or_among_dotdot_modules ignore_Mdotdots (in_export_list, among_dotdot_modules) tc - = if in_export_list (getOccurrenceName tc) then - True - else --- pprTrace "in_export:" (ppAbove (ppr PprDebug ignore_Mdotdots) (ppPStr (getOccurrenceName tc))) ( - if ignore_Mdotdots then - False - else - any among_dotdot_modules (getInformingModules tc) --- ) +ppr_tc (TupleTyCon _ n _) + = uppCat [ uppStr "{- ", ppr_name n, uppStr "-}" ] -is_mentionable tc - = not (from_PreludeCore_or_Builtin tc) || opt_CompilingPrelude +ppr_tc (SynTyCon _ n _ _ tvs expand) + = let + pp_tyvars = map ppr_tyvar tvs + in + 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 (getOrigName 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) - }} + 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}