[project @ 2000-09-07 16:32:23 by simonpj]
[ghc-hetmet.git] / ghc / compiler / main / MkIface.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[MkIface]{Print an interface for a module}
5
6 \begin{code}
7 module MkIface ( writeIface  ) where
8
9 #include "HsVersions.h"
10
11 import IO               ( Handle, hPutStr, openFile, 
12                           hClose, hPutStrLn, IOMode(..) )
13
14 import HsSyn
15 import HsCore           ( HsIdInfo(..), toUfExpr )
16 import RdrHsSyn         ( RdrNameRuleDecl )
17 import HsPragmas        ( DataPragmas(..), ClassPragmas(..) )
18 import HsTypes          ( toHsTyVars )
19 import BasicTypes       ( Fixity(..), FixityDirection(..), NewOrData(..),
20                           Version, bumpVersion, initialVersion, isLoopBreaker
21                         )
22 import RnMonad
23
24 import TcInstUtil       ( InstInfo(..) )
25
26 import CmdLineOpts
27 import Id               ( Id, idType, idInfo, omitIfaceSigForId, isUserExportedId, hasNoBinding,
28                           idSpecialisation
29                         )
30 import Var              ( isId )
31 import VarSet
32 import DataCon          ( StrictnessMark(..), dataConSig, dataConFieldLabels, dataConStrictMarks )
33 import IdInfo           ( IdInfo, StrictnessInfo(..), ArityInfo(..), InlinePragInfo(..), 
34                           CprInfo(..), CafInfo(..),
35                           inlinePragInfo, arityInfo, arityLowerBound,
36                           strictnessInfo, isBottomingStrictness,
37                           cafInfo, specInfo, cprInfo, 
38                           occInfo, isNeverInlinePrag,
39                           workerExists, workerInfo, WorkerInfo(..)
40                         )
41 import CoreSyn          ( CoreExpr, CoreBind, Bind(..), isBuiltinRule, rulesRules, rulesRhsFreeVars )
42 import CoreFVs          ( exprSomeFreeVars, ruleSomeLhsFreeVars, ruleSomeFreeVars )
43 import CoreUnfold       ( okToUnfoldInHiFile, couldBeSmallEnoughToInline )
44 import Module           ( moduleString, pprModule, pprModuleName, moduleUserString )
45 import Name             ( isLocallyDefined, isWiredInName, toRdrName, nameModule,
46                           Name, NamedThing(..)
47                         )
48 import OccName          ( OccName, pprOccName )
49 import TyCon            ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon,
50                           tyConTheta, tyConTyVars, tyConDataCons, tyConFamilySize
51                         )
52 import Class            ( Class, classExtraBigSig )
53 import FieldLabel       ( fieldLabelName, fieldLabelType )
54 import Type             ( mkSigmaTy, splitSigmaTy, mkDictTy, tidyTopType,
55                           deNoteType, classesToPreds,
56                           Type, ThetaType, PredType(..), ClassContext
57                         )
58
59 import PprType
60 import Rules            ( pprProtoCoreRule, ProtoCoreRule(..) )
61
62 import Bag              ( bagToList, isEmptyBag )
63 import Maybes           ( catMaybes, maybeToBool )
64 import UniqFM           ( lookupUFM, listToUFM )
65 import Util             ( sortLt, mapAccumL )
66 import SrcLoc           ( noSrcLoc )
67 import Bag
68 import Outputable
69
70 import Maybe            ( isNothing )
71 import List             ( partition )
72 import Monad            ( when )
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection{Write a new interface file}
79 %*                                                                      *
80 %************************************************************************
81
82 \begin{code}
83 writeIface this_mod old_iface new_iface
84            local_tycons local_classes inst_info
85            final_ids tidy_binds tidy_orphan_rules
86   = 
87     if isNothing opt_HiDir && isNothing opt_HiFile
88         then return ()  -- not producing any .hi file
89         else 
90
91     let 
92         hi_suf = case opt_HiSuf of { Nothing -> "hi"; Just suf -> suf }
93         filename = case opt_HiFile of {
94                         Just f  -> f;
95                         Nothing -> 
96                    case opt_HiDir of {
97                         Just dir -> dir ++ '/':moduleUserString this_mod 
98                                         ++ '.':hi_suf;
99                         Nothing  -> panic "writeIface"
100                 }}
101     in
102
103     case checkIface old_iface full_new_iface of {
104         Nothing -> when opt_D_dump_rn_trace $
105                         putStrLn "Interface file unchanged" ;  -- No need to update .hi file
106
107         Just final_iface ->
108
109     do  let mod_vers_unchanged = case old_iface of
110                                    Just iface -> pi_vers iface == pi_vers final_iface
111                                    Nothing -> False
112         when (mod_vers_unchanged && opt_D_dump_rn_trace) $
113              putStrLn "Module version unchanged, but usages differ; hence need new hi file"
114
115         if_hdl <- openFile filename WriteMode
116         printForIface if_hdl (pprIface final_iface)
117         hClose if_hdl
118     }   
119   where
120     full_new_iface = completeIface new_iface local_tycons local_classes
121                                              inst_info final_ids tidy_binds
122                                              tidy_orphan_rules
123 \end{code}
124
125
126 %************************************************************************
127 %*                                                                      *
128 \subsection{Checking if the new interface is up to date
129 %*                                                                      *
130 %************************************************************************
131
132 \begin{code}
133 checkIface :: Maybe ParsedIface         -- The old interface, read from M.hi
134            -> ParsedIface               -- The new interface; but with all version numbers = 1
135            -> Maybe ParsedIface         -- Nothing => no change; no need to write new Iface
136                                         -- Just pi => Here is the new interface to write
137                                         --            with correct version numbers
138
139 -- NB: the fixities, declarations, rules are all assumed
140 -- to be sorted by increasing order of hsDeclName, so that 
141 -- we can compare for equality
142
143 checkIface Nothing new_iface
144 -- No old interface, so definitely write a new one!
145   = Just new_iface
146
147 checkIface (Just iface) new_iface
148   | no_output_change && no_usage_change
149   = Nothing
150
151   | otherwise           -- Add updated version numbers
152   = 
153 {-  pprTrace "checkIface" (
154         vcat [ppr no_decl_changed <+> ppr no_export_change <+> ppr no_usage_change,
155               text "--------",
156               vcat (map ppr (pi_decls iface)),
157               text "--------",
158               vcat (map ppr (pi_decls new_iface))
159         ]) $
160 -}
161     Just (new_iface { pi_vers = new_mod_vers,
162                       pi_fixity = (new_fixity_vers, new_fixities),
163                       pi_rules  = (new_rules_vers,  new_rules),
164                       pi_decls  = final_decls
165     })
166         
167   where
168     no_usage_change = pi_usages iface == pi_usages new_iface
169
170     no_output_change = no_decl_changed && 
171                        new_fixity_vers == fixity_vers && 
172                        new_rules_vers == rules_vers &&
173                        no_export_change
174
175     no_export_change = pi_exports iface == pi_exports new_iface
176
177     new_mod_vers | no_output_change = mod_vers
178                  | otherwise        = bumpVersion mod_vers
179
180     mod_vers = pi_vers iface
181
182     (fixity_vers, fixities) = pi_fixity iface
183     (_,       new_fixities) = pi_fixity new_iface
184     new_fixity_vers | fixities == new_fixities = fixity_vers
185                     | otherwise                = bumpVersion fixity_vers
186
187     (rules_vers, rules) = pi_rules iface
188     (_,      new_rules) = pi_rules new_iface
189     new_rules_vers  | rules == new_rules = rules_vers
190                     | otherwise          = bumpVersion rules_vers
191
192     (no_decl_changed, final_decls) = merge_decls True [] (pi_decls iface) (pi_decls new_iface)
193
194         -- Fill in the version number on the new declarations
195         -- by looking at the old declarations.
196         -- Set the flag if anything changes. 
197         -- Assumes that the decls are sorted by hsDeclName
198     merge_decls ok_so_far acc []  []        = (ok_so_far, reverse acc)
199     merge_decls ok_so_far acc old []        = (False, reverse acc)
200     merge_decls ok_so_far acc [] (nvd:nvds) = merge_decls False (nvd:acc) [] nvds
201     merge_decls ok_so_far acc (vd@(v,d):vds) (nvd@(_,nd):nvds)
202         = case d_name `compare` nd_name of
203                 LT -> merge_decls False acc       vds      (nvd:nvds)
204                 GT -> merge_decls False (nvd:acc) (vd:vds) nvds
205                 EQ | d == nd   -> merge_decls ok_so_far (vd:acc) vds nvds
206                    | otherwise -> merge_decls False     ((bumpVersion v, nd):acc) vds nvds
207         where
208           d_name  = hsDeclName d
209           nd_name = hsDeclName nd
210 \end{code}
211
212
213
214 %************************************************************************
215 %*                                                                      *
216 \subsection{Printing the interface}
217 %*                                                                      *
218 %************************************************************************
219
220 \begin{code}
221 pprIface (ParsedIface { pi_mod = mod, pi_vers = mod_vers, pi_orphan = orphan,
222                         pi_usages = usages, pi_exports = exports, 
223                         pi_fixity = (fix_vers, fixities),
224                         pi_insts = insts, pi_decls = decls, 
225                         pi_rules = (rule_vers, rules), pi_deprecs = deprecs })
226  = vcat [ ptext SLIT("__interface")
227                 <+> doubleQuotes (ptext opt_InPackage)
228                 <+> ppr mod <+> ppr mod_vers <+> pp_sub_vers
229                 <+> (if orphan then char '!' else empty)
230                 <+> int opt_HiVersion
231                 <+> ptext SLIT("where")
232         , vcat (map pprExport exports)
233         , vcat (map pprUsage usages)
234         , pprFixities fixities
235         , vcat [ppr i <+> semi | i <- insts]
236         , vcat [ppr_vers v <+> ppr d <> semi | (v,d) <- decls]
237         , pprRules rules
238         , pprDeprecs deprecs
239         ]
240   where
241     ppr_vers v | v == initialVersion = empty
242                | otherwise           = int v
243     pp_sub_vers 
244         | fix_vers == initialVersion && rule_vers == initialVersion = empty
245         | otherwise = brackets (ppr fix_vers <+> ppr rule_vers)
246 \end{code}
247
248 When printing export lists, we print like this:
249         Avail   f               f
250         AvailTC C [C, x, y]     C(x,y)
251         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
252
253 \begin{code}
254 pprExport :: ExportItem -> SDoc
255 pprExport (mod, items)
256  = hsep [ ptext SLIT("__export "), ppr mod, hsep (map upp_avail items) ] <> semi
257   where
258     upp_avail :: RdrAvailInfo -> SDoc
259     upp_avail (Avail name)      = pprOccName name
260     upp_avail (AvailTC name []) = empty
261     upp_avail (AvailTC name ns) = hcat [pprOccName name, bang, upp_export ns']
262                                 where
263                                   bang | name `elem` ns = empty
264                                        | otherwise      = char '|'
265                                   ns' = filter (/= name) ns
266     
267     upp_export []    = empty
268     upp_export names = braces (hsep (map pprOccName names))
269 \end{code}
270
271
272 \begin{code}
273 pprUsage :: ImportVersion OccName -> SDoc
274 pprUsage (m, has_orphans, is_boot, whats_imported)
275   = hsep [ptext SLIT("import"), pprModuleName m, 
276           pp_orphan, pp_boot,
277           upp_import_versions whats_imported
278     ] <> semi
279   where
280     pp_orphan | has_orphans = char '!'
281               | otherwise   = empty
282     pp_boot   | is_boot     = char '@'
283               | otherwise   = empty
284
285         -- Importing the whole module is indicated by an empty list
286     upp_import_versions NothingAtAll   = empty
287     upp_import_versions (Everything v) = dcolon <+> int v
288     upp_import_versions (Specifically vm vf vr nvs)
289       = dcolon <+> int vm <+> int vf <+> int vr <+> hsep [ ppr n <+> int v | (n,v) <- nvs ]
290 \end{code}
291
292
293 \begin{code}
294 pprFixities []    = empty
295 pprFixities fixes = hsep (map ppr fixes) <> semi
296
297 pprRules []    = empty
298 pprRules rules = hsep [ptext SLIT("{-## __R"), hsep (map ppr rules), ptext SLIT("##-}")]
299
300 pprDeprecs []   = empty
301 pprDeprecs deps = hsep [ ptext SLIT("{-## __D"), guts, ptext SLIT("##-}")]
302                 where
303                   guts = hsep [ ppr ie <+> doubleQuotes (ppr txt) <> semi 
304                               | Deprecation ie txt _ <- deps ]
305 \end{code}
306
307
308 %************************************************************************
309 %*                                                                      *
310 \subsection{Completing the new interface}
311 %*                                                                      *
312 %************************************************************************
313
314 \begin{code}
315 completeIface new_iface local_tycons local_classes
316                         inst_info final_ids tidy_binds
317                         tidy_orphan_rules
318   = new_iface { pi_decls = [(initialVersion,d) | d <- sortLt lt_decl all_decls],
319                 pi_insts = sortLt lt_inst_decl inst_dcls,
320                 pi_rules = (initialVersion, rule_dcls)
321     }
322   where
323      all_decls = cls_dcls ++ ty_dcls ++ bagToList val_dcls
324      (inst_dcls, inst_ids) = ifaceInstances inst_info
325      cls_dcls = map ifaceClass local_classes
326   
327      ty_dcls  = map ifaceTyCon (filter (not . isWiredInName . getName) local_tycons)
328
329      (val_dcls, emitted_ids) = ifaceBinds (inst_ids `unionVarSet` orphan_rule_ids)
330                                           final_ids tidy_binds
331
332      rule_dcls | opt_OmitInterfacePragmas = []
333                | otherwise                = ifaceRules tidy_orphan_rules emitted_ids
334
335      orphan_rule_ids = unionVarSets [ ruleSomeFreeVars interestingId rule 
336                                     | ProtoCoreRule _ _ rule <- tidy_orphan_rules]
337
338 lt_decl      d1 d2 = hsDeclName   d1 < hsDeclName d2
339 lt_inst_decl d1 d2 = instDeclName d1 < instDeclName d2
340         -- Even instance decls have names, namely the dfun name
341 \end{code}
342
343
344 %************************************************************************
345 %*                                                                      *
346 \subsection{Completion stuff}
347 %*                                                                      *
348 %************************************************************************
349
350 \begin{code}
351 ifaceRules :: [ProtoCoreRule] -> IdSet -> [RdrNameRuleDecl]
352 ifaceRules rules emitted
353   = orphan_rules ++ local_rules
354   where
355     orphan_rules = [ toHsRule fn rule | ProtoCoreRule _ fn rule <- rules ]
356     local_rules  = [ toHsRule fn rule
357                    | fn <- varSetElems emitted, 
358                      rule <- rulesRules (idSpecialisation fn),
359                      not (isBuiltinRule rule),
360                                 -- We can't print builtin rules in interface files
361                                 -- Since they are built in, an importing module
362                                 -- will have access to them anyway
363
364                         -- Sept 00: I've disabled this test.  It doesn't stop many, if any, rules
365                         -- from coming out, and to make it work properly we need to add 
366                              all (`elemVarSet` emitted) (varSetElems (ruleSomeLhsFreeVars interestingId rule))
367                                 -- Spit out a rule only if all its lhs free vars are emitted
368                                 -- This is a good reason not to do it when we emit the Id itself
369                    ]
370 \end{code}
371
372 \begin{code}                     
373 ifaceInstances :: Bag InstInfo -> ([RdrNameInstDecl], IdSet)
374                    -- The IdSet is the needed dfuns
375
376 ifaceInstances inst_infos
377   = (decls, needed_ids)
378   where                 
379     decls       = map to_decl togo_insts
380     togo_insts  = filter is_togo_inst (bagToList inst_infos)
381     needed_ids  = mkVarSet [dfun_id | InstInfo _ _ _ _ dfun_id _ _ _ <- togo_insts]
382     is_togo_inst (InstInfo _ _ _ _ dfun_id _ _ _) = isLocallyDefined dfun_id
383                                  
384     -------                      
385     to_decl (InstInfo clas tvs tys theta dfun_id _ _ _)
386       = let                      
387                 -- The deNoteType is very important.   It removes all type
388                 -- synonyms from the instance type in interface files.
389                 -- That in turn makes sure that when reading in instance decls
390                 -- from interface files that the 'gating' mechanism works properly.
391                 -- Otherwise you could have
392                 --      type Tibble = T Int
393                 --      instance Foo Tibble where ...
394                 -- and this instance decl wouldn't get imported into a module
395                 -- that mentioned T but not Tibble.
396             forall_ty     = mkSigmaTy tvs (classesToPreds theta)
397                                       (deNoteType (mkDictTy clas tys))
398             tidy_ty = tidyTopType forall_ty
399         in                       
400         InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (toRdrName dfun_id)) noSrcLoc 
401 \end{code}
402
403 \begin{code}
404 ifaceTyCon :: TyCon -> RdrNameHsDecl
405 ifaceTyCon tycon
406   | isSynTyCon tycon
407   = TyClD (TySynonym (toRdrName tycon)
408                      (toHsTyVars tyvars) (toHsType ty)
409                      noSrcLoc)
410   where
411     (tyvars, ty) = getSynTyConDefn tycon
412
413 ifaceTyCon tycon
414   | isAlgTyCon tycon
415   = TyClD (TyData new_or_data (toHsContext (tyConTheta tycon))
416                   (toRdrName tycon)
417                   (toHsTyVars tyvars)
418                   (map ifaceConDecl (tyConDataCons tycon))
419                   (tyConFamilySize tycon)
420                   Nothing NoDataPragmas noSrcLoc)
421   where
422     tyvars = tyConTyVars tycon
423     new_or_data | isNewTyCon tycon = NewType
424                 | otherwise        = DataType
425
426     ifaceConDecl data_con 
427         = ConDecl (toRdrName data_con) (error "ifaceConDecl")
428                   (toHsTyVars ex_tyvars)
429                   (toHsContext ex_theta)
430                   details noSrcLoc
431         where
432           (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
433           field_labels   = dataConFieldLabels data_con
434           strict_marks   = dataConStrictMarks data_con
435           details
436             | null field_labels
437             = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
438               VanillaCon (zipWith mk_bang_ty strict_marks arg_tys)
439
440             | otherwise
441             = RecCon (zipWith mk_field strict_marks field_labels)
442
443     mk_bang_ty NotMarkedStrict     ty = Unbanged (toHsType ty)
444     mk_bang_ty (MarkedUnboxed _ _) ty = Unpacked (toHsType ty)
445     mk_bang_ty MarkedStrict        ty = Banged   (toHsType ty)
446
447     mk_field strict_mark field_label
448         = ([toRdrName field_label], mk_bang_ty strict_mark (fieldLabelType field_label))
449
450 ifaceTyCon tycon
451   = pprPanic "pprIfaceTyDecl" (ppr tycon)
452
453 ifaceClass clas
454   = TyClD (ClassDecl (toHsContext sc_theta)
455                      (toRdrName clas)
456                      (toHsTyVars clas_tyvars)
457                      (toHsFDs clas_fds)
458                      (map toClassOpSig op_stuff)
459                      EmptyMonoBinds NoClassPragmas
460                      bogus bogus bogus [] noSrcLoc
461     )
462   where
463      bogus = error "ifaceClass"
464      (clas_tyvars, clas_fds, sc_theta, _, op_stuff) = classExtraBigSig clas
465
466      toClassOpSig (sel_id, dm_id, explicit_dm)
467         = ASSERT( sel_tyvars == clas_tyvars)
468           ClassOpSig (toRdrName sel_id) (Just (bogus, explicit_dm)) (toHsType op_ty) noSrcLoc
469         where
470           (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
471 \end{code}
472
473
474 %************************************************************************
475 %*                                                                      *
476 \subsection{Value bindings}
477 %*                                                                      *
478 %************************************************************************
479
480 \begin{code}
481 ifaceBinds :: IdSet             -- These Ids are needed already
482            -> [Id]              -- Ids used at code-gen time; they have better pragma info!
483            -> [CoreBind]        -- In dependency order, later depend on earlier
484            -> (Bag RdrNameHsDecl, IdSet)                -- Set of Ids actually spat out
485
486 ifaceBinds needed_ids final_ids binds
487   = go needed_ids (reverse binds) emptyBag emptyVarSet 
488                 -- Reverse so that later things will 
489                 -- provoke earlier ones to be emitted
490   where
491     final_id_map  = listToUFM [(id,id) | id <- final_ids]
492     get_idinfo id = case lookupUFM final_id_map id of
493                         Just id' -> idInfo id'
494                         Nothing  -> pprTrace "ifaceBinds not found:" (ppr id) $
495                                     idInfo id
496
497         -- The 'needed' set contains the Ids that are needed by earlier
498         -- interface file emissions.  If the Id isn't in this set, and isn't
499         -- exported, there's no need to emit anything
500     need_id needed_set id = id `elemVarSet` needed_set || isUserExportedId id 
501
502     go needed [] decls emitted
503         | not (isEmptyVarSet needed) = pprTrace "ifaceBinds: free vars:" 
504                                           (sep (map ppr (varSetElems needed)))
505                                        (decls, emitted)
506         | otherwise                  = (decls, emitted)
507
508     go needed (NonRec id rhs : binds) decls emitted
509         | need_id needed id
510         = if omitIfaceSigForId id then
511             go (needed `delVarSet` id) binds decls (emitted `extendVarSet` id)
512           else
513             go ((needed `unionVarSet` extras) `delVarSet` id)
514                binds
515                (decl `consBag` decls)
516                (emitted `extendVarSet` id)
517         | otherwise
518         = go needed binds decls emitted
519         where
520           (decl, extras) = ifaceId get_idinfo False id rhs
521
522         -- Recursive groups are a bit more of a pain.  We may only need one to
523         -- start with, but it may call out the next one, and so on.  So we
524         -- have to look for a fixed point.  We don't want necessarily them all, 
525         -- because without -O we may only need the first one (if we don't emit
526         -- its unfolding)
527     go needed (Rec pairs : binds) decls emitted
528         = go needed' binds decls' emitted' 
529         where
530           (new_decls, new_emitted, extras) = go_rec needed pairs
531           decls'   = new_decls `unionBags` decls
532           needed'  = (needed `unionVarSet` extras) `minusVarSet` mkVarSet (map fst pairs) 
533           emitted' = emitted `unionVarSet` new_emitted
534
535     go_rec :: IdSet -> [(Id,CoreExpr)] -> (Bag RdrNameHsDecl, IdSet, IdSet)
536     go_rec needed pairs
537         | null decls = (emptyBag, emptyVarSet, emptyVarSet)
538         | otherwise  = (more_decls   `unionBags`   listToBag decls, 
539                         more_emitted `unionVarSet` mkVarSet (map fst needed_prs),
540                         more_extras  `unionVarSet` extras)
541         where
542           (needed_prs,leftover_prs) = partition is_needed pairs
543           (decls, extras_s)         = unzip [ifaceId get_idinfo True id rhs 
544                                             | (id,rhs) <- needed_prs, not (omitIfaceSigForId id)]
545           extras                    = unionVarSets extras_s
546           (more_decls, more_emitted, more_extras) = go_rec extras leftover_prs
547           is_needed (id,_) = need_id needed id
548 \end{code}
549
550
551 \begin{code}
552 ifaceId :: (Id -> IdInfo)       -- This function "knows" the extra info added
553                                 -- by the STG passes.  Sigh
554         -> Bool                 -- True <=> recursive, so don't print unfolding
555         -> Id
556         -> CoreExpr             -- The Id's right hand side
557         -> (RdrNameHsDecl, IdSet)       -- The emitted stuff, plus any *extra* needed Ids
558
559 ifaceId get_idinfo is_rec id rhs
560   = (SigD (IfaceSig (toRdrName id) (toHsType id_type) hs_idinfo noSrcLoc),  new_needed_ids)
561   where
562     id_type     = idType id
563     core_idinfo = idInfo id
564     stg_idinfo  = get_idinfo id
565
566     hs_idinfo | opt_OmitInterfacePragmas = []
567               | otherwise                = arity_hsinfo  ++ caf_hsinfo  ++ cpr_hsinfo ++ 
568                                            strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
569
570     ------------  Arity  --------------
571     arity_info   = arityInfo stg_idinfo
572     stg_arity    = arityLowerBound arity_info
573     arity_hsinfo = case arityInfo stg_idinfo of
574                         a@(ArityExactly n) -> [HsArity a]
575                         other              -> []
576
577     ------------ Caf Info --------------
578     caf_hsinfo = case cafInfo stg_idinfo of
579                    NoCafRefs -> [HsNoCafRefs]
580                    otherwise -> []
581
582     ------------ CPR Info --------------
583     cpr_hsinfo = case cprInfo core_idinfo of
584                    ReturnsCPR -> [HsCprInfo]
585                    NoCPRInfo  -> []
586
587     ------------  Strictness  --------------
588     strict_info   = strictnessInfo core_idinfo
589     bottoming_fn  = isBottomingStrictness strict_info
590     strict_hsinfo = case strict_info of
591                         NoStrictnessInfo -> []
592                         info             -> [HsStrictness info]
593
594
595     ------------  Worker  --------------
596         -- We only treat a function as having a worker if
597         -- the exported arity (which is now the number of visible lambdas)
598         -- is the same as the arity at the moment of the w/w split
599         -- If so, we can safely omit the unfolding inside the wrapper, and
600         -- instead re-generate it from the type/arity/strictness info
601         -- But if the arity has changed, we just take the simple path and
602         -- put the unfolding into the interface file, forgetting the fact
603         -- that it's a wrapper.  
604         --
605         -- How can this happen?  Sometimes we get
606         --      f = coerce t (\x y -> $wf x y)
607         -- at the moment of w/w split; but the eta reducer turns it into
608         --      f = coerce t $wf
609         -- which is perfectly fine except that the exposed arity so far as
610         -- the code generator is concerned (zero) differs from the arity
611         -- when we did the split (2).  
612         --
613         -- All this arises because we use 'arity' to mean "exactly how many
614         -- top level lambdas are there" in interface files; but during the
615         -- compilation of this module it means "how many things can I apply
616         -- this to".
617     work_info           = workerInfo core_idinfo
618     HasWorker work_id _ = work_info
619
620     has_worker = case work_info of
621                   HasWorker work_id wrap_arity 
622                    | wrap_arity == stg_arity -> True
623                    | otherwise               -> pprTrace "ifaceId: arity change:" (ppr id) 
624                                                 False
625                                                           
626                   other                      -> False
627
628     wrkr_hsinfo | has_worker = [HsWorker (toRdrName work_id)]
629                 | otherwise  = []
630
631     ------------  Unfolding  --------------
632     inline_pragma  = inlinePragInfo core_idinfo
633     dont_inline    = isNeverInlinePrag inline_pragma
634
635     unfold_hsinfo | show_unfold = [HsUnfold inline_pragma (toUfExpr rhs)]
636                   | otherwise   = []
637
638     show_unfold = not has_worker         &&     -- Not unnecessary
639                   not bottoming_fn       &&     -- Not necessary
640                   not dont_inline        &&
641                   not loop_breaker       &&
642                   rhs_is_small           &&     -- Small enough
643                   okToUnfoldInHiFile rhs        -- No casms etc
644
645     rhs_is_small = couldBeSmallEnoughToInline opt_UF_HiFileThreshold rhs
646
647     ------------  Specialisations --------------
648     spec_info   = specInfo core_idinfo
649     
650     ------------  Occ info  --------------
651     loop_breaker  = isLoopBreaker (occInfo core_idinfo)
652
653     ------------  Extra free Ids  --------------
654     new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
655                    | otherwise                = worker_ids      `unionVarSet`
656                                                 unfold_ids      `unionVarSet`
657                                                 spec_ids
658
659     worker_ids | has_worker && interestingId work_id = unitVarSet work_id
660                         -- Conceivably, the worker might come from
661                         -- another module
662                | otherwise = emptyVarSet
663
664     spec_ids = filterVarSet interestingId (rulesRhsFreeVars spec_info)
665
666     unfold_ids | show_unfold = find_fvs rhs
667                | otherwise   = emptyVarSet
668
669     find_fvs expr = exprSomeFreeVars interestingId expr
670
671     ------------ Sanity checking --------------
672         -- The arity of a wrapper function should match its strictness,
673         -- or else an importing module will get very confused indeed.
674     arity_matches_strictness 
675        = case work_info of
676              HasWorker _ wrap_arity -> wrap_arity == arityLowerBound arity_info
677              other                  -> True
678     
679 interestingId id = isId id && isLocallyDefined id && not (hasNoBinding id)
680 \end{code}
681