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 TysPrim ( alphaTyVars )
20 import BasicTypes ( NewOrData(..), Activation(..),
21 Version, initialVersion, bumpVersion
23 import NewDemand ( isTopSig )
25 import RnHsSyn ( RenamedInstDecl, RenamedTyClDecl )
26 import HscTypes ( VersionInfo(..), ModIface(..), ModDetails(..),
27 ModuleLocation(..), GhciMode(..), FixityEnv, lookupFixity,
28 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
29 TyThing(..), DFunId, Avails, TypeEnv,
30 WhatsImported(..), GenAvailInfo(..),
31 ImportVersion, AvailInfo, Deprecations(..),
32 lookupVersion, typeEnvIds
36 import Id ( idType, idInfo, isImplicitId, idCgInfo,
39 import DataCon ( dataConId, dataConSig, dataConFieldLabels, dataConStrictMarks )
42 import CoreSyn ( CoreRule(..), IdCoreRule )
43 import CoreFVs ( ruleLhsFreeNames )
44 import CoreUnfold ( neverUnfold, unfoldingTemplate )
45 import PprCore ( pprIdCoreRule )
46 import Name ( getName, nameModule, toRdrName, isGlobalName,
47 nameIsLocalOrFrom, Name, NamedThing(..) )
50 import OccName ( pprOccName )
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, dropList )
59 import ErrUtils ( dumpIfSet_dyn )
62 import Maybe ( catMaybes )
63 import IO ( IOMode(..), openFile, hClose )
67 %************************************************************************
69 \subsection{Completing an interface}
71 %************************************************************************
77 mkFinalIface :: GhciMode
80 -> Maybe ModIface -- The old interface, if we have it
81 -> ModIface -- The new one, minus the decls and versions
82 -> ModDetails -- The ModDetails for this module
83 -> IO ModIface -- The new one, complete with decls and versions
85 -- a) completes the interface
86 -- b) writes it out to a file if necessary
88 mkFinalIface ghci_mode dflags location maybe_old_iface
89 new_iface@ModIface{ mi_module=mod }
90 new_details@ModDetails{ md_insts=insts,
94 -- Add the new declarations, and the is-orphan flag
95 let iface_w_decls = new_iface { mi_decls = new_decls,
96 mi_orphan = orphan_mod }
98 -- Add version information
99 ; let (final_iface, maybe_diffs) = _scc_ "versioninfo" addVersionInfo maybe_old_iface iface_w_decls
101 -- Write the interface file, if necessary
102 ; when (must_write_hi_file maybe_diffs)
103 (writeIface hi_file_path final_iface)
106 ; write_diffs dflags final_iface maybe_diffs
112 must_write_hi_file Nothing = False
113 must_write_hi_file (Just _diffs) = ghci_mode /= Interactive
114 -- We must write a new .hi file if there are some changes
115 -- and we're not in interactive mode
116 -- maybe_diffs = 'Nothing' means that even the usages havn't changed,
117 -- so there's no need to write a new interface file. But even if
118 -- the usages have changed, the module version may not have.
120 hi_file_path = ml_hi_file location
121 new_decls = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
122 inst_dcls = map ifaceInstance insts
123 ty_cls_dcls = foldNameEnv ifaceTyThing_acc [] types
124 rule_dcls = map ifaceRule rules
125 orphan_mod = isOrphanModule mod new_details
127 write_diffs :: DynFlags -> ModIface -> Maybe SDoc -> IO ()
128 write_diffs dflags new_iface Nothing
129 = do when (dopt Opt_D_dump_hi_diffs dflags) (printDump (text "INTERFACE UNCHANGED"))
130 dumpIfSet_dyn dflags Opt_D_dump_hi "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
132 write_diffs dflags new_iface (Just sdoc_diffs)
133 = do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
134 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
138 isOrphanModule :: Module -> ModDetails -> Bool
139 isOrphanModule this_mod (ModDetails {md_insts = insts, md_rules = rules})
140 = any orphan_inst insts || any orphan_rule rules
142 orphan_inst dfun_id = no_locals (namesOfDFunHead (idType dfun_id))
143 orphan_rule rule = no_locals (ruleLhsFreeNames rule)
144 no_locals names = isEmptyNameSet (filterNameSet (nameIsLocalOrFrom this_mod) names)
147 Implicit Ids and class tycons aren't included in interface files, so
148 we miss them out of the accumulating parameter here.
151 ifaceTyThing_acc :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
152 ifaceTyThing_acc (AnId id) so_far | isImplicitId id = so_far
153 ifaceTyThing_acc (ATyCon id) so_far | isClassTyCon id = so_far
154 ifaceTyThing_acc other so_far = ifaceTyThing other : so_far
157 Convert *any* TyThing into a RenamedTyClDecl. Used both for
158 generating interface files and for the ':info' command in GHCi.
161 ifaceTyThing :: TyThing -> RenamedTyClDecl
162 ifaceTyThing (AClass clas) = cls_decl
164 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
165 tcdName = getName clas,
166 tcdTyVars = toHsTyVars clas_tyvars,
167 tcdFDs = toHsFDs clas_fds,
168 tcdSigs = map toClassOpSig op_stuff,
170 tcdSysNames = sys_names,
173 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
174 tycon = classTyCon clas
175 data_con = head (tyConDataCons tycon)
176 sys_names = mkClassDeclSysNames (getName tycon, getName data_con,
177 getName (dataConId data_con), map getName sc_sels)
179 toClassOpSig (sel_id, def_meth)
180 = ASSERT(sel_tyvars == clas_tyvars)
181 ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
183 (sel_tyvars, _, op_ty) = tcSplitSigmaTy (idType sel_id)
184 def_meth' = case def_meth of
185 NoDefMeth -> NoDefMeth
186 GenDefMeth -> GenDefMeth
187 DefMeth id -> DefMeth (getName id)
189 ifaceTyThing (ATyCon tycon) = ty_decl
191 ty_decl | isSynTyCon tycon
192 = TySynonym { tcdName = getName tycon,
193 tcdTyVars = toHsTyVars tyvars,
194 tcdSynRhs = toHsType syn_ty,
198 = TyData { tcdND = new_or_data,
199 tcdCtxt = toHsContext (tyConTheta tycon),
200 tcdName = getName tycon,
201 tcdTyVars = toHsTyVars tyvars,
202 tcdCons = ifaceConDecls (tyConDataConDetails tycon),
204 tcdSysNames = map getName (tyConGenIds tycon),
207 | isForeignTyCon tycon
208 = ForeignType { tcdName = getName tycon,
209 tcdExtName = Nothing,
210 tcdFoType = DNType, -- The only case at present
213 | isPrimTyCon tycon || isFunTyCon tycon
214 -- needed in GHCi for ':info Int#', for example
215 = TyData { tcdND = DataType,
217 tcdName = getName tycon,
218 tcdTyVars = toHsTyVars (take (tyConArity tycon) alphaTyVars),
224 | otherwise = pprPanic "ifaceTyThing" (ppr tycon)
226 tyvars = tyConTyVars tycon
227 (_, syn_ty) = getSynTyConDefn tycon
228 new_or_data | isNewTyCon tycon = NewType
229 | otherwise = DataType
231 ifaceConDecls Unknown = Unknown
232 ifaceConDecls (HasCons n) = HasCons n
233 ifaceConDecls (DataCons cs) = DataCons (map ifaceConDecl cs)
235 ifaceConDecl data_con
236 = ConDecl (getName data_con) (getName (dataConId data_con))
237 (toHsTyVars ex_tyvars)
238 (toHsContext ex_theta)
241 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
242 field_labels = dataConFieldLabels data_con
243 strict_marks = dropList ex_theta (dataConStrictMarks data_con)
244 -- The 'drop' is because dataConStrictMarks
245 -- includes the existential dictionaries
246 details | null field_labels
247 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
248 VanillaCon (zipWith BangType strict_marks (map toHsType arg_tys))
251 = RecCon (zipWith mk_field strict_marks field_labels)
253 mk_field strict_mark field_label
254 = ([getName field_label], BangType strict_mark (toHsType (fieldLabelType field_label)))
256 ifaceTyThing (AnId id) = iface_sig
258 iface_sig = IfaceSig { tcdName = getName id,
259 tcdType = toHsType id_type,
260 tcdIdInfo = hs_idinfo,
265 cg_info = idCgInfo id
266 arity_info = arityInfo id_info
267 caf_info = cgCafInfo cg_info
269 hs_idinfo | opt_OmitInterfacePragmas
272 = catMaybes [arity_hsinfo, caf_hsinfo,
273 strict_hsinfo, wrkr_hsinfo,
276 ------------ Arity --------------
277 arity_hsinfo | arity_info == 0 = Nothing
278 | otherwise = Just (HsArity arity_info)
280 ------------ Caf Info --------------
281 caf_hsinfo = case caf_info of
282 NoCafRefs -> Just HsNoCafRefs
285 ------------ Strictness --------------
286 -- No point in explicitly exporting TopSig
287 strict_hsinfo = case newStrictnessInfo id_info of
288 Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
291 ------------ Worker --------------
292 work_info = workerInfo id_info
293 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
294 wrkr_hsinfo = case work_info of
295 HasWorker work_id wrap_arity ->
296 Just (HsWorker (getName work_id) wrap_arity)
299 ------------ Unfolding --------------
300 -- The unfolding is redundant if there is a worker
301 unfold_info = unfoldingInfo id_info
302 inline_prag = inlinePragInfo id_info
303 rhs = unfoldingTemplate unfold_info
304 unfold_hsinfo | neverUnfold unfold_info
305 || has_worker = Nothing
306 | otherwise = Just (HsUnfold inline_prag (toUfExpr rhs))
310 ifaceInstance :: DFunId -> RenamedInstDecl
311 ifaceInstance dfun_id
312 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
314 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
315 -- The deNoteType is very important. It removes all type
316 -- synonyms from the instance type in interface files.
317 -- That in turn makes sure that when reading in instance decls
318 -- from interface files that the 'gating' mechanism works properly.
319 -- Otherwise you could have
320 -- type Tibble = T Int
321 -- instance Foo Tibble where ...
322 -- and this instance decl wouldn't get imported into a module
323 -- that mentioned T but not Tibble.
325 ifaceRule :: IdCoreRule -> RuleDecl Name pat
326 ifaceRule (id, BuiltinRule _ _)
327 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
329 ifaceRule (id, Rule name act bndrs args rhs)
330 = IfaceRule name act (map toUfBndr bndrs) (getName id)
331 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
333 bogusIfaceRule :: (NamedThing a) => a -> RuleDecl Name pat
335 = IfaceRule SLIT("bogus") NeverActive [] (getName id) [] (UfVar (getName id)) noSrcLoc
339 %************************************************************************
341 \subsection{Checking if the new interface is up to date
343 %************************************************************************
346 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
347 -> ModIface -- The new interface decls
348 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
349 -- Just mi => Here is the new interface to write
350 -- with correct version numbers
352 -- NB: the fixities, declarations, rules are all assumed
353 -- to be sorted by increasing order of hsDeclName, so that
354 -- we can compare for equality
356 addVersionInfo Nothing new_iface
357 -- No old interface, so definitely write a new one!
358 = (new_iface, Just (text "No old interface available"))
360 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
361 mi_decls = old_decls,
362 mi_fixities = old_fixities,
363 mi_deprecs = old_deprecs }))
364 new_iface@(ModIface { mi_decls = new_decls,
365 mi_fixities = new_fixities,
366 mi_deprecs = new_deprecs })
368 | no_output_change && no_usage_change
369 = (new_iface, Nothing)
370 -- don't return the old iface because it may not have an
371 -- mi_globals field set to anything reasonable.
373 | otherwise -- Add updated version numbers
374 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
375 (final_iface, Just pp_diffs)
378 final_iface = new_iface { mi_version = new_version }
379 old_mod_vers = vers_module old_version
380 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
381 vers_exports = bumpVersion no_export_change (vers_exports old_version),
382 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
383 vers_decls = tc_vers }
385 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
386 no_usage_change = mi_usages old_iface == mi_usages new_iface
388 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
389 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
390 no_deprec_change = old_deprecs == new_deprecs
392 -- Fill in the version number on the new declarations by looking at the old declarations.
393 -- Set the flag if anything changes.
394 -- Assumes that the decls are sorted by hsDeclName.
395 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
396 (dcl_tycl old_decls) (dcl_tycl new_decls)
397 pp_diffs = vcat [pp_tc_diffs,
398 pp_change no_export_change "Export list",
399 pp_change no_rule_change "Rules",
400 pp_change no_deprec_change "Deprecations",
401 pp_change no_usage_change "Usages"]
402 pp_change True what = empty
403 pp_change False what = text what <+> ptext SLIT("changed")
405 diffDecls :: VersionInfo -- Old version
406 -> FixityEnv -> FixityEnv -- Old and new fixities
407 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
408 -> (Bool, -- True <=> no change
409 SDoc, -- Record of differences
410 NameEnv Version) -- New version map
412 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
413 old_fixities new_fixities old new
414 = diff True empty emptyNameEnv old new
416 -- When seeing if two decls are the same,
417 -- remember to check whether any relevant fixity has changed
418 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
419 same_fixity n = lookupFixity old_fixities n == lookupFixity new_fixities n
421 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
422 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
423 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
425 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
426 -- When adding a new item, start from the old module version
427 -- This way, if you have version 4 of f, then delete f, then add f again,
428 -- you'll get version 6 of f, which will (correctly) force recompilation of
431 diff ok_so_far pp new_vers (od:ods) (nd:nds)
432 = case od_name `compare` nd_name of
433 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
434 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
435 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
436 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
438 od_name = tyClDeclName od
439 nd_name = tyClDeclName nd
440 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
441 old_version = lookupVersion old_decls_vers od_name
443 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
444 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
445 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
446 (ptext SLIT("New:") <+> ppr nd))
451 %************************************************************************
453 \subsection{Writing ModDetails}
455 %************************************************************************
458 pprModDetails :: ModDetails -> SDoc
459 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
460 = vcat [ dump_types dfun_ids type_env
461 , dump_insts dfun_ids
464 dump_types :: [Var] -> TypeEnv -> SDoc
465 dump_types dfun_ids type_env
466 = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
468 ids = [id | id <- typeEnvIds type_env, want_sig id]
469 want_sig id | opt_PprStyle_Debug = True
470 | otherwise = isLocalId id &&
471 isGlobalName (idName id) &&
472 not (id `elem` dfun_ids)
473 -- isLocalId ignores data constructors, records selectors etc
474 -- The isGlobalName ignores local dictionary and method bindings
475 -- that the type checker has invented. User-defined things have
478 dump_insts :: [Var] -> SDoc
479 dump_insts [] = empty
480 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
482 dump_sigs :: [Var] -> SDoc
484 -- Print type signatures
485 -- Convert to HsType so that we get source-language style printing
486 -- And sort by RdrName
487 = vcat $ map ppr_sig $ sortLt lt_sig $
488 [ (toRdrName id, toHsType (idType id))
491 lt_sig (n1,_) (n2,_) = n1 < n2
492 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
494 dump_rules :: [IdCoreRule] -> SDoc
495 dump_rules [] = empty
496 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
497 nest 4 (vcat (map pprIdCoreRule rs)),
502 %************************************************************************
504 \subsection{Writing an interface file}
506 %************************************************************************
509 writeIface :: FilePath -> ModIface -> IO ()
510 writeIface hi_path mod_iface
511 = do { if_hdl <- openFile hi_path WriteMode
512 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
516 -- Print names unqualified if they are from this module
517 from_this_mod n = nameModule n == this_mod
518 this_mod = mi_module mod_iface
520 pprIface :: ModIface -> SDoc
522 = vcat [ ptext SLIT("__interface")
523 <+> doubleQuotes (ptext (mi_package iface))
524 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
526 <+> (if mi_orphan iface then char '!' else empty)
527 <+> int opt_HiVersion
528 <+> ptext SLIT("where")
530 , vcat (map pprExport (mi_exports iface))
531 , vcat (map pprUsage (mi_usages iface))
533 , pprFixities (mi_fixities iface) (dcl_tycl decls)
534 , pprIfaceDecls (vers_decls version_info) decls
535 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
538 version_info = mi_version iface
539 decls = mi_decls iface
540 exp_vers = vers_exports version_info
541 rule_vers = vers_rules version_info
543 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
544 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
547 When printing export lists, we print like this:
549 AvailTC C [C, x, y] C(x,y)
550 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
553 pprExport :: (ModuleName, Avails) -> SDoc
554 pprExport (mod, items)
555 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
557 pp_avail :: AvailInfo -> SDoc
558 pp_avail (Avail name) = pprOcc name
559 pp_avail (AvailTC _ []) = empty
560 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
561 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
564 pp_export names = braces (hsep (map pprOcc names))
566 pprOcc :: Name -> SDoc -- Print the occurrence name only
567 pprOcc n = pprOccName (nameOccName n)
572 pprUsage :: ImportVersion Name -> SDoc
573 pprUsage (m, has_orphans, is_boot, whats_imported)
574 = hsep [ptext SLIT("import"), ppr m,
576 pp_versions whats_imported
579 pp_orphan | has_orphans = char '!'
581 pp_boot | is_boot = char '@'
584 -- Importing the whole module is indicated by an empty list
585 pp_versions NothingAtAll = empty
586 pp_versions (Everything v) = dcolon <+> int v
587 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
588 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
590 pp_export_version Nothing = empty
591 pp_export_version (Just v) = int v
595 pprIfaceDecls :: NameEnv Int -> IfaceDecls -> SDoc
596 pprIfaceDecls version_map decls
597 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
598 , vcat (map ppr_decl (dcl_tycl decls))
601 ppr_decl d = ppr_vers d <+> ppr d <> semi
603 -- Print the version for the decl
604 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
610 pprFixities :: (Outputable a)
612 -> [TyClDecl Name pat]
614 pprFixities fixity_map decls
615 = hsep [ ppr fix <+> ppr n
617 (n,_) <- tyClDeclNames d,
618 Just fix <- [lookupNameEnv fixity_map n]] <> semi
620 -- Disgusting to print these two together, but that's
621 -- the way the interface parser currently expects them.
622 pprRulesAndDeprecs :: (Outputable a) => [a] -> Deprecations -> SDoc
623 pprRulesAndDeprecs [] NoDeprecs = empty
624 pprRulesAndDeprecs rules deprecs
625 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
628 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
630 pp_deprecs NoDeprecs = empty
631 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
633 guts = case deprecs of
634 DeprecAll txt -> doubleQuotes (ptext txt)
635 DeprecSome env -> ppr_deprec_env env
637 ppr_deprec_env :: NameEnv (Name, FAST_STRING) -> SDoc
638 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
640 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)