2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
5 \section[MkIface]{Print an interface for a module}
10 pprModDetails, pprIface, pprUsage,
14 #include "HsVersions.h"
17 import HsCore ( HsIdInfo(..), UfExpr(..), toUfExpr, toUfBndr )
18 import HsTypes ( toHsTyVars )
19 import BasicTypes ( Fixity(..), NewOrData(..),
20 Version, initialVersion, bumpVersion,
23 import RnHsSyn ( RenamedInstDecl, RenamedTyClDecl )
24 import HscTypes ( VersionInfo(..), ModIface(..), ModDetails(..),
25 ModuleLocation(..), GhciMode(..),
26 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
27 TyThing(..), DFunId, Avails,
28 WhatsImported(..), GenAvailInfo(..),
29 ImportVersion, AvailInfo, Deprecations(..),
34 import Id ( idType, idInfo, isImplicitId, idCgInfo,
37 import DataCon ( dataConId, dataConSig, dataConFieldLabels, dataConStrictMarks )
39 import CoreSyn ( CoreRule(..) )
40 import CoreFVs ( ruleLhsFreeNames )
41 import CoreUnfold ( neverUnfold, unfoldingTemplate )
42 import PprCore ( pprIdCoreRule )
43 import Name ( getName, nameModule, toRdrName, isGlobalName,
44 nameIsLocalOrFrom, Name, NamedThing(..) )
47 import OccName ( pprOccName )
48 import TyCon ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon, tyConGenIds,
49 tyConTheta, tyConTyVars, tyConDataCons, tyConFamilySize,
50 isClassTyCon, isForeignTyCon
52 import Class ( classExtraBigSig, classTyCon, DefMeth(..) )
53 import FieldLabel ( fieldLabelType )
54 import TcType ( tcSplitSigmaTy, tidyTopType, deNoteType, namesOfDFunHead )
55 import SrcLoc ( noSrcLoc )
57 import Module ( ModuleName )
58 import Util ( sortLt )
59 import ErrUtils ( dumpIfSet_dyn )
62 import IO ( IOMode(..), openFile, hClose )
66 %************************************************************************
68 \subsection{Completing an interface}
70 %************************************************************************
76 mkFinalIface :: GhciMode
79 -> Maybe ModIface -- The old interface, if we have it
80 -> ModIface -- The new one, minus the decls and versions
81 -> ModDetails -- The ModDetails for this module
82 -> IO ModIface -- The new one, complete with decls and versions
84 -- a) completes the interface
85 -- b) writes it out to a file if necessary
87 mkFinalIface ghci_mode dflags location
88 maybe_old_iface new_iface new_details
90 -- Add the new declarations, and the is-orphan flag
91 let iface_w_decls = new_iface { mi_decls = new_decls,
92 mi_orphan = orphan_mod }
94 -- Add version information
95 ; let (final_iface, maybe_diffs) = addVersionInfo maybe_old_iface iface_w_decls
97 -- Write the interface file, if necessary
98 ; when (must_write_hi_file maybe_diffs)
99 (writeIface hi_file_path final_iface)
102 ; write_diffs dflags final_iface maybe_diffs
104 ; return final_iface }
107 must_write_hi_file Nothing = False
108 must_write_hi_file (Just diffs) = ghci_mode /= Interactive
109 -- We must write a new .hi file if there are some changes
110 -- and we're not in interactive mode
111 -- maybe_diffs = 'Nothing' means that even the usages havn't changed,
112 -- so there's no need to write a new interface file. But even if
113 -- the usages have changed, the module version may not have.
115 hi_file_path = ml_hi_file location
116 new_decls = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
117 inst_dcls = map ifaceInstance (md_insts new_details)
118 ty_cls_dcls = foldNameEnv ifaceTyCls_acc [] (md_types new_details)
119 rule_dcls = map ifaceRule (md_rules new_details)
120 orphan_mod = isOrphanModule (mi_module new_iface) new_details
122 write_diffs dflags new_iface Nothing
123 = do when (dopt Opt_D_dump_hi_diffs dflags) (printDump (text "INTERFACE UNCHANGED"))
124 dumpIfSet_dyn dflags Opt_D_dump_hi "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
126 write_diffs dflags new_iface (Just sdoc_diffs)
127 = do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
128 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
132 isOrphanModule this_mod (ModDetails {md_insts = insts, md_rules = rules})
133 = any orphan_inst insts || any orphan_rule rules
135 orphan_inst dfun_id = no_locals (namesOfDFunHead (idType dfun_id))
136 orphan_rule rule = no_locals (ruleLhsFreeNames rule)
137 no_locals names = isEmptyNameSet (filterNameSet (nameIsLocalOrFrom this_mod) names)
140 Implicit Ids and class tycons aren't included in interface files, so
141 we miss them out of the accumulating parameter here.
144 ifaceTyCls_acc :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
145 ifaceTyCls_acc (AnId id) so_far | isImplicitId id = so_far
146 ifaceTyCls_acc (ATyCon id) so_far | isClassTyCon id = so_far
147 ifaceTyCls_acc other so_far = ifaceTyCls other : so_far
150 Convert *any* TyThing into a RenamedTyClDecl. Used both for
151 generating interface files and for the ':info' command in GHCi.
154 ifaceTyCls :: TyThing -> RenamedTyClDecl
155 ifaceTyCls (AClass clas) = cls_decl
157 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
158 tcdName = getName clas,
159 tcdTyVars = toHsTyVars clas_tyvars,
160 tcdFDs = toHsFDs clas_fds,
161 tcdSigs = map toClassOpSig op_stuff,
163 tcdSysNames = sys_names,
166 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
167 tycon = classTyCon clas
168 data_con = head (tyConDataCons tycon)
169 sys_names = mkClassDeclSysNames (getName tycon, getName data_con,
170 getName (dataConId data_con), map getName sc_sels)
172 toClassOpSig (sel_id, def_meth)
173 = ASSERT(sel_tyvars == clas_tyvars)
174 ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
176 (sel_tyvars, _, op_ty) = tcSplitSigmaTy (idType sel_id)
177 def_meth' = case def_meth of
178 NoDefMeth -> NoDefMeth
179 GenDefMeth -> GenDefMeth
180 DefMeth id -> DefMeth (getName id)
182 ifaceTyCls (ATyCon tycon) = ty_decl
184 ty_decl | isSynTyCon tycon
185 = TySynonym { tcdName = getName tycon,
186 tcdTyVars = toHsTyVars tyvars,
187 tcdSynRhs = toHsType syn_ty,
191 = TyData { tcdND = new_or_data,
192 tcdCtxt = toHsContext (tyConTheta tycon),
193 tcdName = getName tycon,
194 tcdTyVars = toHsTyVars tyvars,
195 tcdCons = map ifaceConDecl (tyConDataCons tycon),
196 tcdNCons = tyConFamilySize tycon,
198 tcdSysNames = map getName (tyConGenIds tycon),
201 | isForeignTyCon tycon
202 = ForeignType { tcdName = getName tycon,
203 tcdFoType = DNType, -- The only case at present
206 | otherwise = pprPanic "ifaceTyCls" (ppr tycon)
208 tyvars = tyConTyVars tycon
209 (_, syn_ty) = getSynTyConDefn tycon
210 new_or_data | isNewTyCon tycon = NewType
211 | otherwise = DataType
213 ifaceConDecl data_con
214 = ConDecl (getName data_con) (getName (dataConId data_con))
215 (toHsTyVars ex_tyvars)
216 (toHsContext ex_theta)
219 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
220 field_labels = dataConFieldLabels data_con
221 strict_marks = drop (length ex_theta) (dataConStrictMarks data_con)
222 -- The 'drop' is because dataConStrictMarks
223 -- includes the existential dictionaries
224 details | null field_labels
225 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
226 VanillaCon (zipWith BangType strict_marks (map toHsType arg_tys))
229 = RecCon (zipWith mk_field strict_marks field_labels)
231 mk_field strict_mark field_label
232 = ([getName field_label], BangType strict_mark (toHsType (fieldLabelType field_label)))
234 ifaceTyCls (AnId id) = iface_sig
236 iface_sig = IfaceSig { tcdName = getName id,
237 tcdType = toHsType id_type,
238 tcdIdInfo = hs_idinfo,
243 cg_info = idCgInfo id
244 arity_info = cgArity cg_info
245 caf_info = cgCafInfo cg_info
247 hs_idinfo | opt_OmitInterfacePragmas = []
248 | otherwise = arity_hsinfo ++ caf_hsinfo ++
249 strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
251 ------------ Arity --------------
252 arity_hsinfo | arity_info == 0 = []
253 | otherwise = [HsArity arity_info]
255 ------------ Caf Info --------------
256 caf_hsinfo = case caf_info of
257 NoCafRefs -> [HsNoCafRefs]
260 ------------ Strictness --------------
261 strict_hsinfo = case newStrictnessInfo id_info of
263 Just sig -> [HsStrictness sig]
265 ------------ Worker --------------
266 work_info = workerInfo id_info
267 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
268 wrkr_hsinfo = case work_info of
269 HasWorker work_id wrap_arity ->
270 [HsWorker (getName work_id) wrap_arity]
273 ------------ Unfolding --------------
274 -- The unfolding is redundant if there is a worker
275 unfold_info = unfoldingInfo id_info
276 inline_prag = inlinePragInfo id_info
277 rhs = unfoldingTemplate unfold_info
278 unfold_hsinfo | neverUnfold unfold_info
280 | otherwise = [HsUnfold inline_prag (toUfExpr rhs)]
284 ifaceInstance :: DFunId -> RenamedInstDecl
285 ifaceInstance dfun_id
286 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
288 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
289 -- The deNoteType is very important. It removes all type
290 -- synonyms from the instance type in interface files.
291 -- That in turn makes sure that when reading in instance decls
292 -- from interface files that the 'gating' mechanism works properly.
293 -- Otherwise you could have
294 -- type Tibble = T Int
295 -- instance Foo Tibble where ...
296 -- and this instance decl wouldn't get imported into a module
297 -- that mentioned T but not Tibble.
299 ifaceRule (id, BuiltinRule _)
300 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
302 ifaceRule (id, Rule name bndrs args rhs)
303 = IfaceRule name (map toUfBndr bndrs) (getName id)
304 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
307 = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
311 %************************************************************************
313 \subsection{Checking if the new interface is up to date
315 %************************************************************************
318 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
319 -> ModIface -- The new interface decls
320 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
321 -- Just mi => Here is the new interface to write
322 -- with correct version numbers
324 -- NB: the fixities, declarations, rules are all assumed
325 -- to be sorted by increasing order of hsDeclName, so that
326 -- we can compare for equality
328 addVersionInfo Nothing new_iface
329 -- No old interface, so definitely write a new one!
330 = (new_iface, Just (text "No old interface available"))
332 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
333 mi_decls = old_decls,
334 mi_fixities = old_fixities,
335 mi_deprecs = old_deprecs }))
336 new_iface@(ModIface { mi_decls = new_decls,
337 mi_fixities = new_fixities,
338 mi_deprecs = new_deprecs })
340 | no_output_change && no_usage_change
341 = (new_iface, Nothing)
342 -- don't return the old iface because it may not have an
343 -- mi_globals field set to anything reasonable.
345 | otherwise -- Add updated version numbers
346 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
347 (final_iface, Just pp_diffs)
350 final_iface = new_iface { mi_version = new_version }
351 old_mod_vers = vers_module old_version
352 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
353 vers_exports = bumpVersion no_export_change (vers_exports old_version),
354 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
355 vers_decls = tc_vers }
357 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
358 no_usage_change = mi_usages old_iface == mi_usages new_iface
360 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
361 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
362 no_deprec_change = old_deprecs == new_deprecs
364 -- Fill in the version number on the new declarations by looking at the old declarations.
365 -- Set the flag if anything changes.
366 -- Assumes that the decls are sorted by hsDeclName.
367 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
368 (dcl_tycl old_decls) (dcl_tycl new_decls)
369 pp_diffs = vcat [pp_tc_diffs,
370 pp_change no_export_change "Export list",
371 pp_change no_rule_change "Rules",
372 pp_change no_deprec_change "Deprecations",
373 pp_change no_usage_change "Usages"]
374 pp_change True what = empty
375 pp_change False what = text what <+> ptext SLIT("changed")
377 diffDecls :: VersionInfo -- Old version
378 -> NameEnv Fixity -> NameEnv Fixity -- Old and new fixities
379 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
380 -> (Bool, -- True <=> no change
381 SDoc, -- Record of differences
382 NameEnv Version) -- New version map
384 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
385 old_fixities new_fixities old new
386 = diff True empty emptyNameEnv old new
388 -- When seeing if two decls are the same,
389 -- remember to check whether any relevant fixity has changed
390 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
391 same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
393 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
394 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
395 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
397 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
398 -- When adding a new item, start from the old module version
399 -- This way, if you have version 4 of f, then delete f, then add f again,
400 -- you'll get version 6 of f, which will (correctly) force recompilation of
403 diff ok_so_far pp new_vers (od:ods) (nd:nds)
404 = case od_name `compare` nd_name of
405 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
406 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
407 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
408 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
410 od_name = tyClDeclName od
411 nd_name = tyClDeclName nd
412 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
413 old_version = lookupVersion old_decls_vers od_name
415 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
416 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
417 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
418 (ptext SLIT("New:") <+> ppr nd))
423 %************************************************************************
425 \subsection{Writing ModDetails}
427 %************************************************************************
430 pprModDetails :: ModDetails -> SDoc
431 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
432 = vcat [ dump_types dfun_ids type_env
433 , dump_insts dfun_ids
436 dump_types dfun_ids type_env
437 = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
439 ids = [id | AnId id <- nameEnvElts type_env, want_sig id]
440 want_sig id | opt_PprStyle_Debug = True
441 | otherwise = isLocalId id &&
442 isGlobalName (idName id) &&
443 not (id `elem` dfun_ids)
444 -- isLocalId ignores data constructors, records selectors etc
445 -- The isGlobalName ignores local dictionary and method bindings
446 -- that the type checker has invented. User-defined things have
449 dump_insts [] = empty
450 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
453 -- Print type signatures
454 -- Convert to HsType so that we get source-language style printing
455 -- And sort by RdrName
456 = vcat $ map ppr_sig $ sortLt lt_sig $
457 [ (toRdrName id, toHsType (idType id))
460 lt_sig (n1,_) (n2,_) = n1 < n2
461 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
463 dump_rules [] = empty
464 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
465 nest 4 (vcat (map pprIdCoreRule rs)),
470 %************************************************************************
472 \subsection{Writing an interface file}
474 %************************************************************************
477 writeIface :: FilePath -> ModIface -> IO ()
478 writeIface hi_path mod_iface
479 = do { if_hdl <- openFile hi_path WriteMode
480 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
484 -- Print names unqualified if they are from this module
485 from_this_mod n = nameModule n == this_mod
486 this_mod = mi_module mod_iface
488 pprIface :: ModIface -> SDoc
490 = vcat [ ptext SLIT("__interface")
491 <+> doubleQuotes (ptext opt_InPackage)
492 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
494 <+> (if mi_orphan iface then char '!' else empty)
495 <+> int opt_HiVersion
496 <+> ptext SLIT("where")
498 , vcat (map pprExport (mi_exports iface))
499 , vcat (map pprUsage (mi_usages iface))
501 , pprFixities (mi_fixities iface) (dcl_tycl decls)
502 , pprIfaceDecls (vers_decls version_info) decls
503 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
506 version_info = mi_version iface
507 decls = mi_decls iface
508 exp_vers = vers_exports version_info
509 rule_vers = vers_rules version_info
511 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
512 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
515 When printing export lists, we print like this:
517 AvailTC C [C, x, y] C(x,y)
518 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
521 pprExport :: (ModuleName, Avails) -> SDoc
522 pprExport (mod, items)
523 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
525 pp_avail :: AvailInfo -> SDoc
526 pp_avail (Avail name) = pprOcc name
527 pp_avail (AvailTC n []) = empty
528 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
529 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
532 pp_export names = braces (hsep (map pprOcc names))
534 pprOcc :: Name -> SDoc -- Print the occurrence name only
535 pprOcc n = pprOccName (nameOccName n)
540 pprUsage :: ImportVersion Name -> SDoc
541 pprUsage (m, has_orphans, is_boot, whats_imported)
542 = hsep [ptext SLIT("import"), ppr m,
544 pp_versions whats_imported
547 pp_orphan | has_orphans = char '!'
549 pp_boot | is_boot = char '@'
552 -- Importing the whole module is indicated by an empty list
553 pp_versions NothingAtAll = empty
554 pp_versions (Everything v) = dcolon <+> int v
555 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
556 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
558 pp_export_version Nothing = empty
559 pp_export_version (Just v) = int v
563 pprIfaceDecls version_map decls
564 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
565 , vcat (map ppr_decl (dcl_tycl decls))
568 ppr_decl d = ppr_vers d <+> ppr d <> semi
570 -- Print the version for the decl
571 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
577 pprFixities fixity_map decls
578 = hsep [ ppr fix <+> ppr n
580 (n,_) <- tyClDeclNames d,
581 Just fix <- [lookupNameEnv fixity_map n]] <> semi
583 -- Disgusting to print these two together, but that's
584 -- the way the interface parser currently expects them.
585 pprRulesAndDeprecs [] NoDeprecs = empty
586 pprRulesAndDeprecs rules deprecs
587 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
590 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
592 pp_deprecs NoDeprecs = empty
593 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
595 guts = case deprecs of
596 DeprecAll txt -> doubleQuotes (ptext txt)
597 DeprecSome env -> ppr_deprec_env env
599 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
601 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)