2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
5 \section[MkIface]{Print an interface for a module}
10 pprModDetails, pprIface, pprUsage
13 #include "HsVersions.h"
16 import HsCore ( HsIdInfo(..), UfExpr(..), toUfExpr, toUfBndr )
17 import HsTypes ( toHsTyVars )
18 import BasicTypes ( Fixity(..), NewOrData(..),
19 Version, initialVersion, bumpVersion,
22 import RnHsSyn ( RenamedInstDecl, RenamedTyClDecl )
23 import HscTypes ( VersionInfo(..), ModIface(..), ModDetails(..),
24 ModuleLocation(..), GhciMode(..),
25 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
26 TyThing(..), DFunId, Avails,
27 WhatsImported(..), GenAvailInfo(..),
28 ImportVersion, AvailInfo, Deprecations(..),
33 import Id ( idType, idInfo, isImplicitId, idCgInfo,
36 import DataCon ( dataConId, dataConSig, dataConFieldLabels, dataConStrictMarks )
38 import CoreSyn ( CoreRule(..) )
39 import CoreFVs ( ruleLhsFreeNames )
40 import CoreUnfold ( neverUnfold, unfoldingTemplate )
41 import PprCore ( pprIdCoreRule )
42 import Name ( getName, nameModule, toRdrName, isGlobalName,
43 nameIsLocalOrFrom, Name, NamedThing(..) )
46 import OccName ( pprOccName )
47 import TyCon ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon, tyConGenIds,
48 tyConTheta, tyConTyVars, tyConDataCons, tyConFamilySize,
49 isClassTyCon, isForeignTyCon
51 import Class ( classExtraBigSig, classTyCon, DefMeth(..) )
52 import FieldLabel ( fieldLabelType )
53 import TcType ( tcSplitSigmaTy, tidyTopType, deNoteType, namesOfDFunHead )
54 import SrcLoc ( noSrcLoc )
56 import Module ( ModuleName )
57 import Util ( sortLt )
58 import ErrUtils ( dumpIfSet_dyn )
61 import IO ( IOMode(..), openFile, hClose )
65 %************************************************************************
67 \subsection{Completing an interface}
69 %************************************************************************
75 mkFinalIface :: GhciMode
78 -> Maybe ModIface -- The old interface, if we have it
79 -> ModIface -- The new one, minus the decls and versions
80 -> ModDetails -- The ModDetails for this module
81 -> IO ModIface -- The new one, complete with decls and versions
83 -- a) completes the interface
84 -- b) writes it out to a file if necessary
86 mkFinalIface ghci_mode dflags location
87 maybe_old_iface new_iface new_details
89 -- Add the new declarations, and the is-orphan flag
90 let iface_w_decls = new_iface { mi_decls = new_decls,
91 mi_orphan = orphan_mod }
93 -- Add version information
94 ; let (final_iface, maybe_diffs) = addVersionInfo maybe_old_iface iface_w_decls
96 -- Write the interface file, if necessary
97 ; when (must_write_hi_file maybe_diffs)
98 (writeIface hi_file_path final_iface)
101 ; write_diffs dflags final_iface maybe_diffs
103 ; return final_iface }
106 must_write_hi_file Nothing = False
107 must_write_hi_file (Just diffs) = ghci_mode /= Interactive
108 -- We must write a new .hi file if there are some changes
109 -- and we're not in interactive mode
110 -- maybe_diffs = 'Nothing' means that even the usages havn't changed,
111 -- so there's no need to write a new interface file. But even if
112 -- the usages have changed, the module version may not have.
114 hi_file_path = ml_hi_file location
115 new_decls = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
116 inst_dcls = map ifaceInstance (md_insts new_details)
117 ty_cls_dcls = foldNameEnv ifaceTyCls [] (md_types new_details)
118 rule_dcls = map ifaceRule (md_rules new_details)
119 orphan_mod = isOrphanModule (mi_module new_iface) new_details
121 write_diffs dflags new_iface Nothing
122 = do when (dopt Opt_D_dump_hi_diffs dflags) (printDump (text "INTERFACE UNCHANGED"))
123 dumpIfSet_dyn dflags Opt_D_dump_hi "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
125 write_diffs dflags new_iface (Just sdoc_diffs)
126 = do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
127 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
131 isOrphanModule this_mod (ModDetails {md_insts = insts, md_rules = rules})
132 = any orphan_inst insts || any orphan_rule rules
134 orphan_inst dfun_id = no_locals (namesOfDFunHead (idType dfun_id))
135 orphan_rule rule = no_locals (ruleLhsFreeNames rule)
136 no_locals names = isEmptyNameSet (filterNameSet (nameIsLocalOrFrom this_mod) names)
140 ifaceTyCls :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
141 ifaceTyCls (AClass clas) so_far
144 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
145 tcdName = getName clas,
146 tcdTyVars = toHsTyVars clas_tyvars,
147 tcdFDs = toHsFDs clas_fds,
148 tcdSigs = map toClassOpSig op_stuff,
150 tcdSysNames = sys_names,
153 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
154 tycon = classTyCon clas
155 data_con = head (tyConDataCons tycon)
156 sys_names = mkClassDeclSysNames (getName tycon, getName data_con,
157 getName (dataConId data_con), map getName sc_sels)
159 toClassOpSig (sel_id, def_meth)
160 = ASSERT(sel_tyvars == clas_tyvars)
161 ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
163 (sel_tyvars, _, op_ty) = tcSplitSigmaTy (idType sel_id)
164 def_meth' = case def_meth of
165 NoDefMeth -> NoDefMeth
166 GenDefMeth -> GenDefMeth
167 DefMeth id -> DefMeth (getName id)
169 ifaceTyCls (ATyCon tycon) so_far
170 | isClassTyCon tycon = so_far
171 | otherwise = ty_decl : so_far
173 ty_decl | isSynTyCon tycon
174 = TySynonym { tcdName = getName tycon,
175 tcdTyVars = toHsTyVars tyvars,
176 tcdSynRhs = toHsType syn_ty,
180 = TyData { tcdND = new_or_data,
181 tcdCtxt = toHsContext (tyConTheta tycon),
182 tcdName = getName tycon,
183 tcdTyVars = toHsTyVars tyvars,
184 tcdCons = map ifaceConDecl (tyConDataCons tycon),
185 tcdNCons = tyConFamilySize tycon,
187 tcdSysNames = map getName (tyConGenIds tycon),
190 | isForeignTyCon tycon
191 = ForeignType { tcdName = getName tycon,
192 tcdFoType = DNType, -- The only case at present
195 | otherwise = pprPanic "ifaceTyCls" (ppr tycon)
197 tyvars = tyConTyVars tycon
198 (_, syn_ty) = getSynTyConDefn tycon
199 new_or_data | isNewTyCon tycon = NewType
200 | otherwise = DataType
202 ifaceConDecl data_con
203 = ConDecl (getName data_con) (getName (dataConId data_con))
204 (toHsTyVars ex_tyvars)
205 (toHsContext ex_theta)
208 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
209 field_labels = dataConFieldLabels data_con
210 strict_marks = drop (length ex_theta) (dataConStrictMarks data_con)
211 -- The 'drop' is because dataConStrictMarks
212 -- includes the existential dictionaries
213 details | null field_labels
214 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
215 VanillaCon (zipWith BangType strict_marks (map toHsType arg_tys))
218 = RecCon (zipWith mk_field strict_marks field_labels)
220 mk_field strict_mark field_label
221 = ([getName field_label], BangType strict_mark (toHsType (fieldLabelType field_label)))
223 ifaceTyCls (AnId id) so_far
224 | isImplicitId id = so_far
225 | otherwise = iface_sig : so_far
227 iface_sig = IfaceSig { tcdName = getName id,
228 tcdType = toHsType id_type,
229 tcdIdInfo = hs_idinfo,
234 cg_info = idCgInfo id
235 arity_info = cgArity cg_info
236 caf_info = cgCafInfo cg_info
238 hs_idinfo | opt_OmitInterfacePragmas = []
239 | otherwise = arity_hsinfo ++ caf_hsinfo ++ cpr_hsinfo ++
240 strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
242 ------------ Arity --------------
243 arity_hsinfo | arity_info == 0 = []
244 | otherwise = [HsArity arity_info]
246 ------------ Caf Info --------------
247 caf_hsinfo = case caf_info of
248 NoCafRefs -> [HsNoCafRefs]
251 ------------ CPR Info --------------
252 cpr_hsinfo = case cprInfo id_info of
253 ReturnsCPR -> [HsCprInfo]
256 ------------ Strictness --------------
257 strict_hsinfo = case strictnessInfo id_info of
258 NoStrictnessInfo -> []
259 info -> [HsStrictness info]
261 ------------ Worker --------------
262 work_info = workerInfo id_info
263 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
264 wrkr_hsinfo = case work_info of
265 HasWorker work_id wrap_arity ->
266 [HsWorker (getName work_id) wrap_arity]
269 ------------ Unfolding --------------
270 -- The unfolding is redundant if there is a worker
271 unfold_info = unfoldingInfo id_info
272 inline_prag = inlinePragInfo id_info
273 rhs = unfoldingTemplate unfold_info
274 unfold_hsinfo | neverUnfold unfold_info
276 | otherwise = [HsUnfold inline_prag (toUfExpr rhs)]
280 ifaceInstance :: DFunId -> RenamedInstDecl
281 ifaceInstance dfun_id
282 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
284 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
285 -- The deNoteType is very important. It removes all type
286 -- synonyms from the instance type in interface files.
287 -- That in turn makes sure that when reading in instance decls
288 -- from interface files that the 'gating' mechanism works properly.
289 -- Otherwise you could have
290 -- type Tibble = T Int
291 -- instance Foo Tibble where ...
292 -- and this instance decl wouldn't get imported into a module
293 -- that mentioned T but not Tibble.
295 ifaceRule (id, BuiltinRule _)
296 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
298 ifaceRule (id, Rule name bndrs args rhs)
299 = IfaceRule name (map toUfBndr bndrs) (getName id)
300 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
303 = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
307 %************************************************************************
309 \subsection{Checking if the new interface is up to date
311 %************************************************************************
314 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
315 -> ModIface -- The new interface decls
316 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
317 -- Just mi => Here is the new interface to write
318 -- with correct version numbers
320 -- NB: the fixities, declarations, rules are all assumed
321 -- to be sorted by increasing order of hsDeclName, so that
322 -- we can compare for equality
324 addVersionInfo Nothing new_iface
325 -- No old interface, so definitely write a new one!
326 = (new_iface, Just (text "No old interface available"))
328 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
329 mi_decls = old_decls,
330 mi_fixities = old_fixities,
331 mi_deprecs = old_deprecs }))
332 new_iface@(ModIface { mi_decls = new_decls,
333 mi_fixities = new_fixities,
334 mi_deprecs = new_deprecs })
336 | no_output_change && no_usage_change
337 = (new_iface, Nothing)
338 -- don't return the old iface because it may not have an
339 -- mi_globals field set to anything reasonable.
341 | otherwise -- Add updated version numbers
342 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
343 (final_iface, Just pp_diffs)
346 final_iface = new_iface { mi_version = new_version }
347 old_mod_vers = vers_module old_version
348 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
349 vers_exports = bumpVersion no_export_change (vers_exports old_version),
350 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
351 vers_decls = tc_vers }
353 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
354 no_usage_change = mi_usages old_iface == mi_usages new_iface
356 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
357 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
358 no_deprec_change = old_deprecs == new_deprecs
360 -- Fill in the version number on the new declarations by looking at the old declarations.
361 -- Set the flag if anything changes.
362 -- Assumes that the decls are sorted by hsDeclName.
363 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
364 (dcl_tycl old_decls) (dcl_tycl new_decls)
365 pp_diffs = vcat [pp_tc_diffs,
366 pp_change no_export_change "Export list",
367 pp_change no_rule_change "Rules",
368 pp_change no_deprec_change "Deprecations",
369 pp_change no_usage_change "Usages"]
370 pp_change True what = empty
371 pp_change False what = text what <+> ptext SLIT("changed")
373 diffDecls :: VersionInfo -- Old version
374 -> NameEnv Fixity -> NameEnv Fixity -- Old and new fixities
375 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
376 -> (Bool, -- True <=> no change
377 SDoc, -- Record of differences
378 NameEnv Version) -- New version map
380 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
381 old_fixities new_fixities old new
382 = diff True empty emptyNameEnv old new
384 -- When seeing if two decls are the same,
385 -- remember to check whether any relevant fixity has changed
386 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
387 same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
389 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
390 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
391 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
393 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
394 -- When adding a new item, start from the old module version
395 -- This way, if you have version 4 of f, then delete f, then add f again,
396 -- you'll get version 6 of f, which will (correctly) force recompilation of
399 diff ok_so_far pp new_vers (od:ods) (nd:nds)
400 = case od_name `compare` nd_name of
401 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
402 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
403 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
404 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
406 od_name = tyClDeclName od
407 nd_name = tyClDeclName nd
408 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
409 old_version = lookupVersion old_decls_vers od_name
411 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
412 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
413 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
414 (ptext SLIT("New:") <+> ppr nd))
419 %************************************************************************
421 \subsection{Writing ModDetails}
423 %************************************************************************
426 pprModDetails :: ModDetails -> SDoc
427 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
428 = vcat [ dump_types dfun_ids type_env
429 , dump_insts dfun_ids
432 dump_types dfun_ids type_env
433 = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
435 ids = [id | AnId id <- nameEnvElts type_env, want_sig id]
436 want_sig id | opt_PprStyle_Debug = True
437 | otherwise = isLocalId id &&
438 isGlobalName (idName id) &&
439 not (id `elem` dfun_ids)
440 -- isLocalId ignores data constructors, records selectors etc
441 -- The isGlobalName ignores local dictionary and method bindings
442 -- that the type checker has invented. User-defined things have
445 dump_insts [] = empty
446 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
449 -- Print type signatures
450 -- Convert to HsType so that we get source-language style printing
451 -- And sort by RdrName
452 = vcat $ map ppr_sig $ sortLt lt_sig $
453 [ (toRdrName id, toHsType (idType id))
456 lt_sig (n1,_) (n2,_) = n1 < n2
457 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
459 dump_rules [] = empty
460 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
461 nest 4 (vcat (map pprIdCoreRule rs)),
466 %************************************************************************
468 \subsection{Writing an interface file}
470 %************************************************************************
473 writeIface :: FilePath -> ModIface -> IO ()
474 writeIface hi_path mod_iface
475 = do { if_hdl <- openFile hi_path WriteMode
476 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
480 -- Print names unqualified if they are from this module
481 from_this_mod n = nameModule n == this_mod
482 this_mod = mi_module mod_iface
484 pprIface :: ModIface -> SDoc
486 = vcat [ ptext SLIT("__interface")
487 <+> doubleQuotes (ptext opt_InPackage)
488 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
490 <+> (if mi_orphan iface then char '!' else empty)
491 <+> int opt_HiVersion
492 <+> ptext SLIT("where")
494 , vcat (map pprExport (mi_exports iface))
495 , vcat (map pprUsage (mi_usages iface))
497 , pprFixities (mi_fixities iface) (dcl_tycl decls)
498 , pprIfaceDecls (vers_decls version_info) decls
499 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
502 version_info = mi_version iface
503 decls = mi_decls iface
504 exp_vers = vers_exports version_info
505 rule_vers = vers_rules version_info
507 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
508 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
511 When printing export lists, we print like this:
513 AvailTC C [C, x, y] C(x,y)
514 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
517 pprExport :: (ModuleName, Avails) -> SDoc
518 pprExport (mod, items)
519 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
521 pp_avail :: AvailInfo -> SDoc
522 pp_avail (Avail name) = pprOcc name
523 pp_avail (AvailTC n []) = empty
524 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
525 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
528 pp_export names = braces (hsep (map pprOcc names))
530 pprOcc :: Name -> SDoc -- Print the occurrence name only
531 pprOcc n = pprOccName (nameOccName n)
536 pprUsage :: ImportVersion Name -> SDoc
537 pprUsage (m, has_orphans, is_boot, whats_imported)
538 = hsep [ptext SLIT("import"), ppr m,
540 pp_versions whats_imported
543 pp_orphan | has_orphans = char '!'
545 pp_boot | is_boot = char '@'
548 -- Importing the whole module is indicated by an empty list
549 pp_versions NothingAtAll = empty
550 pp_versions (Everything v) = dcolon <+> int v
551 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
552 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
554 pp_export_version Nothing = empty
555 pp_export_version (Just v) = int v
559 pprIfaceDecls version_map decls
560 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
561 , vcat (map ppr_decl (dcl_tycl decls))
564 ppr_decl d = ppr_vers d <+> ppr d <> semi
566 -- Print the version for the decl
567 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
573 pprFixities fixity_map decls
574 = hsep [ ppr fix <+> ppr n
576 (n,_) <- tyClDeclNames d,
577 Just fix <- [lookupNameEnv fixity_map n]] <> semi
579 -- Disgusting to print these two together, but that's
580 -- the way the interface parser currently expects them.
581 pprRulesAndDeprecs [] NoDeprecs = empty
582 pprRulesAndDeprecs rules deprecs
583 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
586 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
588 pp_deprecs NoDeprecs = empty
589 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
591 guts = case deprecs of
592 DeprecAll txt -> doubleQuotes (ptext txt)
593 DeprecSome env -> ppr_deprec_env env
595 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
597 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)