root/compiler/iface/IfaceSyn.lhs

Revision ac230c5ef652e27f61d954281ae6a3195e1f9970, 37.9 KB (checked in by Simon Peyton Jones <simonpj@…>, 4 weeks ago)

Allow cases with empty alterantives

This patch allows, for the first time, case expressions with an empty
list of alternatives. Max suggested the idea, and Trac #6067 showed
that it is really quite important.

So I've implemented the idea, fixing #6067. Main changes

  • See Note [Empty case alternatives] in CoreSyn?
  • Various foldr1's become foldrs
  • IfaceCase? does not record the type of the alternatives. I added IfaceECase for empty-alternative cases.
  • Core Lint does not complain about empty cases
  • MkCore?.castBottomExpr constructs an empty-alternative case expression (case e of ty {})
  • Property mode set to 100644
Line 
1%
2% (c) The University of Glasgow 2006
3% (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4%
5
6\begin{code}
7{-# OPTIONS -fno-warn-tabs #-}
8-- The above warning supression flag is a temporary kludge.
9-- While working on this module you are encouraged to remove it and
10-- detab the module (please do the detabbing in a separate patch). See
11--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
12-- for details
13
14module IfaceSyn (
15        module IfaceType,
16
17        IfaceDecl(..), IfaceClassOp(..), IfaceAT(..), IfaceATDefault(..),
18        IfaceConDecl(..), IfaceConDecls(..),
19        IfaceExpr(..), IfaceAlt, IfaceLetBndr(..),
20        IfaceBinding(..), IfaceConAlt(..),
21        IfaceIdInfo(..), IfaceIdDetails(..), IfaceUnfolding(..),
22        IfaceInfoItem(..), IfaceRule(..), IfaceAnnotation(..), IfaceAnnTarget,
23        IfaceClsInst(..), IfaceFamInst(..), IfaceTickish(..),
24
25        -- Misc
26        ifaceDeclImplicitBndrs, visibleIfConDecls,
27
28        -- Free Names
29        freeNamesIfDecl, freeNamesIfRule, freeNamesIfFamInst,
30
31        -- Pretty printing
32        pprIfaceExpr, pprIfaceDeclHead
33    ) where
34
35#include "HsVersions.h"
36
37import IfaceType
38import Demand
39import Annotations
40import Class
41import NameSet
42import Name
43import CostCentre
44import Literal
45import ForeignCall
46import Serialized
47import BasicTypes
48import Outputable
49import FastString
50import Module
51import TysWiredIn ( eqTyConName )
52
53infixl 3 &&&
54\end{code}
55
56
57%************************************************************************
58%*                                                                      *
59    Data type declarations
60%*                                                                      *
61%************************************************************************
62
63\begin{code}
64data IfaceDecl
65  = IfaceId { ifName      :: OccName,
66              ifType      :: IfaceType,
67              ifIdDetails :: IfaceIdDetails,
68              ifIdInfo    :: IfaceIdInfo }
69
70  | IfaceData { ifName       :: OccName,        -- Type constructor
71                ifCType      :: Maybe CType,    -- C type for CAPI FFI
72                ifTyVars     :: [IfaceTvBndr],  -- Type variables
73                ifCtxt       :: IfaceContext,   -- The "stupid theta"
74                ifCons       :: IfaceConDecls,  -- Includes new/data/data family info
75                ifRec        :: RecFlag,        -- Recursive or not?
76                ifGadtSyntax :: Bool,           -- True <=> declared using
77                                                -- GADT syntax
78                ifAxiom      :: Maybe IfExtName -- The axiom, for a newtype,
79                                                -- or data/newtype family instance
80    }
81
82  | IfaceSyn  { ifName    :: OccName,           -- Type constructor
83                ifTyVars  :: [IfaceTvBndr],     -- Type variables
84                ifSynKind :: IfaceKind,         -- Kind of the *rhs* (not of the tycon)
85                ifSynRhs  :: Maybe IfaceType    -- Just rhs for an ordinary synonyn
86                                                -- Nothing for an type family declaration
87    }
88
89  | IfaceClass { ifCtxt    :: IfaceContext,     -- Context...
90                 ifName    :: OccName,          -- Name of the class TyCon
91                 ifTyVars  :: [IfaceTvBndr],    -- Type variables
92                 ifFDs     :: [FunDep FastString], -- Functional dependencies
93                 ifATs     :: [IfaceAT],      -- Associated type families
94                 ifSigs    :: [IfaceClassOp],   -- Method signatures
95                 ifRec     :: RecFlag           -- Is newtype/datatype associated
96                                                --   with the class recursive?
97    }
98
99  | IfaceAxiom { ifName   :: OccName       -- Axiom name
100               , ifTyVars :: [IfaceTvBndr] -- Axiom tyvars
101               , ifLHS    :: IfaceType     -- Axiom LHS
102               , ifRHS    :: IfaceType }   -- and RHS
103
104  | IfaceForeign { ifName :: OccName,           -- Needs expanding when we move
105                                                -- beyond .NET
106                   ifExtName :: Maybe FastString }
107
108data IfaceClassOp = IfaceClassOp OccName DefMethSpec IfaceType
109        -- Nothing    => no default method
110        -- Just False => ordinary polymorphic default method
111        -- Just True  => generic default method
112
113data IfaceAT = IfaceAT IfaceDecl [IfaceATDefault]
114        -- Nothing => no default associated type instance
115        -- Just ds => default associated type instance from these templates
116
117data IfaceATDefault = IfaceATD [IfaceTvBndr] [IfaceType] IfaceType
118        -- Each associated type default template is a triple of:
119        --   1. TyVars of the RHS and family arguments (including the class TVs)
120        --   3. The instantiated family arguments
121        --   2. The RHS of the synonym
122
123data IfaceConDecls
124  = IfAbstractTyCon Bool        -- c.f TyCon.AbstractTyCon
125  | IfDataFamTyCon              -- Data family
126  | IfDataTyCon [IfaceConDecl]  -- Data type decls
127  | IfNewTyCon  IfaceConDecl    -- Newtype decls
128
129visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl]
130visibleIfConDecls (IfAbstractTyCon {}) = []
131visibleIfConDecls IfDataFamTyCon      = []
132visibleIfConDecls (IfDataTyCon cs)     = cs
133visibleIfConDecls (IfNewTyCon c)       = [c]
134
135data IfaceConDecl
136  = IfCon {
137        ifConOcc     :: OccName,                -- Constructor name
138        ifConWrapper :: Bool,                   -- True <=> has a wrapper
139        ifConInfix   :: Bool,                   -- True <=> declared infix
140        ifConUnivTvs :: [IfaceTvBndr],          -- Universal tyvars
141        ifConExTvs   :: [IfaceTvBndr],          -- Existential tyvars
142        ifConEqSpec  :: [(OccName,IfaceType)],  -- Equality contraints
143        ifConCtxt    :: IfaceContext,           -- Non-stupid context
144        ifConArgTys  :: [IfaceType],            -- Arg types
145        ifConFields  :: [OccName],              -- ...ditto... (field labels)
146        ifConStricts :: [HsBang]}               -- Empty (meaning all lazy),
147                                                -- or 1-1 corresp with arg tys
148
149data IfaceClsInst
150  = IfaceClsInst { ifInstCls  :: IfExtName,                -- See comments with
151                   ifInstTys  :: [Maybe IfaceTyCon],       -- the defn of ClsInst
152                   ifDFun     :: IfExtName,                -- The dfun
153                   ifOFlag    :: OverlapFlag,              -- Overlap flag
154                   ifInstOrph :: Maybe OccName }           -- See Note [Orphans]
155        -- There's always a separate IfaceDecl for the DFun, which gives
156        -- its IdInfo with its full type and version number.
157        -- The instance declarations taken together have a version number,
158        -- and we don't want that to wobble gratuitously
159        -- If this instance decl is *used*, we'll record a usage on the dfun;
160        -- and if the head does not change it won't be used if it wasn't before
161
162data IfaceFamInst
163  = IfaceFamInst { ifFamInstFam   :: IfExtName           -- Family name
164                 , ifFamInstTys   :: [Maybe IfaceTyCon]  -- Rough match types
165                 , ifFamInstAxiom :: IfExtName           -- The axiom
166                 , ifFamInstOrph  :: Maybe OccName       -- Just like IfaceClsInst
167                 }
168
169data IfaceRule
170  = IfaceRule {
171        ifRuleName   :: RuleName,
172        ifActivation :: Activation,
173        ifRuleBndrs  :: [IfaceBndr],    -- Tyvars and term vars
174        ifRuleHead   :: IfExtName,      -- Head of lhs
175        ifRuleArgs   :: [IfaceExpr],    -- Args of LHS
176        ifRuleRhs    :: IfaceExpr,
177        ifRuleAuto   :: Bool,
178        ifRuleOrph   :: Maybe OccName   -- Just like IfaceClsInst
179    }
180
181data IfaceAnnotation
182  = IfaceAnnotation {
183        ifAnnotatedTarget :: IfaceAnnTarget,
184        ifAnnotatedValue :: Serialized
185  }
186
187type IfaceAnnTarget = AnnTarget OccName
188
189-- We only serialise the IdDetails of top-level Ids, and even then
190-- we only need a very limited selection.  Notably, none of the
191-- implicit ones are needed here, becuase they are not put it
192-- interface files
193
194data IfaceIdDetails
195  = IfVanillaId
196  | IfRecSelId IfaceTyCon Bool
197  | IfDFunId 
198
199data IfaceIdInfo
200  = NoInfo                      -- When writing interface file without -O
201  | HasInfo [IfaceInfoItem]     -- Has info, and here it is
202
203-- Here's a tricky case:
204--   * Compile with -O module A, and B which imports A.f
205--   * Change function f in A, and recompile without -O
206--   * When we read in old A.hi we read in its IdInfo (as a thunk)
207--      (In earlier GHCs we used to drop IdInfo immediately on reading,
208--       but we do not do that now.  Instead it's discarded when the
209--       ModIface is read into the various decl pools.)
210--   * The version comparsion sees that new (=NoInfo) differs from old (=HasInfo *)
211--      and so gives a new version.
212
213data IfaceInfoItem
214  = HsArity      Arity
215  | HsStrictness StrictSig
216  | HsInline     InlinePragma
217  | HsUnfold     Bool             -- True <=> isStrongLoopBreaker is true
218                 IfaceUnfolding   -- See Note [Expose recursive functions]
219  | HsNoCafRefs
220
221-- NB: Specialisations and rules come in separately and are
222-- only later attached to the Id.  Partial reason: some are orphans.
223
224data IfaceUnfolding
225  = IfCoreUnfold Bool IfaceExpr -- True <=> INLINABLE, False <=> regular unfolding
226                                -- Possibly could eliminate the Bool here, the information
227                                -- is also in the InlinePragma.
228
229  | IfCompulsory IfaceExpr      -- Only used for default methods, in fact
230
231  | IfInlineRule Arity          -- INLINE pragmas
232                 Bool           -- OK to inline even if *un*-saturated
233                 Bool           -- OK to inline even if context is boring
234                 IfaceExpr
235
236  | IfExtWrapper Arity IfExtName  -- NB: sometimes we need a IfExtName (not just IfLclName)
237  | IfLclWrapper Arity IfLclName  --     because the worker can simplify to a function in
238                                  --     another module.
239
240  | IfDFunUnfold [IfaceExpr]
241
242--------------------------------
243data IfaceExpr
244  = IfaceLcl    IfLclName
245  | IfaceExt    IfExtName
246  | IfaceType   IfaceType
247  | IfaceCo     IfaceType               -- We re-use IfaceType for coercions
248  | IfaceTuple  TupleSort [IfaceExpr]   -- Saturated; type arguments omitted
249  | IfaceLam    IfaceBndr IfaceExpr
250  | IfaceApp    IfaceExpr IfaceExpr
251  | IfaceCase   IfaceExpr IfLclName [IfaceAlt]
252  | IfaceECase  IfaceExpr IfaceType     -- See Note [Empty case alternatives]
253  | IfaceLet    IfaceBinding  IfaceExpr
254  | IfaceCast   IfaceExpr IfaceCoercion
255  | IfaceLit    Literal
256  | IfaceFCall  ForeignCall IfaceType
257  | IfaceTick   IfaceTickish IfaceExpr    -- from Tick tickish E
258
259data IfaceTickish
260  = IfaceHpcTick Module Int                -- from HpcTick x
261  | IfaceSCC     CostCentre Bool Bool      -- from ProfNote
262  -- no breakpoints: we never export these into interface files
263
264type IfaceAlt = (IfaceConAlt, [IfLclName], IfaceExpr)
265        -- Note: IfLclName, not IfaceBndr (and same with the case binder)
266        -- We reconstruct the kind/type of the thing from the context
267        -- thus saving bulk in interface files
268
269data IfaceConAlt = IfaceDefault
270                 | IfaceDataAlt IfExtName
271                 | IfaceLitAlt Literal
272
273data IfaceBinding
274  = IfaceNonRec IfaceLetBndr IfaceExpr
275  | IfaceRec    [(IfaceLetBndr, IfaceExpr)]
276
277-- IfaceLetBndr is like IfaceIdBndr, but has IdInfo too
278-- It's used for *non-top-level* let/rec binders
279-- See Note [IdInfo on nested let-bindings]
280data IfaceLetBndr = IfLetBndr IfLclName IfaceType IfaceIdInfo
281\end{code}
282
283Note [Empty case alternatives]
284~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
285In IfaceSyn an IfaceCase does not record the types of the alternatives,
286unlike CorSyn Case.  But we need this type if the alternatives are empty.
287Hence IfaceECase.  See Note [Empty case alternatives] in CoreSyn.
288
289Note [Expose recursive functions]
290~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
291For supercompilation we want to put *all* unfoldings in the interface
292file, even for functions that are recursive (or big).  So we need to
293know when an unfolding belongs to a loop-breaker so that we can refrain
294from inlining it (except during supercompilation).
295
296Note [IdInfo on nested let-bindings]
297~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
298Occasionally we want to preserve IdInfo on nested let bindings. The one
299that came up was a NOINLINE pragma on a let-binding inside an INLINE
300function.  The user (Duncan Coutts) really wanted the NOINLINE control
301to cross the separate compilation boundary.
302
303In general we retain all info that is left by CoreTidy.tidyLetBndr, since
304that is what is seen by importing module with --make
305
306Note [Orphans]: the ifInstOrph and ifRuleOrph fields
307~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
308Class instances, rules, and family instances are divided into orphans
309and non-orphans.  Roughly speaking, an instance/rule is an orphan if
310its left hand side mentions nothing defined in this module.  Orphan-hood
311has two major consequences
312
313 * A non-orphan is not finger-printed separately.  Instead, for
314   fingerprinting purposes it is treated as part of the entity it
315   mentions on the LHS.  For example
316      data T = T1 | T2
317      instance Eq T where ....
318   The instance (Eq T) is incorprated as part of T's fingerprint.
319
320   In constrast, orphans are all fingerprinted together in the
321   mi_orph_hash field of the ModIface.
322 
323   See MkIface.addFingerprints.
324
325 * A module that contains orphans is called an "orphan module".  If
326   the module being compiled depends (transitively) on an oprhan
327   module M, then M.hi is read in regardless of whether M is oherwise
328   needed. This is to ensure that we don't miss any instance decls in
329   M.  But it's painful, because it means we need to keep track of all
330   the orphan modules below us.
331
332Orphan-hood is computed when we generate an IfaceInst, IfaceRule, or
333IfaceFamInst respectively:
334
335 - If an instance is an orphan its ifInstOprh field is Nothing
336   Otherwise ifInstOrph is (Just n) where n is the Name of a
337   local class or tycon that witnesses its non-orphan-hood.
338   This computation is done by MkIface.instanceToIfaceInst
339
340 - Similarly for ifRuleOrph
341   The computation is done by MkIface.coreRuleToIfaceRule
342
343Note [When exactly is an instance decl an orphan?]
344~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
345  (see MkIface.instanceToIfaceInst, which implements this)
346Roughly speaking, an instance is an orphan if its head (after the =>)
347mentions nothing defined in this module. 
348
349Functional dependencies complicate the situation though. Consider
350
351  module M where { class C a b | a -> b }
352
353and suppose we are compiling module X:
354
355  module X where
356        import M
357        data T = ...
358        instance C Int T where ...
359
360This instance is an orphan, because when compiling a third module Y we
361might get a constraint (C Int v), and we'd want to improve v to T.  So
362we must make sure X's instances are loaded, even if we do not directly
363use anything from X.
364
365More precisely, an instance is an orphan iff
366
367  If there are no fundeps, then at least of the names in
368  the instance head is locally defined.
369
370  If there are fundeps, then for every fundep, at least one of the
371  names free in a *non-determined* part of the instance head is
372  defined in this module.
373
374(Note that these conditions hold trivially if the class is locally
375defined.) 
376
377Note [Versioning of instances]
378~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
379See [http://hackage.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance#Instances]
380
381\begin{code}
382-- -----------------------------------------------------------------------------
383-- Utils on IfaceSyn
384
385ifaceDeclImplicitBndrs :: IfaceDecl -> [OccName]
386--  *Excludes* the 'main' name, but *includes* the implicitly-bound names
387-- Deeply revolting, because it has to predict what gets bound,
388-- especially the question of whether there's a wrapper for a datacon
389-- See Note [Implicit TyThings] in HscTypes
390
391-- N.B. the set of names returned here *must* match the set of
392-- TyThings returned by HscTypes.implicitTyThings, in the sense that
393-- TyThing.getOccName should define a bijection between the two lists.
394-- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
395-- The order of the list does not matter.
396ifaceDeclImplicitBndrs IfaceData {ifCons = IfAbstractTyCon {}}  = []
397
398-- Newtype
399ifaceDeclImplicitBndrs (IfaceData {ifName = tc_occ,
400                              ifCons = IfNewTyCon (
401                                        IfCon { ifConOcc = con_occ })})
402  =   -- implicit newtype coercion
403    (mkNewTyCoOcc tc_occ) : -- JPM: newtype coercions shouldn't be implicit
404      -- data constructor and worker (newtypes don't have a wrapper)
405    [con_occ, mkDataConWorkerOcc con_occ]
406
407
408ifaceDeclImplicitBndrs (IfaceData {ifName = _tc_occ,
409                              ifCons = IfDataTyCon cons })
410  = -- for each data constructor in order,
411    --    data constructor, worker, and (possibly) wrapper
412    concatMap dc_occs cons
413  where
414    dc_occs con_decl
415        | has_wrapper = [con_occ, work_occ, wrap_occ]
416        | otherwise   = [con_occ, work_occ]
417        where
418          con_occ  = ifConOcc con_decl            -- DataCon namespace
419          wrap_occ = mkDataConWrapperOcc con_occ  -- Id namespace
420          work_occ = mkDataConWorkerOcc con_occ   -- Id namespace
421          has_wrapper = ifConWrapper con_decl     -- This is the reason for
422                                                  -- having the ifConWrapper field!
423
424ifaceDeclImplicitBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_tc_occ,
425                               ifSigs = sigs, ifATs = ats })
426  = --   (possibly) newtype coercion
427    co_occs ++
428    --    data constructor (DataCon namespace)
429    --    data worker (Id namespace)
430    --    no wrapper (class dictionaries never have a wrapper)
431    [dc_occ, dcww_occ] ++
432    -- associated types
433    [ifName at | IfaceAT at _ <- ats ] ++
434    -- superclass selectors
435    [mkSuperDictSelOcc n cls_tc_occ | n <- [1..n_ctxt]] ++
436    -- operation selectors
437    [op | IfaceClassOp op  _ _ <- sigs]
438  where
439    n_ctxt = length sc_ctxt
440    n_sigs = length sigs
441    co_occs | is_newtype = [mkNewTyCoOcc cls_tc_occ]
442            | otherwise  = []
443    dcww_occ = mkDataConWorkerOcc dc_occ
444    dc_occ = mkClassDataConOcc cls_tc_occ
445    is_newtype = n_sigs + n_ctxt == 1 -- Sigh
446
447ifaceDeclImplicitBndrs _ = []
448
449----------------------------- Printing IfaceDecl ------------------------------
450
451instance Outputable IfaceDecl where
452  ppr = pprIfaceDecl
453
454pprIfaceDecl :: IfaceDecl -> SDoc
455pprIfaceDecl (IfaceId {ifName = var, ifType = ty,
456                       ifIdDetails = details, ifIdInfo = info})
457  = sep [ ppr var <+> dcolon <+> ppr ty,
458          nest 2 (ppr details),
459          nest 2 (ppr info) ]
460
461pprIfaceDecl (IfaceForeign {ifName = tycon})
462  = hsep [ptext (sLit "foreign import type dotnet"), ppr tycon]
463
464pprIfaceDecl (IfaceSyn {ifName = tycon,
465                        ifTyVars = tyvars,
466                        ifSynRhs = Just mono_ty})
467  = hang (ptext (sLit "type") <+> pprIfaceDeclHead [] tycon tyvars)
468       4 (vcat [equals <+> ppr mono_ty])
469
470pprIfaceDecl (IfaceSyn {ifName = tycon, ifTyVars = tyvars,
471                        ifSynRhs = Nothing, ifSynKind = kind })
472  = hang (ptext (sLit "type family") <+> pprIfaceDeclHead [] tycon tyvars)
473       4 (dcolon <+> ppr kind)
474
475pprIfaceDecl (IfaceData {ifName = tycon, ifCType = cType,
476                         ifCtxt = context,
477                         ifTyVars = tyvars, ifCons = condecls,
478                         ifRec = isrec, ifAxiom = mbAxiom})
479  = hang (pp_nd <+> pprIfaceDeclHead context tycon tyvars)
480       4 (vcat [pprCType cType, pprRec isrec, pp_condecls tycon condecls,
481                pprAxiom mbAxiom])
482  where
483    pp_nd = case condecls of
484                IfAbstractTyCon dis -> ptext (sLit "abstract") <> parens (ppr dis)
485                IfDataFamTyCon     -> ptext (sLit "data family")
486                IfDataTyCon _       -> ptext (sLit "data")
487                IfNewTyCon _        -> ptext (sLit "newtype")
488
489pprIfaceDecl (IfaceClass {ifCtxt = context, ifName = clas, ifTyVars = tyvars,
490                          ifFDs = fds, ifATs = ats, ifSigs = sigs,
491                          ifRec = isrec})
492  = hang (ptext (sLit "class") <+> pprIfaceDeclHead context clas tyvars <+> pprFundeps fds)
493       4 (vcat [pprRec isrec,
494                sep (map ppr ats),
495                sep (map ppr sigs)])
496
497pprIfaceDecl (IfaceAxiom {ifName = name, ifTyVars = tyvars,
498                          ifLHS = lhs, ifRHS = rhs})
499  = hang (ptext (sLit "axiom") <+> ppr name <+> ppr tyvars)
500       2 (dcolon <+> ppr lhs <+> text "~#" <+> ppr rhs)
501
502pprCType :: Maybe CType -> SDoc
503pprCType Nothing = ptext (sLit "No C type associated")
504pprCType (Just cType) = ptext (sLit "C type:") <+> ppr cType
505
506pprRec :: RecFlag -> SDoc
507pprRec isrec = ptext (sLit "RecFlag") <+> ppr isrec
508
509pprAxiom :: Maybe Name -> SDoc
510pprAxiom Nothing   = ptext (sLit "FamilyInstance: none")
511pprAxiom (Just ax) = ptext (sLit "FamilyInstance:") <+> ppr ax
512
513instance Outputable IfaceClassOp where
514   ppr (IfaceClassOp n dm ty) = ppr n <+> ppr dm <+> dcolon <+> ppr ty
515
516instance Outputable IfaceAT where
517   ppr (IfaceAT d defs) = hang (ppr d) 2 (vcat (map ppr defs))
518
519instance Outputable IfaceATDefault where
520   ppr (IfaceATD tvs pat_tys ty) = ppr tvs <+> hsep (map ppr pat_tys) <+> char '=' <+> ppr ty
521
522pprIfaceDeclHead :: IfaceContext -> OccName -> [IfaceTvBndr] -> SDoc
523pprIfaceDeclHead context thing tyvars
524  = hsep [pprIfaceContext context, parenSymOcc thing (ppr thing),
525          pprIfaceTvBndrs tyvars]
526
527pp_condecls :: OccName -> IfaceConDecls -> SDoc
528pp_condecls _  (IfAbstractTyCon {}) = empty
529pp_condecls _  IfDataFamTyCon      = empty
530pp_condecls tc (IfNewTyCon c)   = equals <+> pprIfaceConDecl tc c
531pp_condecls tc (IfDataTyCon cs) = equals <+> sep (punctuate (ptext (sLit " |"))
532                                                            (map (pprIfaceConDecl tc) cs))
533
534mkIfaceEqPred :: IfaceType -> IfaceType -> IfacePredType
535-- IA0_NOTE: This is wrong, but only used for pretty-printing.
536mkIfaceEqPred ty1 ty2 = IfaceTyConApp (IfaceTc eqTyConName) [ty1, ty2]
537
538pprIfaceConDecl :: OccName -> IfaceConDecl -> SDoc
539pprIfaceConDecl tc
540        (IfCon { ifConOcc = name, ifConInfix = is_infix, ifConWrapper = has_wrap,
541                 ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs,
542                 ifConEqSpec = eq_spec, ifConCtxt = ctxt, ifConArgTys = arg_tys,
543                 ifConStricts = strs, ifConFields = fields })
544  = sep [main_payload,
545         if is_infix then ptext (sLit "Infix") else empty,
546         if has_wrap then ptext (sLit "HasWrapper") else empty,
547         ppUnless (null strs) $
548            nest 4 (ptext (sLit "Stricts:") <+> hsep (map ppr_bang strs)),
549         ppUnless (null fields) $
550            nest 4 (ptext (sLit "Fields:") <+> hsep (map ppr fields))]
551  where
552    ppr_bang HsNoBang = char '_'        -- Want to see these
553    ppr_bang bang     = ppr bang
554
555    main_payload = ppr name <+> dcolon <+>
556                   pprIfaceForAllPart (univ_tvs ++ ex_tvs) (eq_ctxt ++ ctxt) pp_tau
557
558    eq_ctxt = [(mkIfaceEqPred (IfaceTyVar (occNameFS tv)) ty)
559              | (tv,ty) <- eq_spec]
560
561        -- A bit gruesome this, but we can't form the full con_tau, and ppr it,
562        -- because we don't have a Name for the tycon, only an OccName
563    pp_tau = case map pprParendIfaceType arg_tys ++ [pp_res_ty] of
564                (t:ts) -> fsep (t : map (arrow <+>) ts)
565                []     -> panic "pp_con_taus"
566
567    pp_res_ty = ppr tc <+> fsep [ppr tv | (tv,_) <- univ_tvs]
568
569instance Outputable IfaceRule where
570  ppr (IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
571                   ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
572    = sep [hsep [doubleQuotes (ftext name), ppr act,
573                 ptext (sLit "forall") <+> pprIfaceBndrs bndrs],
574           nest 2 (sep [ppr fn <+> sep (map pprParendIfaceExpr args),
575                        ptext (sLit "=") <+> ppr rhs])
576      ]
577
578instance Outputable IfaceClsInst where
579  ppr (IfaceClsInst {ifDFun = dfun_id, ifOFlag = flag,
580                  ifInstCls = cls, ifInstTys = mb_tcs})
581    = hang (ptext (sLit "instance") <+> ppr flag
582                <+> ppr cls <+> brackets (pprWithCommas ppr_rough mb_tcs))
583         2 (equals <+> ppr dfun_id)
584
585instance Outputable IfaceFamInst where
586  ppr (IfaceFamInst {ifFamInstFam = fam, ifFamInstTys = mb_tcs,
587                     ifFamInstAxiom = tycon_ax})
588    = hang (ptext (sLit "family instance") <+>
589            ppr fam <+> brackets (pprWithCommas ppr_rough mb_tcs))
590         2 (equals <+> ppr tycon_ax)
591
592ppr_rough :: Maybe IfaceTyCon -> SDoc
593ppr_rough Nothing   = dot
594ppr_rough (Just tc) = ppr tc
595\end{code}
596
597
598----------------------------- Printing IfaceExpr ------------------------------------
599
600\begin{code}
601instance Outputable IfaceExpr where
602    ppr e = pprIfaceExpr noParens e
603
604pprParendIfaceExpr :: IfaceExpr -> SDoc
605pprParendIfaceExpr = pprIfaceExpr parens
606
607-- | Pretty Print an IfaceExpre
608--
609-- The first argument should be a function that adds parens in context that need
610-- an atomic value (e.g. function args)
611pprIfaceExpr :: (SDoc -> SDoc) -> IfaceExpr -> SDoc
612
613pprIfaceExpr _       (IfaceLcl v)       = ppr v
614pprIfaceExpr _       (IfaceExt v)       = ppr v
615pprIfaceExpr _       (IfaceLit l)       = ppr l
616pprIfaceExpr _       (IfaceFCall cc ty) = braces (ppr cc <+> ppr ty)
617pprIfaceExpr _       (IfaceType ty)     = char '@' <+> pprParendIfaceType ty
618pprIfaceExpr _       (IfaceCo co)       = text "@~" <+> pprParendIfaceType co
619
620pprIfaceExpr add_par app@(IfaceApp _ _) = add_par (pprIfaceApp app [])
621pprIfaceExpr _       (IfaceTuple c as)  = tupleParens c (interpp'SP as)
622
623pprIfaceExpr add_par i@(IfaceLam _ _)
624  = add_par (sep [char '\\' <+> sep (map ppr bndrs) <+> arrow,
625                  pprIfaceExpr noParens body])
626  where
627    (bndrs,body) = collect [] i
628    collect bs (IfaceLam b e) = collect (b:bs) e
629    collect bs e              = (reverse bs, e)
630
631pprIfaceExpr add_par (IfaceECase scrut ty)
632  = add_par (sep [ ptext (sLit "case") <+> pprIfaceExpr noParens scrut
633                 , ptext (sLit "ret_ty") <+> pprParendIfaceType ty
634                 , ptext (sLit "of {}") ])
635
636pprIfaceExpr add_par (IfaceCase scrut bndr [(con, bs, rhs)])
637  = add_par (sep [ptext (sLit "case") 
638                        <+> pprIfaceExpr noParens scrut <+> ptext (sLit "of") 
639                        <+> ppr bndr <+> char '{' <+> ppr_con_bs con bs <+> arrow,
640                  pprIfaceExpr noParens rhs <+> char '}'])
641
642pprIfaceExpr add_par (IfaceCase scrut bndr alts)
643  = add_par (sep [ptext (sLit "case") 
644                        <+> pprIfaceExpr noParens scrut <+> ptext (sLit "of") 
645                        <+> ppr bndr <+> char '{',
646                  nest 2 (sep (map ppr_alt alts)) <+> char '}'])
647
648pprIfaceExpr _       (IfaceCast expr co)
649  = sep [pprParendIfaceExpr expr,
650         nest 2 (ptext (sLit "`cast`")),
651         pprParendIfaceType co]
652
653pprIfaceExpr add_par (IfaceLet (IfaceNonRec b rhs) body)
654  = add_par (sep [ptext (sLit "let {"),
655                  nest 2 (ppr_bind (b, rhs)),
656                  ptext (sLit "} in"),
657                  pprIfaceExpr noParens body])
658
659pprIfaceExpr add_par (IfaceLet (IfaceRec pairs) body)
660  = add_par (sep [ptext (sLit "letrec {"),
661                  nest 2 (sep (map ppr_bind pairs)),
662                  ptext (sLit "} in"),
663                  pprIfaceExpr noParens body])
664
665pprIfaceExpr add_par (IfaceTick tickish e)
666  = add_par (pprIfaceTickish tickish <+> pprIfaceExpr noParens e)
667
668ppr_alt :: (IfaceConAlt, [IfLclName], IfaceExpr) -> SDoc
669ppr_alt (con, bs, rhs) = sep [ppr_con_bs con bs,
670                         arrow <+> pprIfaceExpr noParens rhs]
671
672ppr_con_bs :: IfaceConAlt -> [IfLclName] -> SDoc
673ppr_con_bs con bs = ppr con <+> hsep (map ppr bs)
674
675ppr_bind :: (IfaceLetBndr, IfaceExpr) -> SDoc
676ppr_bind (IfLetBndr b ty info, rhs)
677  = sep [hang (ppr b <+> dcolon <+> ppr ty) 2 (ppr info),
678         equals <+> pprIfaceExpr noParens rhs]
679
680------------------
681pprIfaceTickish :: IfaceTickish -> SDoc
682pprIfaceTickish (IfaceHpcTick m ix)
683  = braces (text "tick" <+> ppr m <+> ppr ix)
684pprIfaceTickish (IfaceSCC cc tick scope)
685  = braces (pprCostCentreCore cc <+> ppr tick <+> ppr scope)
686
687------------------
688pprIfaceApp :: IfaceExpr -> [SDoc] -> SDoc
689pprIfaceApp (IfaceApp fun arg) args = pprIfaceApp fun $
690                                          nest 2 (pprParendIfaceExpr arg) : args
691pprIfaceApp fun                args = sep (pprParendIfaceExpr fun : args)
692
693------------------
694instance Outputable IfaceConAlt where
695    ppr IfaceDefault      = text "DEFAULT"
696    ppr (IfaceLitAlt l)   = ppr l
697    ppr (IfaceDataAlt d)  = ppr d
698
699------------------
700instance Outputable IfaceIdDetails where
701  ppr IfVanillaId       = empty
702  ppr (IfRecSelId tc b) = ptext (sLit "RecSel") <+> ppr tc
703                          <+> if b then ptext (sLit "<naughty>") else empty
704  ppr IfDFunId          = ptext (sLit "DFunId")
705
706instance Outputable IfaceIdInfo where
707  ppr NoInfo       = empty
708  ppr (HasInfo is) = ptext (sLit "{-") <+> pprWithCommas ppr is
709                     <+> ptext (sLit "-}")
710
711instance Outputable IfaceInfoItem where
712  ppr (HsUnfold lb unf)  = ptext (sLit "Unfolding")
713                           <> ppWhen lb (ptext (sLit "(loop-breaker)"))
714                           <> colon <+> ppr unf
715  ppr (HsInline prag)    = ptext (sLit "Inline:") <+> ppr prag
716  ppr (HsArity arity)    = ptext (sLit "Arity:") <+> int arity
717  ppr (HsStrictness str) = ptext (sLit "Strictness:") <+> pprIfaceStrictSig str
718  ppr HsNoCafRefs        = ptext (sLit "HasNoCafRefs")
719
720instance Outputable IfaceUnfolding where
721  ppr (IfCompulsory e)     = ptext (sLit "<compulsory>") <+> parens (ppr e)
722  ppr (IfCoreUnfold s e)   = (if s then ptext (sLit "<stable>") else empty)
723                              <+> parens (ppr e)
724  ppr (IfInlineRule a uok bok e) = sep [ptext (sLit "InlineRule")
725                                            <+> ppr (a,uok,bok),
726                                        pprParendIfaceExpr e]
727  ppr (IfLclWrapper a wkr) = ptext (sLit "Worker(lcl):") <+> ppr wkr
728                             <+> parens (ptext (sLit "arity") <+> int a)
729  ppr (IfExtWrapper a wkr) = ptext (sLit "Worker(ext0:") <+> ppr wkr
730                             <+> parens (ptext (sLit "arity") <+> int a)
731  ppr (IfDFunUnfold ns)    = ptext (sLit "DFun:")
732                             <+> brackets (pprWithCommas ppr ns)
733
734-- -----------------------------------------------------------------------------
735-- | Finding the Names in IfaceSyn
736
737-- This is used for dependency analysis in MkIface, so that we
738-- fingerprint a declaration before the things that depend on it.  It
739-- is specific to interface-file fingerprinting in the sense that we
740-- don't collect *all* Names: for example, the DFun of an instance is
741-- recorded textually rather than by its fingerprint when
742-- fingerprinting the instance, so DFuns are not dependencies.
743
744freeNamesIfDecl :: IfaceDecl -> NameSet
745freeNamesIfDecl (IfaceId _s t d i) =
746  freeNamesIfType t &&&
747  freeNamesIfIdInfo i &&&
748  freeNamesIfIdDetails d
749freeNamesIfDecl IfaceForeign{} =
750  emptyNameSet
751freeNamesIfDecl d@IfaceData{} =
752  freeNamesIfTvBndrs (ifTyVars d) &&&
753  maybe emptyNameSet unitNameSet (ifAxiom d) &&&
754  freeNamesIfContext (ifCtxt d) &&&
755  freeNamesIfConDecls (ifCons d)
756freeNamesIfDecl d@IfaceSyn{} =
757  freeNamesIfTvBndrs (ifTyVars d) &&&
758  freeNamesIfSynRhs (ifSynRhs d) &&&
759  freeNamesIfKind (ifSynKind d) -- IA0_NOTE: because of promotion, we
760                                -- return names in the kind signature
761freeNamesIfDecl d@IfaceClass{} =
762  freeNamesIfTvBndrs (ifTyVars d) &&&
763  freeNamesIfContext (ifCtxt d) &&&
764  fnList freeNamesIfAT     (ifATs d) &&&
765  fnList freeNamesIfClsSig (ifSigs d)
766freeNamesIfDecl d@IfaceAxiom{} =
767  freeNamesIfTvBndrs (ifTyVars d) &&&
768  freeNamesIfType (ifLHS d) &&&
769  freeNamesIfType (ifRHS d)
770
771freeNamesIfIdDetails :: IfaceIdDetails -> NameSet
772freeNamesIfIdDetails (IfRecSelId tc _) = freeNamesIfTc tc
773freeNamesIfIdDetails _                 = emptyNameSet
774
775-- All other changes are handled via the version info on the tycon
776freeNamesIfSynRhs :: Maybe IfaceType -> NameSet
777freeNamesIfSynRhs (Just ty) = freeNamesIfType ty
778freeNamesIfSynRhs Nothing   = emptyNameSet
779
780freeNamesIfContext :: IfaceContext -> NameSet
781freeNamesIfContext = fnList freeNamesIfType
782
783freeNamesIfAT :: IfaceAT -> NameSet
784freeNamesIfAT (IfaceAT decl defs)
785  = freeNamesIfDecl decl &&&
786    fnList fn_at_def defs
787  where
788    fn_at_def (IfaceATD tvs pat_tys ty)
789      = freeNamesIfTvBndrs tvs &&&
790        fnList freeNamesIfType pat_tys &&&
791        freeNamesIfType ty
792
793freeNamesIfClsSig :: IfaceClassOp -> NameSet
794freeNamesIfClsSig (IfaceClassOp _n _dm ty) = freeNamesIfType ty
795
796freeNamesIfConDecls :: IfaceConDecls -> NameSet
797freeNamesIfConDecls (IfDataTyCon c) = fnList freeNamesIfConDecl c
798freeNamesIfConDecls (IfNewTyCon c)  = freeNamesIfConDecl c
799freeNamesIfConDecls _               = emptyNameSet
800
801freeNamesIfConDecl :: IfaceConDecl -> NameSet
802freeNamesIfConDecl c =
803  freeNamesIfTvBndrs (ifConUnivTvs c) &&&
804  freeNamesIfTvBndrs (ifConExTvs c) &&&
805  freeNamesIfContext (ifConCtxt c) &&&
806  fnList freeNamesIfType (ifConArgTys c) &&&
807  fnList freeNamesIfType (map snd (ifConEqSpec c)) -- equality constraints
808
809freeNamesIfKind :: IfaceType -> NameSet
810freeNamesIfKind = freeNamesIfType
811
812freeNamesIfType :: IfaceType -> NameSet
813freeNamesIfType (IfaceTyVar _)        = emptyNameSet
814freeNamesIfType (IfaceAppTy s t)      = freeNamesIfType s &&& freeNamesIfType t
815freeNamesIfType (IfaceTyConApp tc ts) =
816   freeNamesIfTc tc &&& fnList freeNamesIfType ts
817freeNamesIfType (IfaceLitTy _)        = emptyNameSet
818freeNamesIfType (IfaceForAllTy tv t)  =
819   freeNamesIfTvBndr tv &&& freeNamesIfType t
820freeNamesIfType (IfaceFunTy s t)      = freeNamesIfType s &&& freeNamesIfType t
821freeNamesIfType (IfaceCoConApp tc ts) = 
822   freeNamesIfCo tc &&& fnList freeNamesIfType ts
823
824freeNamesIfTvBndrs :: [IfaceTvBndr] -> NameSet
825freeNamesIfTvBndrs = fnList freeNamesIfTvBndr
826
827freeNamesIfBndr :: IfaceBndr -> NameSet
828freeNamesIfBndr (IfaceIdBndr b) = freeNamesIfIdBndr b
829freeNamesIfBndr (IfaceTvBndr b) = freeNamesIfTvBndr b
830
831freeNamesIfLetBndr :: IfaceLetBndr -> NameSet
832-- Remember IfaceLetBndr is used only for *nested* bindings
833-- The IdInfo can contain an unfolding (in the case of
834-- local INLINE pragmas), so look there too
835freeNamesIfLetBndr (IfLetBndr _name ty info) = freeNamesIfType ty
836                                             &&& freeNamesIfIdInfo info
837
838freeNamesIfTvBndr :: IfaceTvBndr -> NameSet
839freeNamesIfTvBndr (_fs,k) = freeNamesIfKind k
840    -- kinds can have Names inside, because of promotion
841
842freeNamesIfIdBndr :: IfaceIdBndr -> NameSet
843freeNamesIfIdBndr = freeNamesIfTvBndr
844
845freeNamesIfIdInfo :: IfaceIdInfo -> NameSet
846freeNamesIfIdInfo NoInfo      = emptyNameSet
847freeNamesIfIdInfo (HasInfo i) = fnList freeNamesItem i
848
849freeNamesItem :: IfaceInfoItem -> NameSet
850freeNamesItem (HsUnfold _ u) = freeNamesIfUnfold u
851freeNamesItem _              = emptyNameSet
852
853freeNamesIfUnfold :: IfaceUnfolding -> NameSet
854freeNamesIfUnfold (IfCoreUnfold _ e)     = freeNamesIfExpr e
855freeNamesIfUnfold (IfCompulsory e)       = freeNamesIfExpr e
856freeNamesIfUnfold (IfInlineRule _ _ _ e) = freeNamesIfExpr e
857freeNamesIfUnfold (IfExtWrapper _ v)     = unitNameSet v
858freeNamesIfUnfold (IfLclWrapper {})      = emptyNameSet
859freeNamesIfUnfold (IfDFunUnfold vs)      = fnList freeNamesIfExpr vs
860
861freeNamesIfExpr :: IfaceExpr -> NameSet
862freeNamesIfExpr (IfaceExt v)      = unitNameSet v
863freeNamesIfExpr (IfaceFCall _ ty) = freeNamesIfType ty
864freeNamesIfExpr (IfaceType ty)    = freeNamesIfType ty
865freeNamesIfExpr (IfaceCo co)      = freeNamesIfType co
866freeNamesIfExpr (IfaceTuple _ as) = fnList freeNamesIfExpr as
867freeNamesIfExpr (IfaceLam b body) = freeNamesIfBndr b &&& freeNamesIfExpr body
868freeNamesIfExpr (IfaceApp f a)    = freeNamesIfExpr f &&& freeNamesIfExpr a
869freeNamesIfExpr (IfaceCast e co)  = freeNamesIfExpr e &&& freeNamesIfType co
870freeNamesIfExpr (IfaceTick _ e)   = freeNamesIfExpr e
871freeNamesIfExpr (IfaceECase e ty) = freeNamesIfExpr e &&& freeNamesIfType ty
872freeNamesIfExpr (IfaceCase s _ alts)
873  = freeNamesIfExpr s
874    &&& fnList fn_alt alts &&& fn_cons alts
875  where
876    fn_alt (_con,_bs,r) = freeNamesIfExpr r
877
878    -- Depend on the data constructors.  Just one will do!
879    -- Note [Tracking data constructors]
880    fn_cons []                            = emptyNameSet
881    fn_cons ((IfaceDefault    ,_,_) : xs) = fn_cons xs
882    fn_cons ((IfaceDataAlt con,_,_) : _ ) = unitNameSet con
883    fn_cons (_                      : _ ) = emptyNameSet
884
885freeNamesIfExpr (IfaceLet (IfaceNonRec bndr rhs) body)
886  = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs &&& freeNamesIfExpr body
887
888freeNamesIfExpr (IfaceLet (IfaceRec as) x)
889  = fnList fn_pair as &&& freeNamesIfExpr x
890  where
891    fn_pair (bndr, rhs) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs
892
893freeNamesIfExpr _ = emptyNameSet
894
895freeNamesIfTc :: IfaceTyCon -> NameSet
896freeNamesIfTc (IfaceTc tc) = unitNameSet tc
897-- ToDo: shouldn't we include IfaceIntTc & co.?
898
899freeNamesIfCo :: IfaceCoCon -> NameSet
900freeNamesIfCo (IfaceCoAx tc) = unitNameSet tc
901-- ToDo: include IfaceIPCoAx? Probably not necessary.
902freeNamesIfCo _ = emptyNameSet
903
904freeNamesIfRule :: IfaceRule -> NameSet
905freeNamesIfRule (IfaceRule { ifRuleBndrs = bs, ifRuleHead = f
906                           , ifRuleArgs = es, ifRuleRhs = rhs })
907  = unitNameSet f &&&
908    fnList freeNamesIfBndr bs &&&
909    fnList freeNamesIfExpr es &&&
910    freeNamesIfExpr rhs
911   
912freeNamesIfFamInst :: IfaceFamInst -> NameSet
913freeNamesIfFamInst (IfaceFamInst { ifFamInstFam = famName
914                                 , ifFamInstAxiom = axName })
915  = unitNameSet famName &&&
916    unitNameSet axName
917
918-- helpers
919(&&&) :: NameSet -> NameSet -> NameSet
920(&&&) = unionNameSets
921
922fnList :: (a -> NameSet) -> [a] -> NameSet
923fnList f = foldr (&&&) emptyNameSet . map f
924\end{code}
925
926Note [Tracking data constructors]
927~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
928In a case expression
929   case e of { C a -> ...; ... }
930You might think that we don't need to include the datacon C
931in the free names, because its type will probably show up in
932the free names of 'e'.  But in rare circumstances this may
933not happen.   Here's the one that bit me:
934
935   module DynFlags where
936     import {-# SOURCE #-} Packages( PackageState )
937     data DynFlags = DF ... PackageState ...
938
939   module Packages where
940     import DynFlags
941     data PackageState = PS ...
942     lookupModule (df :: DynFlags)
943        = case df of
944              DF ...p... -> case p of
945                               PS ... -> ...
946
947Now, lookupModule depends on DynFlags, but the transitive dependency
948on the *locally-defined* type PackageState is not visible. We need
949to take account of the use of the data constructor PS in the pattern match.
Note: See TracBrowser for help on using the browser.