2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[MkIface]{Print an interface for a module}
8 completeIface, writeIface,
9 pprModDetails, pprIface, pprUsage
12 #include "HsVersions.h"
15 import HsCore ( HsIdInfo(..), UfExpr(..), toUfExpr, toUfBndr )
16 import HsTypes ( toHsTyVars )
17 import BasicTypes ( Fixity(..), NewOrData(..),
18 Version, initialVersion, bumpVersion,
21 import RnHsSyn ( RenamedInstDecl, RenamedTyClDecl )
22 import HscTypes ( VersionInfo(..), ModIface(..), ModDetails(..),
23 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
24 TyThing(..), DFunId, Avails,
25 WhatsImported(..), GenAvailInfo(..),
26 ImportVersion, AvailInfo, Deprecations(..),
31 import Id ( idType, idInfo, isImplicitId, isLocalId, idName )
32 import DataCon ( StrictnessMark(..), dataConId, dataConSig, dataConFieldLabels, dataConStrictMarks )
34 import CoreSyn ( CoreBind, CoreRule(..) )
35 import CoreUnfold ( neverUnfold, unfoldingTemplate )
36 import PprCore ( pprIdCoreRule )
37 import Name ( getName, nameModule, toRdrName, isGlobalName, Name, NamedThing(..) )
39 import OccName ( pprOccName )
40 import TyCon ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon, tyConGenIds,
41 tyConTheta, tyConTyVars, tyConDataCons, tyConFamilySize, isClassTyCon
43 import Class ( classExtraBigSig, classTyCon, DefMeth(..) )
44 import FieldLabel ( fieldLabelType )
45 import Type ( splitSigmaTy, tidyTopType, deNoteType )
46 import SrcLoc ( noSrcLoc )
48 import Module ( ModuleName )
49 import Util ( sortLt )
51 import IO ( IOMode(..), openFile, hClose )
55 %************************************************************************
57 \subsection{Completing an interface}
59 %************************************************************************
62 completeIface :: Maybe ModIface -- The old interface, if we have it
63 -> ModIface -- The new one, minus the decls and versions
64 -> ModDetails -- The ModDetails for this module
65 -> (ModIface, Maybe SDoc) -- The new one, complete with decls and versions
66 -- The SDoc is a debug document giving differences
67 -- Nothing => no change
69 -- NB: 'Nothing' means that even the usages havn't changed, so there's no
70 -- need to write a new interface file. But even if the usages have
71 -- changed, the module version may not have.
72 completeIface maybe_old_iface new_iface mod_details
73 = addVersionInfo maybe_old_iface (new_iface { mi_decls = new_decls })
75 new_decls = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
76 inst_dcls = map ifaceInstance (md_insts mod_details)
77 ty_cls_dcls = foldNameEnv ifaceTyCls [] (md_types mod_details)
78 rule_dcls = map ifaceRule (md_rules mod_details)
83 ifaceTyCls :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
84 ifaceTyCls (AClass clas) so_far
87 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
88 tcdName = getName clas,
89 tcdTyVars = toHsTyVars clas_tyvars,
90 tcdFDs = toHsFDs clas_fds,
91 tcdSigs = map toClassOpSig op_stuff,
93 tcdSysNames = sys_names,
96 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
97 tycon = classTyCon clas
98 data_con = head (tyConDataCons tycon)
99 sys_names = mkClassDeclSysNames (getName tycon, getName data_con,
100 getName (dataConId data_con), map getName sc_sels)
102 toClassOpSig (sel_id, def_meth)
103 = ASSERT(sel_tyvars == clas_tyvars)
104 ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
106 (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
107 def_meth' = case def_meth of
108 NoDefMeth -> NoDefMeth
109 GenDefMeth -> GenDefMeth
110 DefMeth id -> DefMeth (getName id)
112 ifaceTyCls (ATyCon tycon) so_far
113 | isClassTyCon tycon = so_far
114 | otherwise = ty_decl : so_far
116 ty_decl | isSynTyCon tycon
117 = TySynonym { tcdName = getName tycon,
118 tcdTyVars = toHsTyVars tyvars,
119 tcdSynRhs = toHsType syn_ty,
123 = TyData { tcdND = new_or_data,
124 tcdCtxt = toHsContext (tyConTheta tycon),
125 tcdName = getName tycon,
126 tcdTyVars = toHsTyVars tyvars,
127 tcdCons = map ifaceConDecl (tyConDataCons tycon),
128 tcdNCons = tyConFamilySize tycon,
130 tcdSysNames = map getName (tyConGenIds tycon),
133 | otherwise = pprPanic "ifaceTyCls" (ppr tycon)
135 tyvars = tyConTyVars tycon
136 (_, syn_ty) = getSynTyConDefn tycon
137 new_or_data | isNewTyCon tycon = NewType
138 | otherwise = DataType
140 ifaceConDecl data_con
141 = ConDecl (getName data_con) (getName (dataConId data_con))
142 (toHsTyVars ex_tyvars)
143 (toHsContext ex_theta)
146 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
147 field_labels = dataConFieldLabels data_con
148 strict_marks = dataConStrictMarks data_con
149 details | null field_labels
150 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
151 VanillaCon (zipWith mk_bang_ty strict_marks arg_tys)
154 = RecCon (zipWith mk_field strict_marks field_labels)
156 mk_bang_ty NotMarkedStrict ty = Unbanged (toHsType ty)
157 mk_bang_ty (MarkedUnboxed _ _) ty = Unpacked (toHsType ty)
158 mk_bang_ty MarkedStrict ty = Banged (toHsType ty)
160 mk_field strict_mark field_label
161 = ([getName field_label], mk_bang_ty strict_mark (fieldLabelType field_label))
163 ifaceTyCls (AnId id) so_far
164 | isImplicitId id = so_far
165 | otherwise = iface_sig : so_far
167 iface_sig = IfaceSig { tcdName = getName id,
168 tcdType = toHsType id_type,
169 tcdIdInfo = hs_idinfo,
175 hs_idinfo | opt_OmitInterfacePragmas = []
176 | otherwise = arity_hsinfo ++ caf_hsinfo ++ cpr_hsinfo ++
177 strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
179 ------------ Arity --------------
180 arity_hsinfo = case arityInfo id_info of
181 a@(ArityExactly n) -> [HsArity a]
184 ------------ Caf Info --------------
185 caf_hsinfo = case cafInfo id_info of
186 NoCafRefs -> [HsNoCafRefs]
189 ------------ CPR Info --------------
190 cpr_hsinfo = case cprInfo id_info of
191 ReturnsCPR -> [HsCprInfo]
194 ------------ Strictness --------------
195 strict_hsinfo = case strictnessInfo id_info of
196 NoStrictnessInfo -> []
197 info -> [HsStrictness info]
199 ------------ Worker --------------
200 work_info = workerInfo id_info
201 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
202 wrkr_hsinfo = case work_info of
203 HasWorker work_id wrap_arity -> [HsWorker (getName work_id)]
206 ------------ Unfolding --------------
207 -- The unfolding is redundant if there is a worker
208 unfold_info = unfoldingInfo id_info
209 inline_prag = inlinePragInfo id_info
210 rhs = unfoldingTemplate unfold_info
211 unfold_hsinfo | neverUnfold unfold_info
213 | otherwise = [HsUnfold inline_prag (toUfExpr rhs)]
217 ifaceInstance :: DFunId -> RenamedInstDecl
218 ifaceInstance dfun_id
219 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
221 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
222 -- The deNoteType is very important. It removes all type
223 -- synonyms from the instance type in interface files.
224 -- That in turn makes sure that when reading in instance decls
225 -- from interface files that the 'gating' mechanism works properly.
226 -- Otherwise you could have
227 -- type Tibble = T Int
228 -- instance Foo Tibble where ...
229 -- and this instance decl wouldn't get imported into a module
230 -- that mentioned T but not Tibble.
232 ifaceRule (id, BuiltinRule _)
233 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
235 ifaceRule (id, Rule name bndrs args rhs)
236 = IfaceRule name (map toUfBndr bndrs) (getName id)
237 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
240 = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
244 %************************************************************************
246 \subsection{Checking if the new interface is up to date
248 %************************************************************************
251 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
252 -> ModIface -- The new interface decls
253 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
254 -- Just mi => Here is the new interface to write
255 -- with correct version numbers
257 -- NB: the fixities, declarations, rules are all assumed
258 -- to be sorted by increasing order of hsDeclName, so that
259 -- we can compare for equality
261 addVersionInfo Nothing new_iface
262 -- No old interface, so definitely write a new one!
263 = (new_iface, Just (text "No old interface available"))
265 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
266 mi_decls = old_decls,
267 mi_fixities = old_fixities,
268 mi_deprecs = old_deprecs }))
269 new_iface@(ModIface { mi_decls = new_decls,
270 mi_fixities = new_fixities,
271 mi_deprecs = new_deprecs })
273 | no_output_change && no_usage_change
274 = (new_iface, Nothing)
275 -- don't return the old iface because it may not have an
276 -- mi_globals field set to anything reasonable.
278 | otherwise -- Add updated version numbers
279 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
280 (final_iface, Just pp_diffs)
283 final_iface = new_iface { mi_version = new_version }
284 old_mod_vers = vers_module old_version
285 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
286 vers_exports = bumpVersion no_export_change (vers_exports old_version),
287 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
288 vers_decls = tc_vers }
290 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
291 no_usage_change = mi_usages old_iface == mi_usages new_iface
293 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
294 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
295 no_deprec_change = old_deprecs == new_deprecs
297 -- Fill in the version number on the new declarations by looking at the old declarations.
298 -- Set the flag if anything changes.
299 -- Assumes that the decls are sorted by hsDeclName.
300 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
301 (dcl_tycl old_decls) (dcl_tycl new_decls)
302 pp_diffs = vcat [pp_tc_diffs,
303 pp_change no_export_change "Export list",
304 pp_change no_rule_change "Rules",
305 pp_change no_deprec_change "Deprecations",
306 pp_change no_usage_change "Usages"]
307 pp_change True what = empty
308 pp_change False what = text what <+> ptext SLIT("changed")
310 diffDecls :: VersionInfo -- Old version
311 -> NameEnv Fixity -> NameEnv Fixity -- Old and new fixities
312 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
313 -> (Bool, -- True <=> no change
314 SDoc, -- Record of differences
315 NameEnv Version) -- New version map
317 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
318 old_fixities new_fixities old new
319 = diff True empty emptyNameEnv old new
321 -- When seeing if two decls are the same,
322 -- remember to check whether any relevant fixity has changed
323 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
324 same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
326 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
327 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
328 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
330 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
331 -- When adding a new item, start from the old module version
332 -- This way, if you have version 4 of f, then delete f, then add f again,
333 -- you'll get version 6 of f, which will (correctly) force recompilation of
336 diff ok_so_far pp new_vers (od:ods) (nd:nds)
337 = case od_name `compare` nd_name of
338 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
339 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
340 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
341 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
343 od_name = tyClDeclName od
344 nd_name = tyClDeclName nd
345 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
346 old_version = lookupVersion old_decls_vers od_name
348 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
349 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
350 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
351 (ptext SLIT("New:") <+> ppr nd))
356 %************************************************************************
358 \subsection{Writing ModDetails}
360 %************************************************************************
363 pprModDetails :: ModDetails -> SDoc
364 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
365 = vcat [ dump_types dfun_ids type_env
366 , dump_insts dfun_ids
369 dump_types dfun_ids type_env
370 = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
372 ids = [id | AnId id <- nameEnvElts type_env, want_sig id]
373 want_sig id | opt_PprStyle_Debug = True
374 | otherwise = isLocalId id &&
375 isGlobalName (idName id) &&
376 not (id `elem` dfun_ids)
377 -- isLocalId ignores data constructors, records selectors etc
378 -- The isGlobalName ignores local dictionary and method bindings
379 -- that the type checker has invented. User-defined things have
382 dump_insts [] = empty
383 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
386 -- Print type signatures
387 -- Convert to HsType so that we get source-language style printing
388 -- And sort by RdrName
389 = vcat $ map ppr_sig $ sortLt lt_sig $
390 [ (toRdrName id, toHsType (idType id))
393 lt_sig (n1,_) (n2,_) = n1 < n2
394 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
396 dump_rules [] = empty
397 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
398 nest 4 (vcat (map pprIdCoreRule rs)),
403 %************************************************************************
405 \subsection{Writing an interface file}
407 %************************************************************************
410 writeIface :: FilePath -> ModIface -> IO ()
411 writeIface hi_path mod_iface
412 = do { if_hdl <- openFile hi_path WriteMode
413 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
417 -- Print names unqualified if they are from this module
418 from_this_mod n = nameModule n == this_mod
419 this_mod = mi_module mod_iface
421 pprIface :: ModIface -> SDoc
423 = vcat [ ptext SLIT("__interface")
424 <+> doubleQuotes (ptext opt_InPackage)
425 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
427 <+> (if mi_orphan iface then char '!' else empty)
428 <+> int opt_HiVersion
429 <+> ptext SLIT("where")
431 , vcat (map pprExport (mi_exports iface))
432 , vcat (map pprUsage (mi_usages iface))
434 , pprFixities (mi_fixities iface) (dcl_tycl decls)
435 , pprIfaceDecls (vers_decls version_info) decls
436 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
439 version_info = mi_version iface
440 decls = mi_decls iface
441 exp_vers = vers_exports version_info
442 rule_vers = vers_rules version_info
444 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
445 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
448 When printing export lists, we print like this:
450 AvailTC C [C, x, y] C(x,y)
451 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
454 pprExport :: (ModuleName, Avails) -> SDoc
455 pprExport (mod, items)
456 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
458 pp_avail :: AvailInfo -> SDoc
459 pp_avail (Avail name) = pprOcc name
460 pp_avail (AvailTC n []) = empty
461 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
462 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
465 pp_export names = braces (hsep (map pprOcc names))
467 pprOcc :: Name -> SDoc -- Print the occurrence name only
468 pprOcc n = pprOccName (nameOccName n)
473 pprUsage :: ImportVersion Name -> SDoc
474 pprUsage (m, has_orphans, is_boot, whats_imported)
475 = hsep [ptext SLIT("import"), ppr m,
477 pp_versions whats_imported
480 pp_orphan | has_orphans = char '!'
482 pp_boot | is_boot = char '@'
485 -- Importing the whole module is indicated by an empty list
486 pp_versions NothingAtAll = empty
487 pp_versions (Everything v) = dcolon <+> int v
488 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
489 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
491 pp_export_version Nothing = empty
492 pp_export_version (Just v) = int v
496 pprIfaceDecls version_map decls
497 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
498 , vcat (map ppr_decl (dcl_tycl decls))
501 ppr_decl d = ppr_vers d <+> ppr d <> semi
503 -- Print the version for the decl
504 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
510 pprFixities fixity_map decls
511 = hsep [ ppr fix <+> ppr n
513 (n,_) <- tyClDeclNames d,
514 Just fix <- [lookupNameEnv fixity_map n]] <> semi
516 -- Disgusting to print these two together, but that's
517 -- the way the interface parser currently expects them.
518 pprRulesAndDeprecs [] NoDeprecs = empty
519 pprRulesAndDeprecs rules deprecs
520 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
523 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
525 pp_deprecs NoDeprecs = empty
526 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
528 guts = case deprecs of
529 DeprecAll txt -> doubleQuotes (ptext txt)
530 DeprecSome env -> ppr_deprec_env env
532 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
534 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)