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 [] (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)
141 ifaceTyCls :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
142 ifaceTyCls (AClass clas) so_far
145 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
146 tcdName = getName clas,
147 tcdTyVars = toHsTyVars clas_tyvars,
148 tcdFDs = toHsFDs clas_fds,
149 tcdSigs = map toClassOpSig op_stuff,
151 tcdSysNames = sys_names,
154 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
155 tycon = classTyCon clas
156 data_con = head (tyConDataCons tycon)
157 sys_names = mkClassDeclSysNames (getName tycon, getName data_con,
158 getName (dataConId data_con), map getName sc_sels)
160 toClassOpSig (sel_id, def_meth)
161 = ASSERT(sel_tyvars == clas_tyvars)
162 ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
164 (sel_tyvars, _, op_ty) = tcSplitSigmaTy (idType sel_id)
165 def_meth' = case def_meth of
166 NoDefMeth -> NoDefMeth
167 GenDefMeth -> GenDefMeth
168 DefMeth id -> DefMeth (getName id)
170 ifaceTyCls (ATyCon tycon) so_far
171 | isClassTyCon tycon = so_far
172 | otherwise = ty_decl : so_far
174 ty_decl | isSynTyCon tycon
175 = TySynonym { tcdName = getName tycon,
176 tcdTyVars = toHsTyVars tyvars,
177 tcdSynRhs = toHsType syn_ty,
181 = TyData { tcdND = new_or_data,
182 tcdCtxt = toHsContext (tyConTheta tycon),
183 tcdName = getName tycon,
184 tcdTyVars = toHsTyVars tyvars,
185 tcdCons = map ifaceConDecl (tyConDataCons tycon),
186 tcdNCons = tyConFamilySize tycon,
188 tcdSysNames = map getName (tyConGenIds tycon),
191 | isForeignTyCon tycon
192 = ForeignType { tcdName = getName tycon,
193 tcdFoType = DNType, -- The only case at present
196 | otherwise = pprPanic "ifaceTyCls" (ppr tycon)
198 tyvars = tyConTyVars tycon
199 (_, syn_ty) = getSynTyConDefn tycon
200 new_or_data | isNewTyCon tycon = NewType
201 | otherwise = DataType
203 ifaceConDecl data_con
204 = ConDecl (getName data_con) (getName (dataConId data_con))
205 (toHsTyVars ex_tyvars)
206 (toHsContext ex_theta)
209 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
210 field_labels = dataConFieldLabels data_con
211 strict_marks = drop (length ex_theta) (dataConStrictMarks data_con)
212 -- The 'drop' is because dataConStrictMarks
213 -- includes the existential dictionaries
214 details | null field_labels
215 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
216 VanillaCon (zipWith BangType strict_marks (map toHsType arg_tys))
219 = RecCon (zipWith mk_field strict_marks field_labels)
221 mk_field strict_mark field_label
222 = ([getName field_label], BangType strict_mark (toHsType (fieldLabelType field_label)))
224 ifaceTyCls (AnId id) so_far
225 | isImplicitId id = so_far
226 | otherwise = iface_sig : so_far
228 iface_sig = IfaceSig { tcdName = getName id,
229 tcdType = toHsType id_type,
230 tcdIdInfo = hs_idinfo,
235 cg_info = idCgInfo id
236 arity_info = cgArity cg_info
237 caf_info = cgCafInfo cg_info
239 hs_idinfo | opt_OmitInterfacePragmas = []
240 | otherwise = arity_hsinfo ++ caf_hsinfo ++
241 strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
243 ------------ Arity --------------
244 arity_hsinfo | arity_info == 0 = []
245 | otherwise = [HsArity arity_info]
247 ------------ Caf Info --------------
248 caf_hsinfo = case caf_info of
249 NoCafRefs -> [HsNoCafRefs]
252 ------------ Strictness --------------
253 strict_hsinfo = case newStrictnessInfo id_info of
255 Just sig -> [HsStrictness sig]
257 ------------ Worker --------------
258 work_info = workerInfo id_info
259 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
260 wrkr_hsinfo = case work_info of
261 HasWorker work_id wrap_arity ->
262 [HsWorker (getName work_id) wrap_arity]
265 ------------ Unfolding --------------
266 -- The unfolding is redundant if there is a worker
267 unfold_info = unfoldingInfo id_info
268 inline_prag = inlinePragInfo id_info
269 rhs = unfoldingTemplate unfold_info
270 unfold_hsinfo | neverUnfold unfold_info
272 | otherwise = [HsUnfold inline_prag (toUfExpr rhs)]
276 ifaceInstance :: DFunId -> RenamedInstDecl
277 ifaceInstance dfun_id
278 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
280 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
281 -- The deNoteType is very important. It removes all type
282 -- synonyms from the instance type in interface files.
283 -- That in turn makes sure that when reading in instance decls
284 -- from interface files that the 'gating' mechanism works properly.
285 -- Otherwise you could have
286 -- type Tibble = T Int
287 -- instance Foo Tibble where ...
288 -- and this instance decl wouldn't get imported into a module
289 -- that mentioned T but not Tibble.
291 ifaceRule (id, BuiltinRule _)
292 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
294 ifaceRule (id, Rule name bndrs args rhs)
295 = IfaceRule name (map toUfBndr bndrs) (getName id)
296 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
299 = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
303 %************************************************************************
305 \subsection{Checking if the new interface is up to date
307 %************************************************************************
310 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
311 -> ModIface -- The new interface decls
312 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
313 -- Just mi => Here is the new interface to write
314 -- with correct version numbers
316 -- NB: the fixities, declarations, rules are all assumed
317 -- to be sorted by increasing order of hsDeclName, so that
318 -- we can compare for equality
320 addVersionInfo Nothing new_iface
321 -- No old interface, so definitely write a new one!
322 = (new_iface, Just (text "No old interface available"))
324 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
325 mi_decls = old_decls,
326 mi_fixities = old_fixities,
327 mi_deprecs = old_deprecs }))
328 new_iface@(ModIface { mi_decls = new_decls,
329 mi_fixities = new_fixities,
330 mi_deprecs = new_deprecs })
332 | no_output_change && no_usage_change
333 = (new_iface, Nothing)
334 -- don't return the old iface because it may not have an
335 -- mi_globals field set to anything reasonable.
337 | otherwise -- Add updated version numbers
338 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
339 (final_iface, Just pp_diffs)
342 final_iface = new_iface { mi_version = new_version }
343 old_mod_vers = vers_module old_version
344 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
345 vers_exports = bumpVersion no_export_change (vers_exports old_version),
346 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
347 vers_decls = tc_vers }
349 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
350 no_usage_change = mi_usages old_iface == mi_usages new_iface
352 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
353 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
354 no_deprec_change = old_deprecs == new_deprecs
356 -- Fill in the version number on the new declarations by looking at the old declarations.
357 -- Set the flag if anything changes.
358 -- Assumes that the decls are sorted by hsDeclName.
359 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
360 (dcl_tycl old_decls) (dcl_tycl new_decls)
361 pp_diffs = vcat [pp_tc_diffs,
362 pp_change no_export_change "Export list",
363 pp_change no_rule_change "Rules",
364 pp_change no_deprec_change "Deprecations",
365 pp_change no_usage_change "Usages"]
366 pp_change True what = empty
367 pp_change False what = text what <+> ptext SLIT("changed")
369 diffDecls :: VersionInfo -- Old version
370 -> NameEnv Fixity -> NameEnv Fixity -- Old and new fixities
371 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
372 -> (Bool, -- True <=> no change
373 SDoc, -- Record of differences
374 NameEnv Version) -- New version map
376 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
377 old_fixities new_fixities old new
378 = diff True empty emptyNameEnv old new
380 -- When seeing if two decls are the same,
381 -- remember to check whether any relevant fixity has changed
382 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
383 same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
385 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
386 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
387 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
389 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
390 -- When adding a new item, start from the old module version
391 -- This way, if you have version 4 of f, then delete f, then add f again,
392 -- you'll get version 6 of f, which will (correctly) force recompilation of
395 diff ok_so_far pp new_vers (od:ods) (nd:nds)
396 = case od_name `compare` nd_name of
397 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
398 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
399 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
400 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
402 od_name = tyClDeclName od
403 nd_name = tyClDeclName nd
404 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
405 old_version = lookupVersion old_decls_vers od_name
407 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
408 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
409 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
410 (ptext SLIT("New:") <+> ppr nd))
415 %************************************************************************
417 \subsection{Writing ModDetails}
419 %************************************************************************
422 pprModDetails :: ModDetails -> SDoc
423 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
424 = vcat [ dump_types dfun_ids type_env
425 , dump_insts dfun_ids
428 dump_types dfun_ids type_env
429 = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
431 ids = [id | AnId id <- nameEnvElts type_env, want_sig id]
432 want_sig id | opt_PprStyle_Debug = True
433 | otherwise = isLocalId id &&
434 isGlobalName (idName id) &&
435 not (id `elem` dfun_ids)
436 -- isLocalId ignores data constructors, records selectors etc
437 -- The isGlobalName ignores local dictionary and method bindings
438 -- that the type checker has invented. User-defined things have
441 dump_insts [] = empty
442 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
445 -- Print type signatures
446 -- Convert to HsType so that we get source-language style printing
447 -- And sort by RdrName
448 = vcat $ map ppr_sig $ sortLt lt_sig $
449 [ (toRdrName id, toHsType (idType id))
452 lt_sig (n1,_) (n2,_) = n1 < n2
453 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
455 dump_rules [] = empty
456 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
457 nest 4 (vcat (map pprIdCoreRule rs)),
462 %************************************************************************
464 \subsection{Writing an interface file}
466 %************************************************************************
469 writeIface :: FilePath -> ModIface -> IO ()
470 writeIface hi_path mod_iface
471 = do { if_hdl <- openFile hi_path WriteMode
472 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
476 -- Print names unqualified if they are from this module
477 from_this_mod n = nameModule n == this_mod
478 this_mod = mi_module mod_iface
480 pprIface :: ModIface -> SDoc
482 = vcat [ ptext SLIT("__interface")
483 <+> doubleQuotes (ptext opt_InPackage)
484 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
486 <+> (if mi_orphan iface then char '!' else empty)
487 <+> int opt_HiVersion
488 <+> ptext SLIT("where")
490 , vcat (map pprExport (mi_exports iface))
491 , vcat (map pprUsage (mi_usages iface))
493 , pprFixities (mi_fixities iface) (dcl_tycl decls)
494 , pprIfaceDecls (vers_decls version_info) decls
495 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
498 version_info = mi_version iface
499 decls = mi_decls iface
500 exp_vers = vers_exports version_info
501 rule_vers = vers_rules version_info
503 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
504 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
507 When printing export lists, we print like this:
509 AvailTC C [C, x, y] C(x,y)
510 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
513 pprExport :: (ModuleName, Avails) -> SDoc
514 pprExport (mod, items)
515 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
517 pp_avail :: AvailInfo -> SDoc
518 pp_avail (Avail name) = pprOcc name
519 pp_avail (AvailTC n []) = empty
520 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
521 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
524 pp_export names = braces (hsep (map pprOcc names))
526 pprOcc :: Name -> SDoc -- Print the occurrence name only
527 pprOcc n = pprOccName (nameOccName n)
532 pprUsage :: ImportVersion Name -> SDoc
533 pprUsage (m, has_orphans, is_boot, whats_imported)
534 = hsep [ptext SLIT("import"), ppr m,
536 pp_versions whats_imported
539 pp_orphan | has_orphans = char '!'
541 pp_boot | is_boot = char '@'
544 -- Importing the whole module is indicated by an empty list
545 pp_versions NothingAtAll = empty
546 pp_versions (Everything v) = dcolon <+> int v
547 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
548 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
550 pp_export_version Nothing = empty
551 pp_export_version (Just v) = int v
555 pprIfaceDecls version_map decls
556 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
557 , vcat (map ppr_decl (dcl_tycl decls))
560 ppr_decl d = ppr_vers d <+> ppr d <> semi
562 -- Print the version for the decl
563 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
569 pprFixities fixity_map decls
570 = hsep [ ppr fix <+> ppr n
572 (n,_) <- tyClDeclNames d,
573 Just fix <- [lookupNameEnv fixity_map n]] <> semi
575 -- Disgusting to print these two together, but that's
576 -- the way the interface parser currently expects them.
577 pprRulesAndDeprecs [] NoDeprecs = empty
578 pprRulesAndDeprecs rules deprecs
579 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
582 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
584 pp_deprecs NoDeprecs = empty
585 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
587 guts = case deprecs of
588 DeprecAll txt -> doubleQuotes (ptext txt)
589 DeprecSome env -> ppr_deprec_env env
591 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
593 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)