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, idCgInfo,
34 import DataCon ( StrictnessMark(..), dataConId, dataConSig, dataConFieldLabels, dataConStrictMarks )
36 import CoreSyn ( CoreRule(..) )
37 import CoreUnfold ( neverUnfold, unfoldingTemplate )
38 import PprCore ( pprIdCoreRule )
39 import Name ( getName, nameModule, toRdrName, isGlobalName, Name, NamedThing(..) )
41 import OccName ( pprOccName )
42 import TyCon ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon, tyConGenIds,
43 tyConTheta, tyConTyVars, tyConDataCons, tyConFamilySize, isClassTyCon
45 import Class ( classExtraBigSig, classTyCon, DefMeth(..) )
46 import FieldLabel ( fieldLabelType )
47 import Type ( splitSigmaTy, tidyTopType, deNoteType )
48 import SrcLoc ( noSrcLoc )
50 import Module ( ModuleName )
51 import Util ( sortLt )
53 import IO ( IOMode(..), openFile, hClose )
57 %************************************************************************
59 \subsection{Completing an interface}
61 %************************************************************************
64 completeIface :: Maybe ModIface -- The old interface, if we have it
65 -> ModIface -- The new one, minus the decls and versions
66 -> ModDetails -- The ModDetails for this module
67 -> (ModIface, Maybe SDoc) -- The new one, complete with decls and versions
68 -- The SDoc is a debug document giving differences
69 -- Nothing => no change
71 -- NB: 'Nothing' means that even the usages havn't changed, so there's no
72 -- need to write a new interface file. But even if the usages have
73 -- changed, the module version may not have.
74 completeIface maybe_old_iface new_iface mod_details
75 = addVersionInfo maybe_old_iface (new_iface { mi_decls = new_decls })
77 new_decls = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
78 inst_dcls = map ifaceInstance (md_insts mod_details)
79 ty_cls_dcls = foldNameEnv ifaceTyCls [] (md_types mod_details)
80 rule_dcls = map ifaceRule (md_rules mod_details)
85 ifaceTyCls :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
86 ifaceTyCls (AClass clas) so_far
89 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
90 tcdName = getName clas,
91 tcdTyVars = toHsTyVars clas_tyvars,
92 tcdFDs = toHsFDs clas_fds,
93 tcdSigs = map toClassOpSig op_stuff,
95 tcdSysNames = sys_names,
98 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
99 tycon = classTyCon clas
100 data_con = head (tyConDataCons tycon)
101 sys_names = mkClassDeclSysNames (getName tycon, getName data_con,
102 getName (dataConId data_con), map getName sc_sels)
104 toClassOpSig (sel_id, def_meth)
105 = ASSERT(sel_tyvars == clas_tyvars)
106 ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
108 (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
109 def_meth' = case def_meth of
110 NoDefMeth -> NoDefMeth
111 GenDefMeth -> GenDefMeth
112 DefMeth id -> DefMeth (getName id)
114 ifaceTyCls (ATyCon tycon) so_far
115 | isClassTyCon tycon = so_far
116 | otherwise = ty_decl : so_far
118 ty_decl | isSynTyCon tycon
119 = TySynonym { tcdName = getName tycon,
120 tcdTyVars = toHsTyVars tyvars,
121 tcdSynRhs = toHsType syn_ty,
125 = TyData { tcdND = new_or_data,
126 tcdCtxt = toHsContext (tyConTheta tycon),
127 tcdName = getName tycon,
128 tcdTyVars = toHsTyVars tyvars,
129 tcdCons = map ifaceConDecl (tyConDataCons tycon),
130 tcdNCons = tyConFamilySize tycon,
132 tcdSysNames = map getName (tyConGenIds tycon),
135 | otherwise = pprPanic "ifaceTyCls" (ppr tycon)
137 tyvars = tyConTyVars tycon
138 (_, syn_ty) = getSynTyConDefn tycon
139 new_or_data | isNewTyCon tycon = NewType
140 | otherwise = DataType
142 ifaceConDecl data_con
143 = ConDecl (getName data_con) (getName (dataConId data_con))
144 (toHsTyVars ex_tyvars)
145 (toHsContext ex_theta)
148 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
149 field_labels = dataConFieldLabels data_con
150 strict_marks = dataConStrictMarks data_con
151 details | null field_labels
152 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
153 VanillaCon (zipWith mk_bang_ty strict_marks arg_tys)
156 = RecCon (zipWith mk_field strict_marks field_labels)
158 mk_bang_ty NotMarkedStrict ty = Unbanged (toHsType ty)
159 mk_bang_ty (MarkedUnboxed _ _) ty = Unpacked (toHsType ty)
160 mk_bang_ty MarkedStrict ty = Banged (toHsType ty)
162 mk_field strict_mark field_label
163 = ([getName field_label], mk_bang_ty strict_mark (fieldLabelType field_label))
165 ifaceTyCls (AnId id) so_far
166 | isImplicitId id = so_far
167 | otherwise = iface_sig : so_far
169 iface_sig = IfaceSig { tcdName = getName id,
170 tcdType = toHsType id_type,
171 tcdIdInfo = hs_idinfo,
176 cg_info = idCgInfo id
177 arity_info = cgArity cg_info
178 caf_info = cgCafInfo cg_info
180 hs_idinfo | opt_OmitInterfacePragmas = []
181 | otherwise = arity_hsinfo ++ caf_hsinfo ++ cpr_hsinfo ++
182 strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
184 ------------ Arity --------------
185 arity_hsinfo | arity_info == 0 = []
186 | otherwise = [HsArity arity_info]
188 ------------ Caf Info --------------
189 caf_hsinfo = case caf_info of
190 NoCafRefs -> [HsNoCafRefs]
193 ------------ CPR Info --------------
194 cpr_hsinfo = case cprInfo id_info of
195 ReturnsCPR -> [HsCprInfo]
198 ------------ Strictness --------------
199 strict_hsinfo = case strictnessInfo id_info of
200 NoStrictnessInfo -> []
201 info -> [HsStrictness info]
203 ------------ Worker --------------
204 work_info = workerInfo id_info
205 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
206 wrkr_hsinfo = case work_info of
207 HasWorker work_id wrap_arity ->
208 [HsWorker (getName work_id) wrap_arity]
211 ------------ Unfolding --------------
212 -- The unfolding is redundant if there is a worker
213 unfold_info = unfoldingInfo id_info
214 inline_prag = inlinePragInfo id_info
215 rhs = unfoldingTemplate unfold_info
216 unfold_hsinfo | neverUnfold unfold_info
218 | otherwise = [HsUnfold inline_prag (toUfExpr rhs)]
222 ifaceInstance :: DFunId -> RenamedInstDecl
223 ifaceInstance dfun_id
224 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
226 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
227 -- The deNoteType is very important. It removes all type
228 -- synonyms from the instance type in interface files.
229 -- That in turn makes sure that when reading in instance decls
230 -- from interface files that the 'gating' mechanism works properly.
231 -- Otherwise you could have
232 -- type Tibble = T Int
233 -- instance Foo Tibble where ...
234 -- and this instance decl wouldn't get imported into a module
235 -- that mentioned T but not Tibble.
237 ifaceRule (id, BuiltinRule _)
238 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
240 ifaceRule (id, Rule name bndrs args rhs)
241 = IfaceRule name (map toUfBndr bndrs) (getName id)
242 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
245 = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
249 %************************************************************************
251 \subsection{Checking if the new interface is up to date
253 %************************************************************************
256 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
257 -> ModIface -- The new interface decls
258 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
259 -- Just mi => Here is the new interface to write
260 -- with correct version numbers
262 -- NB: the fixities, declarations, rules are all assumed
263 -- to be sorted by increasing order of hsDeclName, so that
264 -- we can compare for equality
266 addVersionInfo Nothing new_iface
267 -- No old interface, so definitely write a new one!
268 = (new_iface, Just (text "No old interface available"))
270 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
271 mi_decls = old_decls,
272 mi_fixities = old_fixities,
273 mi_deprecs = old_deprecs }))
274 new_iface@(ModIface { mi_decls = new_decls,
275 mi_fixities = new_fixities,
276 mi_deprecs = new_deprecs })
278 | no_output_change && no_usage_change
279 = (new_iface, Nothing)
280 -- don't return the old iface because it may not have an
281 -- mi_globals field set to anything reasonable.
283 | otherwise -- Add updated version numbers
284 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
285 (final_iface, Just pp_diffs)
288 final_iface = new_iface { mi_version = new_version }
289 old_mod_vers = vers_module old_version
290 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
291 vers_exports = bumpVersion no_export_change (vers_exports old_version),
292 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
293 vers_decls = tc_vers }
295 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
296 no_usage_change = mi_usages old_iface == mi_usages new_iface
298 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
299 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
300 no_deprec_change = old_deprecs == new_deprecs
302 -- Fill in the version number on the new declarations by looking at the old declarations.
303 -- Set the flag if anything changes.
304 -- Assumes that the decls are sorted by hsDeclName.
305 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
306 (dcl_tycl old_decls) (dcl_tycl new_decls)
307 pp_diffs = vcat [pp_tc_diffs,
308 pp_change no_export_change "Export list",
309 pp_change no_rule_change "Rules",
310 pp_change no_deprec_change "Deprecations",
311 pp_change no_usage_change "Usages"]
312 pp_change True what = empty
313 pp_change False what = text what <+> ptext SLIT("changed")
315 diffDecls :: VersionInfo -- Old version
316 -> NameEnv Fixity -> NameEnv Fixity -- Old and new fixities
317 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
318 -> (Bool, -- True <=> no change
319 SDoc, -- Record of differences
320 NameEnv Version) -- New version map
322 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
323 old_fixities new_fixities old new
324 = diff True empty emptyNameEnv old new
326 -- When seeing if two decls are the same,
327 -- remember to check whether any relevant fixity has changed
328 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
329 same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
331 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
332 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
333 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
335 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
336 -- When adding a new item, start from the old module version
337 -- This way, if you have version 4 of f, then delete f, then add f again,
338 -- you'll get version 6 of f, which will (correctly) force recompilation of
341 diff ok_so_far pp new_vers (od:ods) (nd:nds)
342 = case od_name `compare` nd_name of
343 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
344 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
345 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
346 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
348 od_name = tyClDeclName od
349 nd_name = tyClDeclName nd
350 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
351 old_version = lookupVersion old_decls_vers od_name
353 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
354 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
355 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
356 (ptext SLIT("New:") <+> ppr nd))
361 %************************************************************************
363 \subsection{Writing ModDetails}
365 %************************************************************************
368 pprModDetails :: ModDetails -> SDoc
369 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
370 = vcat [ dump_types dfun_ids type_env
371 , dump_insts dfun_ids
374 dump_types dfun_ids type_env
375 = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
377 ids = [id | AnId id <- nameEnvElts type_env, want_sig id]
378 want_sig id | opt_PprStyle_Debug = True
379 | otherwise = isLocalId id &&
380 isGlobalName (idName id) &&
381 not (id `elem` dfun_ids)
382 -- isLocalId ignores data constructors, records selectors etc
383 -- The isGlobalName ignores local dictionary and method bindings
384 -- that the type checker has invented. User-defined things have
387 dump_insts [] = empty
388 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
391 -- Print type signatures
392 -- Convert to HsType so that we get source-language style printing
393 -- And sort by RdrName
394 = vcat $ map ppr_sig $ sortLt lt_sig $
395 [ (toRdrName id, toHsType (idType id))
398 lt_sig (n1,_) (n2,_) = n1 < n2
399 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
401 dump_rules [] = empty
402 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
403 nest 4 (vcat (map pprIdCoreRule rs)),
408 %************************************************************************
410 \subsection{Writing an interface file}
412 %************************************************************************
415 writeIface :: FilePath -> ModIface -> IO ()
416 writeIface hi_path mod_iface
417 = do { if_hdl <- openFile hi_path WriteMode
418 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
422 -- Print names unqualified if they are from this module
423 from_this_mod n = nameModule n == this_mod
424 this_mod = mi_module mod_iface
426 pprIface :: ModIface -> SDoc
428 = vcat [ ptext SLIT("__interface")
429 <+> doubleQuotes (ptext opt_InPackage)
430 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
432 <+> (if mi_orphan iface then char '!' else empty)
433 <+> int opt_HiVersion
434 <+> ptext SLIT("where")
436 , vcat (map pprExport (mi_exports iface))
437 , vcat (map pprUsage (mi_usages iface))
439 , pprFixities (mi_fixities iface) (dcl_tycl decls)
440 , pprIfaceDecls (vers_decls version_info) decls
441 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
444 version_info = mi_version iface
445 decls = mi_decls iface
446 exp_vers = vers_exports version_info
447 rule_vers = vers_rules version_info
449 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
450 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
453 When printing export lists, we print like this:
455 AvailTC C [C, x, y] C(x,y)
456 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
459 pprExport :: (ModuleName, Avails) -> SDoc
460 pprExport (mod, items)
461 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
463 pp_avail :: AvailInfo -> SDoc
464 pp_avail (Avail name) = pprOcc name
465 pp_avail (AvailTC n []) = empty
466 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
467 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
470 pp_export names = braces (hsep (map pprOcc names))
472 pprOcc :: Name -> SDoc -- Print the occurrence name only
473 pprOcc n = pprOccName (nameOccName n)
478 pprUsage :: ImportVersion Name -> SDoc
479 pprUsage (m, has_orphans, is_boot, whats_imported)
480 = hsep [ptext SLIT("import"), ppr m,
482 pp_versions whats_imported
485 pp_orphan | has_orphans = char '!'
487 pp_boot | is_boot = char '@'
490 -- Importing the whole module is indicated by an empty list
491 pp_versions NothingAtAll = empty
492 pp_versions (Everything v) = dcolon <+> int v
493 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
494 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
496 pp_export_version Nothing = empty
497 pp_export_version (Just v) = int v
501 pprIfaceDecls version_map decls
502 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
503 , vcat (map ppr_decl (dcl_tycl decls))
506 ppr_decl d = ppr_vers d <+> ppr d <> semi
508 -- Print the version for the decl
509 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
515 pprFixities fixity_map decls
516 = hsep [ ppr fix <+> ppr n
518 (n,_) <- tyClDeclNames d,
519 Just fix <- [lookupNameEnv fixity_map n]] <> semi
521 -- Disgusting to print these two together, but that's
522 -- the way the interface parser currently expects them.
523 pprRulesAndDeprecs [] NoDeprecs = empty
524 pprRulesAndDeprecs rules deprecs
525 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
528 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
530 pp_deprecs NoDeprecs = empty
531 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
533 guts = case deprecs of
534 DeprecAll txt -> doubleQuotes (ptext txt)
535 DeprecSome env -> ppr_deprec_env env
537 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
539 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)