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 ( Fixity(..), NewOrData(..), Activation(..),
21 Version, initialVersion, bumpVersion
23 import NewDemand ( isTopSig )
25 import RnHsSyn ( RenamedInstDecl, RenamedTyClDecl )
26 import HscTypes ( VersionInfo(..), ModIface(..), ModDetails(..),
27 ModuleLocation(..), GhciMode(..),
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 )
51 import TyCon ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon,
52 isAlgTyCon, tyConGenIds, tyConTheta, tyConTyVars,
53 tyConDataCons, tyConFamilySize, isPrimTyCon,
54 isClassTyCon, isForeignTyCon, tyConArity
56 import Class ( classExtraBigSig, classTyCon, DefMeth(..) )
57 import FieldLabel ( fieldLabelType )
58 import TcType ( tcSplitSigmaTy, tidyTopType, deNoteType, namesOfDFunHead )
59 import SrcLoc ( noSrcLoc )
61 import Module ( ModuleName )
62 import Util ( sortLt )
63 import ErrUtils ( dumpIfSet_dyn )
65 import Monad ( when, mplus )
66 import Maybe ( maybeToList )
67 import IO ( IOMode(..), openFile, hClose )
71 %************************************************************************
73 \subsection{Completing an interface}
75 %************************************************************************
81 mkFinalIface :: GhciMode
84 -> Maybe ModIface -- The old interface, if we have it
85 -> ModIface -- The new one, minus the decls and versions
86 -> ModDetails -- The ModDetails for this module
87 -> IO ModIface -- The new one, complete with decls and versions
89 -- a) completes the interface
90 -- b) writes it out to a file if necessary
92 mkFinalIface ghci_mode dflags location
93 maybe_old_iface new_iface new_details
95 -- Add the new declarations, and the is-orphan flag
96 let iface_w_decls = new_iface { mi_decls = new_decls,
97 mi_orphan = orphan_mod }
99 -- Add version information
100 ; let (final_iface, maybe_diffs) = addVersionInfo maybe_old_iface iface_w_decls
102 -- Write the interface file, if necessary
103 ; when (must_write_hi_file maybe_diffs)
104 (writeIface hi_file_path final_iface)
107 ; write_diffs dflags final_iface maybe_diffs
109 ; return final_iface }
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 (md_insts new_details)
123 ty_cls_dcls = foldNameEnv ifaceTyThing_acc [] (md_types new_details)
124 rule_dcls = map ifaceRule (md_rules new_details)
125 orphan_mod = isOrphanModule (mi_module new_iface) 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 = map ifaceConDecl (tyConDataCons tycon),
203 tcdNCons = tyConFamilySize tycon,
205 tcdSysNames = map getName (tyConGenIds tycon),
208 | isForeignTyCon tycon
209 = ForeignType { tcdName = getName tycon,
210 tcdExtName = Nothing,
211 tcdFoType = DNType, -- The only case at present
215 -- needed in GHCi for ':info Int#', for example
216 = TyData { tcdND = DataType,
218 tcdName = getName tycon,
219 tcdTyVars = toHsTyVars (take (tyConArity tycon) alphaTyVars),
226 | otherwise = pprPanic "ifaceTyThing" (ppr tycon)
228 tyvars = tyConTyVars tycon
229 (_, syn_ty) = getSynTyConDefn tycon
230 new_or_data | isNewTyCon tycon = NewType
231 | otherwise = DataType
233 ifaceConDecl data_con
234 = ConDecl (getName data_con) (getName (dataConId data_con))
235 (toHsTyVars ex_tyvars)
236 (toHsContext ex_theta)
239 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
240 field_labels = dataConFieldLabels data_con
241 strict_marks = drop (length ex_theta) (dataConStrictMarks data_con)
242 -- The 'drop' is because dataConStrictMarks
243 -- includes the existential dictionaries
244 details | null field_labels
245 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
246 VanillaCon (zipWith BangType strict_marks (map toHsType arg_tys))
249 = RecCon (zipWith mk_field strict_marks field_labels)
251 mk_field strict_mark field_label
252 = ([getName field_label], BangType strict_mark (toHsType (fieldLabelType field_label)))
254 ifaceTyThing (AnId id) = iface_sig
256 iface_sig = IfaceSig { tcdName = getName id,
257 tcdType = toHsType id_type,
258 tcdIdInfo = hs_idinfo,
263 cg_info = idCgInfo id
264 arity_info = arityInfo id_info
265 caf_info = cgCafInfo cg_info
267 hs_idinfo | opt_OmitInterfacePragmas = []
268 | otherwise = maybeToList $
271 strict_hsinfo `mplus`
275 ------------ Arity --------------
276 arity_hsinfo | arity_info == 0 = Nothing
277 | otherwise = Just (HsArity arity_info)
279 ------------ Caf Info --------------
280 caf_hsinfo = case caf_info of
281 NoCafRefs -> Just HsNoCafRefs
284 ------------ Strictness --------------
285 -- No point in explicitly exporting TopSig
286 strict_hsinfo = case newStrictnessInfo id_info of
287 Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
290 ------------ Worker --------------
291 work_info = workerInfo id_info
292 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
293 wrkr_hsinfo = case work_info of
294 HasWorker work_id wrap_arity ->
295 Just (HsWorker (getName work_id) wrap_arity)
298 ------------ Unfolding --------------
299 -- The unfolding is redundant if there is a worker
300 unfold_info = unfoldingInfo id_info
301 inline_prag = inlinePragInfo id_info
302 rhs = unfoldingTemplate unfold_info
303 unfold_hsinfo | neverUnfold unfold_info
304 || has_worker = Nothing
305 | otherwise = Just (HsUnfold inline_prag (toUfExpr rhs))
309 ifaceInstance :: DFunId -> RenamedInstDecl
310 ifaceInstance dfun_id
311 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
313 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
314 -- The deNoteType is very important. It removes all type
315 -- synonyms from the instance type in interface files.
316 -- That in turn makes sure that when reading in instance decls
317 -- from interface files that the 'gating' mechanism works properly.
318 -- Otherwise you could have
319 -- type Tibble = T Int
320 -- instance Foo Tibble where ...
321 -- and this instance decl wouldn't get imported into a module
322 -- that mentioned T but not Tibble.
324 ifaceRule :: IdCoreRule -> RuleDecl Name pat
325 ifaceRule (id, BuiltinRule _ _)
326 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
328 ifaceRule (id, Rule name act bndrs args rhs)
329 = IfaceRule name act (map toUfBndr bndrs) (getName id)
330 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
332 bogusIfaceRule :: (NamedThing a) => a -> RuleDecl Name pat
334 = IfaceRule SLIT("bogus") NeverActive [] (getName id) [] (UfVar (getName id)) noSrcLoc
338 %************************************************************************
340 \subsection{Checking if the new interface is up to date
342 %************************************************************************
345 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
346 -> ModIface -- The new interface decls
347 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
348 -- Just mi => Here is the new interface to write
349 -- with correct version numbers
351 -- NB: the fixities, declarations, rules are all assumed
352 -- to be sorted by increasing order of hsDeclName, so that
353 -- we can compare for equality
355 addVersionInfo Nothing new_iface
356 -- No old interface, so definitely write a new one!
357 = (new_iface, Just (text "No old interface available"))
359 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
360 mi_decls = old_decls,
361 mi_fixities = old_fixities,
362 mi_deprecs = old_deprecs }))
363 new_iface@(ModIface { mi_decls = new_decls,
364 mi_fixities = new_fixities,
365 mi_deprecs = new_deprecs })
367 | no_output_change && no_usage_change
368 = (new_iface, Nothing)
369 -- don't return the old iface because it may not have an
370 -- mi_globals field set to anything reasonable.
372 | otherwise -- Add updated version numbers
373 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
374 (final_iface, Just pp_diffs)
377 final_iface = new_iface { mi_version = new_version }
378 old_mod_vers = vers_module old_version
379 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
380 vers_exports = bumpVersion no_export_change (vers_exports old_version),
381 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
382 vers_decls = tc_vers }
384 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
385 no_usage_change = mi_usages old_iface == mi_usages new_iface
387 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
388 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
389 no_deprec_change = old_deprecs == new_deprecs
391 -- Fill in the version number on the new declarations by looking at the old declarations.
392 -- Set the flag if anything changes.
393 -- Assumes that the decls are sorted by hsDeclName.
394 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
395 (dcl_tycl old_decls) (dcl_tycl new_decls)
396 pp_diffs = vcat [pp_tc_diffs,
397 pp_change no_export_change "Export list",
398 pp_change no_rule_change "Rules",
399 pp_change no_deprec_change "Deprecations",
400 pp_change no_usage_change "Usages"]
401 pp_change True what = empty
402 pp_change False what = text what <+> ptext SLIT("changed")
404 diffDecls :: VersionInfo -- Old version
405 -> NameEnv Fixity -> NameEnv Fixity -- Old and new fixities
406 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
407 -> (Bool, -- True <=> no change
408 SDoc, -- Record of differences
409 NameEnv Version) -- New version map
411 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
412 old_fixities new_fixities old new
413 = diff True empty emptyNameEnv old new
415 -- When seeing if two decls are the same,
416 -- remember to check whether any relevant fixity has changed
417 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
418 same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
420 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
421 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
422 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
424 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
425 -- When adding a new item, start from the old module version
426 -- This way, if you have version 4 of f, then delete f, then add f again,
427 -- you'll get version 6 of f, which will (correctly) force recompilation of
430 diff ok_so_far pp new_vers (od:ods) (nd:nds)
431 = case od_name `compare` nd_name of
432 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
433 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
434 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
435 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
437 od_name = tyClDeclName od
438 nd_name = tyClDeclName nd
439 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
440 old_version = lookupVersion old_decls_vers od_name
442 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
443 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
444 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
445 (ptext SLIT("New:") <+> ppr nd))
450 %************************************************************************
452 \subsection{Writing ModDetails}
454 %************************************************************************
457 pprModDetails :: ModDetails -> SDoc
458 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
459 = vcat [ dump_types dfun_ids type_env
460 , dump_insts dfun_ids
463 dump_types :: [Var] -> TypeEnv -> SDoc
464 dump_types dfun_ids type_env
465 = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
467 ids = [id | id <- typeEnvIds type_env, want_sig id]
468 want_sig id | opt_PprStyle_Debug = True
469 | otherwise = isLocalId id &&
470 isGlobalName (idName id) &&
471 not (id `elem` dfun_ids)
472 -- isLocalId ignores data constructors, records selectors etc
473 -- The isGlobalName ignores local dictionary and method bindings
474 -- that the type checker has invented. User-defined things have
477 dump_insts :: [Var] -> SDoc
478 dump_insts [] = empty
479 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
481 dump_sigs :: [Var] -> SDoc
483 -- Print type signatures
484 -- Convert to HsType so that we get source-language style printing
485 -- And sort by RdrName
486 = vcat $ map ppr_sig $ sortLt lt_sig $
487 [ (toRdrName id, toHsType (idType id))
490 lt_sig (n1,_) (n2,_) = n1 < n2
491 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
493 dump_rules :: [IdCoreRule] -> SDoc
494 dump_rules [] = empty
495 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
496 nest 4 (vcat (map pprIdCoreRule rs)),
501 %************************************************************************
503 \subsection{Writing an interface file}
505 %************************************************************************
508 writeIface :: FilePath -> ModIface -> IO ()
509 writeIface hi_path mod_iface
510 = do { if_hdl <- openFile hi_path WriteMode
511 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
515 -- Print names unqualified if they are from this module
516 from_this_mod n = nameModule n == this_mod
517 this_mod = mi_module mod_iface
519 pprIface :: ModIface -> SDoc
521 = vcat [ ptext SLIT("__interface")
522 <+> doubleQuotes (ptext opt_InPackage)
523 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
525 <+> (if mi_orphan iface then char '!' else empty)
526 <+> int opt_HiVersion
527 <+> ptext SLIT("where")
529 , vcat (map pprExport (mi_exports iface))
530 , vcat (map pprUsage (mi_usages iface))
532 , pprFixities (mi_fixities iface) (dcl_tycl decls)
533 , pprIfaceDecls (vers_decls version_info) decls
534 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
537 version_info = mi_version iface
538 decls = mi_decls iface
539 exp_vers = vers_exports version_info
540 rule_vers = vers_rules version_info
542 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
543 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
546 When printing export lists, we print like this:
548 AvailTC C [C, x, y] C(x,y)
549 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
552 pprExport :: (ModuleName, Avails) -> SDoc
553 pprExport (mod, items)
554 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
556 pp_avail :: AvailInfo -> SDoc
557 pp_avail (Avail name) = pprOcc name
558 pp_avail (AvailTC _ []) = empty
559 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
560 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
563 pp_export names = braces (hsep (map pprOcc names))
565 pprOcc :: Name -> SDoc -- Print the occurrence name only
566 pprOcc n = pprOccName (nameOccName n)
571 pprUsage :: ImportVersion Name -> SDoc
572 pprUsage (m, has_orphans, is_boot, whats_imported)
573 = hsep [ptext SLIT("import"), ppr m,
575 pp_versions whats_imported
578 pp_orphan | has_orphans = char '!'
580 pp_boot | is_boot = char '@'
583 -- Importing the whole module is indicated by an empty list
584 pp_versions NothingAtAll = empty
585 pp_versions (Everything v) = dcolon <+> int v
586 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
587 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
589 pp_export_version Nothing = empty
590 pp_export_version (Just v) = int v
594 pprIfaceDecls :: NameEnv Int -> IfaceDecls -> SDoc
595 pprIfaceDecls version_map decls
596 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
597 , vcat (map ppr_decl (dcl_tycl decls))
600 ppr_decl d = ppr_vers d <+> ppr d <> semi
602 -- Print the version for the decl
603 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
609 pprFixities :: (Outputable a)
611 -> [TyClDecl Name pat]
613 pprFixities fixity_map decls
614 = hsep [ ppr fix <+> ppr n
616 (n,_) <- tyClDeclNames d,
617 Just fix <- [lookupNameEnv fixity_map n]] <> semi
619 -- Disgusting to print these two together, but that's
620 -- the way the interface parser currently expects them.
621 pprRulesAndDeprecs :: (Outputable a) => [a] -> Deprecations -> SDoc
622 pprRulesAndDeprecs [] NoDeprecs = empty
623 pprRulesAndDeprecs rules deprecs
624 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
627 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
629 pp_deprecs NoDeprecs = empty
630 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
632 guts = case deprecs of
633 DeprecAll txt -> doubleQuotes (ptext txt)
634 DeprecSome env -> ppr_deprec_env env
636 ppr_deprec_env :: NameEnv (Name, FAST_STRING) -> SDoc
637 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
639 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)