Extended TyCon and friends to represent family declarations
[ghc-hetmet.git] / compiler / iface / IfaceSyn.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 %************************************************************************
5 %*                                                                      *
6 \section[HsCore]{Core-syntax unfoldings in Haskell interface files}
7 %*                                                                      *
8 %************************************************************************
9
10 We could either use this, or parameterise @GenCoreExpr@ on @Types@ and
11 @TyVars@ as well.  Currently trying the former... MEGA SIGH.
12
13 \begin{code}
14 module IfaceSyn (
15         module IfaceType,               -- Re-export all this
16
17         IfaceDecl(..), IfaceClassOp(..), IfaceConDecl(..), IfaceConDecls(..),
18         IfaceExpr(..), IfaceAlt, IfaceNote(..),
19         IfaceBinding(..), IfaceConAlt(..), IfaceIdInfo(..),
20         IfaceInfoItem(..), IfaceRule(..), IfaceInst(..), 
21
22         -- Misc
23         visibleIfConDecls,
24
25         -- Equality
26         IfaceEq(..), (&&&), bool, eqListBy, eqMaybeBy,
27         eqIfDecl, eqIfInst, eqIfRule, checkBootDecl,
28         
29         -- Pretty printing
30         pprIfaceExpr, pprIfaceDecl, pprIfaceDeclHead 
31     ) where
32
33 #include "HsVersions.h"
34
35 import CoreSyn
36 import IfaceType
37
38 import NewDemand        ( StrictSig, pprIfaceStrictSig )
39 import TcType           ( deNoteType )
40 import Class            ( FunDep, DefMeth, pprFundeps )
41 import OccName          ( OccName, parenSymOcc, occNameFS,
42                           OccSet, unionOccSets, unitOccSet )
43 import UniqFM           ( UniqFM, emptyUFM, addToUFM, lookupUFM )
44 import Name             ( Name, NamedThing(..), nameOccName, isExternalName )
45 import CostCentre       ( CostCentre, pprCostCentreCore )
46 import Literal          ( Literal )
47 import ForeignCall      ( ForeignCall )
48 import BasicTypes       ( Arity, Activation(..), StrictnessMark, OverlapFlag,
49                           RecFlag(..), Boxity(..), 
50                           isAlwaysActive, tupleParens )
51 import Outputable
52 import FastString
53 import Maybes           ( catMaybes )
54 import Util             ( lengthIs )
55
56 infixl 3 &&&
57 infix  4 `eqIfExt`, `eqIfIdInfo`, `eqIfType`
58 \end{code}
59
60
61 %************************************************************************
62 %*                                                                      *
63                 Data type declarations
64 %*                                                                      *
65 %************************************************************************
66
67 \begin{code}
68 data IfaceDecl 
69   = IfaceId { ifName   :: OccName,
70               ifType   :: IfaceType, 
71               ifIdInfo :: IfaceIdInfo }
72
73   | IfaceData { ifName       :: OccName,                -- Type constructor
74                 ifTyVars     :: [IfaceTvBndr],  -- Type variables
75                 ifCtxt       :: IfaceContext,   -- The "stupid theta"
76                 ifCons       :: IfaceConDecls,  -- Includes new/data info
77                 ifRec        :: RecFlag,        -- Recursive or not?
78                 ifGadtSyntax :: Bool,           -- True <=> declared using GADT syntax
79                 ifGeneric    :: Bool            -- True <=> generic converter functions available
80     }                                           -- We need this for imported data decls, since the
81                                                 -- imported modules may have been compiled with
82                                                 -- different flags to the current compilation unit
83
84   | IfaceSyn  { ifName    :: OccName,           -- Type constructor
85                 ifTyVars  :: [IfaceTvBndr],     -- Type variables
86                 ifOpenSyn :: Bool,              -- Is an open family?
87                 ifSynRhs  :: IfaceType          -- Type for an ordinary
88                                                 -- synonym and kind for an
89                                                 -- open family
90     }
91
92   | IfaceClass { ifCtxt    :: IfaceContext,     -- Context...
93                  ifName    :: OccName,          -- Name of the class
94                  ifTyVars  :: [IfaceTvBndr],    -- Type variables
95                  ifFDs     :: [FunDep FastString], -- Functional dependencies
96                  ifSigs    :: [IfaceClassOp],   -- Method signatures
97                  ifRec     :: RecFlag           -- Is newtype/datatype associated with the class recursive?
98     }
99
100   | IfaceForeign { ifName :: OccName,           -- Needs expanding when we move beyond .NET
101                    ifExtName :: Maybe FastString }
102
103 data IfaceClassOp = IfaceClassOp OccName DefMeth IfaceType
104         -- Nothing    => no default method
105         -- Just False => ordinary polymorphic default method
106         -- Just True  => generic default method
107
108 data IfaceConDecls
109   = IfAbstractTyCon             -- No info
110   | IfOpenDataTyCon             -- Open data family
111   | IfOpenNewTyCon              -- Open newtype family
112   | IfDataTyCon [IfaceConDecl]  -- data type decls
113   | IfNewTyCon  IfaceConDecl    -- newtype decls
114
115 visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl]
116 visibleIfConDecls IfAbstractTyCon  = []
117 visibleIfConDecls IfOpenDataTyCon  = []
118 visibleIfConDecls IfOpenNewTyCon   = []
119 visibleIfConDecls (IfDataTyCon cs) = cs
120 visibleIfConDecls (IfNewTyCon c)   = [c]
121
122 data IfaceConDecl 
123   = IfCon {
124         ifConOcc     :: OccName,                -- Constructor name
125         ifConInfix   :: Bool,                   -- True <=> declared infix
126         ifConUnivTvs :: [IfaceTvBndr],          -- Universal tyvars
127         ifConExTvs   :: [IfaceTvBndr],          -- Existential tyvars
128         ifConEqSpec  :: [(OccName,IfaceType)],  -- Equality contraints
129         ifConCtxt    :: IfaceContext,           -- Non-stupid context
130         ifConArgTys  :: [IfaceType],            -- Arg types
131         ifConFields  :: [OccName],              -- ...ditto... (field labels)
132         ifConStricts :: [StrictnessMark] }      -- Empty (meaning all lazy), or 1-1 corresp with arg types
133                         
134 data IfaceInst 
135   = IfaceInst { ifInstCls  :: IfaceExtName,             -- See comments with
136                 ifInstTys  :: [Maybe IfaceTyCon],       -- the defn of Instance
137                 ifDFun     :: OccName,                  -- The dfun
138                 ifOFlag    :: OverlapFlag,              -- Overlap flag
139                 ifInstOrph :: Maybe OccName }           -- See is_orph in defn of Instance
140         -- There's always a separate IfaceDecl for the DFun, which gives 
141         -- its IdInfo with its full type and version number.
142         -- The instance declarations taken together have a version number,
143         -- and we don't want that to wobble gratuitously
144         -- If this instance decl is *used*, we'll record a usage on the dfun;
145         -- and if the head does not change it won't be used if it wasn't before
146
147 data IfaceRule
148   = IfaceRule { 
149         ifRuleName   :: RuleName,
150         ifActivation :: Activation,
151         ifRuleBndrs  :: [IfaceBndr],    -- Tyvars and term vars
152         ifRuleHead   :: IfaceExtName,   -- Head of lhs
153         ifRuleArgs   :: [IfaceExpr],    -- Args of LHS
154         ifRuleRhs    :: IfaceExpr,
155         ifRuleOrph   :: Maybe OccName   -- Just like IfaceInst
156     }
157
158 data IfaceIdInfo
159   = NoInfo                      -- When writing interface file without -O
160   | HasInfo [IfaceInfoItem]     -- Has info, and here it is
161
162 -- Here's a tricky case:
163 --   * Compile with -O module A, and B which imports A.f
164 --   * Change function f in A, and recompile without -O
165 --   * When we read in old A.hi we read in its IdInfo (as a thunk)
166 --      (In earlier GHCs we used to drop IdInfo immediately on reading,
167 --       but we do not do that now.  Instead it's discarded when the
168 --       ModIface is read into the various decl pools.)
169 --   * The version comparsion sees that new (=NoInfo) differs from old (=HasInfo *)
170 --      and so gives a new version.
171
172 data IfaceInfoItem
173   = HsArity      Arity
174   | HsStrictness StrictSig
175   | HsInline     Activation
176   | HsUnfold     IfaceExpr
177   | HsNoCafRefs
178   | HsWorker     IfaceExtName Arity     -- Worker, if any see IdInfo.WorkerInfo
179                                         -- for why we want arity here.
180         -- NB: we need IfaceExtName (not just OccName) because the worker
181         --     can simplify to a function in another module.
182 -- NB: Specialisations and rules come in separately and are
183 -- only later attached to the Id.  Partial reason: some are orphans.
184
185 --------------------------------
186 data IfaceExpr
187   = IfaceLcl    FastString
188   | IfaceExt    IfaceExtName
189   | IfaceType   IfaceType
190   | IfaceTuple  Boxity [IfaceExpr]              -- Saturated; type arguments omitted
191   | IfaceLam    IfaceBndr IfaceExpr
192   | IfaceApp    IfaceExpr IfaceExpr
193   | IfaceCase   IfaceExpr FastString IfaceType [IfaceAlt]
194   | IfaceLet    IfaceBinding  IfaceExpr
195   | IfaceNote   IfaceNote IfaceExpr
196   | IfaceCast   IfaceExpr IfaceCoercion
197   | IfaceLit    Literal
198   | IfaceFCall  ForeignCall IfaceType
199
200 data IfaceNote = IfaceSCC CostCentre
201                | IfaceInlineMe
202                | IfaceCoreNote String
203
204 type IfaceAlt = (IfaceConAlt, [FastString], IfaceExpr)
205         -- Note: FastString, not IfaceBndr (and same with the case binder)
206         -- We reconstruct the kind/type of the thing from the context
207         -- thus saving bulk in interface files
208
209 data IfaceConAlt = IfaceDefault
210                  | IfaceDataAlt OccName
211                  | IfaceTupleAlt Boxity
212                  | IfaceLitAlt Literal
213
214 data IfaceBinding
215   = IfaceNonRec IfaceIdBndr IfaceExpr
216   | IfaceRec    [(IfaceIdBndr, IfaceExpr)]
217 \end{code}
218
219
220 %************************************************************************
221 %*                                                                      *
222 \subsection[HsCore-print]{Printing Core unfoldings}
223 %*                                                                      *
224 %************************************************************************
225
226 ----------------------------- Printing IfaceDecl ------------------------------------
227
228 \begin{code}
229 instance Outputable IfaceDecl where
230   ppr = pprIfaceDecl
231
232 pprIfaceDecl (IfaceId {ifName = var, ifType = ty, ifIdInfo = info})
233   = sep [ ppr var <+> dcolon <+> ppr ty, 
234           nest 2 (ppr info) ]
235
236 pprIfaceDecl (IfaceForeign {ifName = tycon})
237   = hsep [ptext SLIT("foreign import type dotnet"), ppr tycon]
238
239 pprIfaceDecl (IfaceSyn {ifName = tycon, ifTyVars = tyvars, 
240                         ifOpenSyn = False, ifSynRhs = mono_ty})
241   = hang (ptext SLIT("type") <+> pprIfaceDeclHead [] tycon tyvars)
242        4 (equals <+> ppr mono_ty)
243
244 pprIfaceDecl (IfaceSyn {ifName = tycon, ifTyVars = tyvars, 
245                         ifOpenSyn = True, ifSynRhs = mono_ty})
246   = hang (ptext SLIT("type family") <+> pprIfaceDeclHead [] tycon tyvars)
247        4 (dcolon <+> ppr mono_ty)
248
249 pprIfaceDecl (IfaceData {ifName = tycon, ifGeneric = gen, ifCtxt = context,
250                          ifTyVars = tyvars, ifCons = condecls, 
251                          ifRec = isrec})
252   = hang (pp_nd <+> pprIfaceDeclHead context tycon tyvars)
253        4 (vcat [pprRec isrec, pprGen gen, pp_condecls tycon condecls])
254   where
255     pp_nd = case condecls of
256                 IfAbstractTyCon -> ptext SLIT("data")
257                 IfOpenDataTyCon -> ptext SLIT("data family")
258                 IfDataTyCon _   -> ptext SLIT("data")
259                 IfNewTyCon _    -> ptext SLIT("newtype")
260                 IfOpenNewTyCon  -> ptext SLIT("newtype family")
261
262 pprIfaceDecl (IfaceClass {ifCtxt = context, ifName = clas, ifTyVars = tyvars, 
263                           ifFDs = fds, ifSigs = sigs, ifRec = isrec})
264   = hang (ptext SLIT("class") <+> pprIfaceDeclHead context clas tyvars <+> pprFundeps fds)
265        4 (vcat [pprRec isrec,
266                 sep (map ppr sigs)])
267
268 pprRec isrec = ptext SLIT("RecFlag") <+> ppr isrec
269 pprGen True  = ptext SLIT("Generics: yes")
270 pprGen False = ptext SLIT("Generics: no")
271
272 instance Outputable IfaceClassOp where
273    ppr (IfaceClassOp n dm ty) = ppr n <+> ppr dm <+> dcolon <+> ppr ty
274
275 pprIfaceDeclHead :: IfaceContext -> OccName -> [IfaceTvBndr] -> SDoc
276 pprIfaceDeclHead context thing tyvars 
277   = hsep [pprIfaceContext context, parenSymOcc thing (ppr thing), pprIfaceTvBndrs tyvars]
278
279 pp_condecls tc IfAbstractTyCon  = ptext SLIT("{- abstract -}")
280 pp_condecls tc IfOpenNewTyCon   = empty
281 pp_condecls tc (IfNewTyCon c)   = equals <+> pprIfaceConDecl tc c
282 pp_condecls tc IfOpenDataTyCon  = empty
283 pp_condecls tc (IfDataTyCon cs) = equals <+> sep (punctuate (ptext SLIT(" |"))
284                                                              (map (pprIfaceConDecl tc) cs))
285
286 pprIfaceConDecl tc
287         (IfCon { ifConOcc = name, ifConInfix = is_infix, 
288                  ifConUnivTvs = univ_tvs, ifConExTvs = ex_tvs, 
289                  ifConEqSpec = eq_spec, ifConCtxt = ctxt, ifConArgTys = arg_tys, 
290                  ifConStricts = strs, ifConFields = fields })
291   = sep [main_payload,
292          if is_infix then ptext SLIT("Infix") else empty,
293          if null strs then empty 
294               else nest 4 (ptext SLIT("Stricts:") <+> hsep (map ppr strs)),
295          if null fields then empty
296               else nest 4 (ptext SLIT("Fields:") <+> hsep (map ppr fields))]
297   where
298     main_payload = ppr name <+> dcolon <+> 
299                    pprIfaceForAllPart (univ_tvs ++ ex_tvs) (eq_ctxt ++ ctxt) (ppr con_tau)
300
301     eq_ctxt = [(IfaceEqPred (IfaceTyVar (occNameFS tv)) ty) 
302               | (tv,ty) <- eq_spec] 
303     con_tau = foldr1 IfaceFunTy (arg_tys ++ [tc_app])
304     tc_app  = IfaceTyConApp (IfaceTc (LocalTop tc)) 
305                             [IfaceTyVar tv | (tv,_) <- univ_tvs]
306         -- Gruesome, but jsut for debug print
307
308 instance Outputable IfaceRule where
309   ppr (IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
310                    ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs }) 
311     = sep [hsep [doubleQuotes (ftext name), ppr act,
312                  ptext SLIT("forall") <+> pprIfaceBndrs bndrs],
313            nest 2 (sep [ppr fn <+> sep (map (pprIfaceExpr parens) args),
314                         ptext SLIT("=") <+> ppr rhs])
315       ]
316
317 instance Outputable IfaceInst where
318   ppr (IfaceInst {ifDFun = dfun_id, ifOFlag = flag, 
319                   ifInstCls = cls, ifInstTys = mb_tcs})
320     = hang (ptext SLIT("instance") <+> ppr flag 
321                 <+> ppr cls <+> brackets (pprWithCommas ppr_mb mb_tcs))
322          2 (equals <+> ppr dfun_id)
323     where
324       ppr_mb Nothing   = dot
325       ppr_mb (Just tc) = ppr tc
326 \end{code}
327
328
329 ----------------------------- Printing IfaceExpr ------------------------------------
330
331 \begin{code}
332 instance Outputable IfaceExpr where
333     ppr e = pprIfaceExpr noParens e
334
335 pprIfaceExpr :: (SDoc -> SDoc) -> IfaceExpr -> SDoc
336         -- The function adds parens in context that need
337         -- an atomic value (e.g. function args)
338
339 pprIfaceExpr add_par (IfaceLcl v)       = ppr v
340 pprIfaceExpr add_par (IfaceExt v)       = ppr v
341 pprIfaceExpr add_par (IfaceLit l)       = ppr l
342 pprIfaceExpr add_par (IfaceFCall cc ty) = braces (ppr cc <+> ppr ty)
343 pprIfaceExpr add_par (IfaceType ty)     = char '@' <+> pprParendIfaceType ty
344
345 pprIfaceExpr add_par app@(IfaceApp _ _) = add_par (pprIfaceApp app [])
346 pprIfaceExpr add_par (IfaceTuple c as)  = tupleParens c (interpp'SP as)
347
348 pprIfaceExpr add_par e@(IfaceLam _ _)   
349   = add_par (sep [char '\\' <+> sep (map ppr bndrs) <+> arrow,
350                   pprIfaceExpr noParens body])
351   where 
352     (bndrs,body) = collect [] e
353     collect bs (IfaceLam b e) = collect (b:bs) e
354     collect bs e              = (reverse bs, e)
355
356 -- gaw 2004 
357 pprIfaceExpr add_par (IfaceCase scrut bndr ty [(con, bs, rhs)])
358 -- gaw 2004
359   = add_par (sep [ptext SLIT("case") <+> char '@' <+> pprParendIfaceType ty <+> pprIfaceExpr noParens scrut <+> ptext SLIT("of") 
360                         <+> ppr bndr <+> char '{' <+> ppr_con_bs con bs <+> arrow,
361                   pprIfaceExpr noParens rhs <+> char '}'])
362
363 -- gaw 2004
364 pprIfaceExpr add_par (IfaceCase scrut bndr ty alts)
365 -- gaw 2004
366   = add_par (sep [ptext SLIT("case") <+> char '@' <+> pprParendIfaceType ty <+> pprIfaceExpr noParens scrut <+> ptext SLIT("of") 
367                         <+> ppr bndr <+> char '{',
368                   nest 2 (sep (map ppr_alt alts)) <+> char '}'])
369
370 pprIfaceExpr add_par (IfaceCast expr co) = add_par (ptext SLIT("cast") <+> ppr expr <+> ppr co)
371
372 pprIfaceExpr add_par (IfaceLet (IfaceNonRec b rhs) body)
373   = add_par (sep [ptext SLIT("let {"), 
374                   nest 2 (ppr_bind (b, rhs)),
375                   ptext SLIT("} in"), 
376                   pprIfaceExpr noParens body])
377
378 pprIfaceExpr add_par (IfaceLet (IfaceRec pairs) body)
379   = add_par (sep [ptext SLIT("letrec {"),
380                   nest 2 (sep (map ppr_bind pairs)), 
381                   ptext SLIT("} in"),
382                   pprIfaceExpr noParens body])
383
384 pprIfaceExpr add_par (IfaceNote note body) = add_par (ppr note <+> pprIfaceExpr parens body)
385
386 ppr_alt (con, bs, rhs) = sep [ppr_con_bs con bs, 
387                               arrow <+> pprIfaceExpr noParens rhs]
388
389 ppr_con_bs (IfaceTupleAlt tup_con) bs = tupleParens tup_con (interpp'SP bs)
390 ppr_con_bs con bs                     = ppr con <+> hsep (map ppr bs)
391   
392 ppr_bind ((b,ty),rhs) = sep [ppr b <+> dcolon <+> ppr ty, 
393                              equals <+> pprIfaceExpr noParens rhs]
394
395 ------------------
396 pprIfaceApp (IfaceApp fun arg) args = pprIfaceApp fun (nest 2 (pprIfaceExpr parens arg) : args)
397 pprIfaceApp fun                args = sep (pprIfaceExpr parens fun : args)
398
399 ------------------
400 instance Outputable IfaceNote where
401     ppr (IfaceSCC cc)     = pprCostCentreCore cc
402     ppr IfaceInlineMe     = ptext SLIT("__inline_me")
403     ppr (IfaceCoreNote s) = ptext SLIT("__core_note") <+> pprHsString (mkFastString s)
404
405 instance Outputable IfaceConAlt where
406     ppr IfaceDefault      = text "DEFAULT"
407     ppr (IfaceLitAlt l)   = ppr l
408     ppr (IfaceDataAlt d)  = ppr d
409     ppr (IfaceTupleAlt b) = panic "ppr IfaceConAlt" 
410         -- IfaceTupleAlt is handled by the case-alternative printer
411
412 ------------------
413 instance Outputable IfaceIdInfo where
414    ppr NoInfo       = empty
415    ppr (HasInfo is) = ptext SLIT("{-") <+> fsep (map ppr_hs_info is) <+> ptext SLIT("-}")
416
417 ppr_hs_info (HsUnfold unf)      = ptext SLIT("Unfolding:") <+>
418                                         parens (pprIfaceExpr noParens unf)
419 ppr_hs_info (HsInline act)      = ptext SLIT("Inline:") <+> ppr act
420 ppr_hs_info (HsArity arity)     = ptext SLIT("Arity:") <+> int arity
421 ppr_hs_info (HsStrictness str)  = ptext SLIT("Strictness:") <+> pprIfaceStrictSig str
422 ppr_hs_info HsNoCafRefs         = ptext SLIT("HasNoCafRefs")
423 ppr_hs_info (HsWorker w a)      = ptext SLIT("Worker:") <+> ppr w <+> int a
424 \end{code}
425
426
427 %************************************************************************
428 %*                                                                      *
429         Equality, for interface file version generaion only
430 %*                                                                      *
431 %************************************************************************
432
433 Equality over IfaceSyn returns an IfaceEq, not a Bool.  The new constructor is
434 EqBut, which gives the set of *locally-defined* things whose version must be equal
435 for the whole thing to be equal.  So the key function is eqIfExt, which compares
436 IfaceExtNames.
437
438 Of course, equality is also done modulo alpha conversion.
439
440 \begin{code}
441 data IfaceEq 
442   = Equal               -- Definitely exactly the same
443   | NotEqual            -- Definitely different
444   | EqBut OccSet        -- The same provided these local things have not changed
445
446 bool :: Bool -> IfaceEq
447 bool True  = Equal
448 bool False = NotEqual
449
450 toBool :: IfaceEq -> Bool
451 toBool Equal     = True
452 toBool (EqBut _) = True
453 toBool NotEqual  = False
454
455 zapEq :: IfaceEq -> IfaceEq     -- Used to forget EqBut information
456 zapEq (EqBut _) = Equal
457 zapEq other     = other
458
459 (&&&) :: IfaceEq -> IfaceEq -> IfaceEq
460 Equal       &&& x           = x
461 NotEqual    &&& x           = NotEqual
462 EqBut occs  &&& Equal       = EqBut occs
463 EqBut occs  &&& NotEqual    = NotEqual
464 EqBut occs1 &&& EqBut occs2 = EqBut (occs1 `unionOccSets` occs2)
465
466 ---------------------
467 eqIfExt :: IfaceExtName -> IfaceExtName -> IfaceEq
468 -- This function is the core of the EqBut stuff
469 eqIfExt (ExtPkg mod1 occ1)     (ExtPkg mod2 occ2)     = bool (mod1==mod2 && occ1==occ2)
470 eqIfExt (HomePkg mod1 occ1 v1) (HomePkg mod2 occ2 v2) = bool (mod1==mod2 && occ1==occ2 && v1==v2)
471 eqIfExt (LocalTop occ1)       (LocalTop occ2)      | occ1 == occ2 = EqBut (unitOccSet occ1)
472 eqIfExt (LocalTopSub occ1 p1) (LocalTop occ2)      | occ1 == occ2 = EqBut (unitOccSet p1)
473 eqIfExt (LocalTopSub occ1 p1) (LocalTopSub occ2 _) | occ1 == occ2 = EqBut (unitOccSet p1)
474 eqIfExt n1 n2 = NotEqual
475 \end{code}
476
477
478 \begin{code}
479 ---------------------
480 checkBootDecl :: IfaceDecl      -- The boot decl
481               -> IfaceDecl      -- The real decl
482               -> Bool           -- True <=> compatible
483 checkBootDecl (IfaceId s1 t1 _) (IfaceId s2 t2 _)
484   = ASSERT( s1==s2 ) toBool (t1 `eqIfType` t2)
485
486 checkBootDecl d1@(IfaceForeign {}) d2@(IfaceForeign {})
487   = ASSERT (ifName d1 == ifName d2 ) ifExtName d1 == ifExtName d2
488
489 checkBootDecl d1@(IfaceSyn {}) d2@(IfaceSyn {})
490   = ASSERT( ifName d1 == ifName d2 )
491     toBool $ eqWith (ifTyVars d1) (ifTyVars d2) $ \ env -> 
492           eq_ifType env (ifSynRhs d1) (ifSynRhs d2)
493
494 checkBootDecl d1@(IfaceData {}) d2@(IfaceData {})
495 -- We don't check the recursion flags because the boot-one is
496 -- recursive, to be conservative, but the real one may not be.
497 -- I'm not happy with the way recursive flags are dealt with.
498   = ASSERT( ifName d1    == ifName d2 ) 
499     toBool $ eqWith (ifTyVars d1) (ifTyVars d2) $ \ env -> 
500         eq_ifContext env (ifCtxt d1) (ifCtxt d2) &&& 
501         case ifCons d1 of
502             IfAbstractTyCon -> Equal
503             cons1           -> eq_hsCD env cons1 (ifCons d2)
504
505 checkBootDecl d1@(IfaceClass {}) d2@(IfaceClass {})
506   = ASSERT( ifName d1 == ifName d2 )
507     toBool $ eqWith (ifTyVars d1) (ifTyVars d2) $ \ env -> 
508           eqListBy (eq_hsFD env)    (ifFDs d1)  (ifFDs d2) &&&
509           case (ifCtxt d1, ifSigs d1) of
510              ([], [])      -> Equal
511              (cxt1, sigs1) -> eq_ifContext env cxt1 (ifCtxt d2)  &&&
512                               eqListBy (eq_cls_sig env) sigs1 (ifSigs d2)
513
514 checkBootDecl _ _ = False       -- default case
515
516 ---------------------
517 eqIfDecl :: IfaceDecl -> IfaceDecl -> IfaceEq
518 eqIfDecl (IfaceId s1 t1 i1) (IfaceId s2 t2 i2)
519   = bool (s1 == s2) &&& (t1 `eqIfType` t2) &&& (i1 `eqIfIdInfo` i2)
520
521 eqIfDecl d1@(IfaceForeign {}) d2@(IfaceForeign {})
522   = bool (ifName d1 == ifName d2 && ifExtName d1 == ifExtName d2)
523
524 eqIfDecl d1@(IfaceData {}) d2@(IfaceData {})
525   = bool (ifName d1    == ifName d2 && 
526           ifRec d1     == ifRec   d2 && 
527           ifGadtSyntax d1 == ifGadtSyntax   d2 && 
528           ifGeneric d1 == ifGeneric d2) &&&
529     eqWith (ifTyVars d1) (ifTyVars d2) (\ env -> 
530             eq_ifContext env (ifCtxt d1) (ifCtxt d2) &&& 
531             eq_hsCD env (ifCons d1) (ifCons d2) 
532         )
533         -- The type variables of the data type do not scope
534         -- over the constructors (any more), but they do scope
535         -- over the stupid context in the IfaceConDecls
536
537 eqIfDecl d1@(IfaceSyn {}) d2@(IfaceSyn {})
538   = bool (ifName d1 == ifName d2) &&&
539     eqWith (ifTyVars d1) (ifTyVars d2) (\ env -> 
540           eq_ifType env (ifSynRhs d1) (ifSynRhs d2)
541         )
542
543 eqIfDecl d1@(IfaceClass {}) d2@(IfaceClass {})
544   = bool (ifName d1 == ifName d2 && 
545           ifRec d1  == ifRec  d2) &&&
546     eqWith (ifTyVars d1) (ifTyVars d2) (\ env -> 
547           eq_ifContext env (ifCtxt d1) (ifCtxt d2)  &&&
548           eqListBy (eq_hsFD env)    (ifFDs d1)  (ifFDs d2) &&&
549           eqListBy (eq_cls_sig env) (ifSigs d1) (ifSigs d2)
550        )
551
552 eqIfDecl _ _ = NotEqual -- default case
553
554 -- Helper
555 eqWith :: [IfaceTvBndr] -> [IfaceTvBndr] -> (EqEnv -> IfaceEq) -> IfaceEq
556 eqWith = eq_ifTvBndrs emptyEqEnv
557
558 -----------------------
559 eqIfInst d1 d2 = bool (ifDFun d1 == ifDFun d2 && ifOFlag d1 == ifOFlag d2)
560 -- All other changes are handled via the version info on the dfun
561
562 eqIfRule (IfaceRule n1 a1 bs1 f1 es1 rhs1 o1)
563          (IfaceRule n2 a2 bs2 f2 es2 rhs2 o2)
564        = bool (n1==n2 && a1==a2 && o1 == o2) &&&
565          f1 `eqIfExt` f2 &&&
566          eq_ifBndrs emptyEqEnv bs1 bs2 (\env -> 
567          zapEq (eqListBy (eq_ifaceExpr env) es1 es2) &&&
568                 -- zapEq: for the LHSs, ignore the EqBut part
569          eq_ifaceExpr env rhs1 rhs2)
570
571 eq_hsCD env (IfDataTyCon c1) (IfDataTyCon c2) 
572   = eqListBy (eq_ConDecl env) c1 c2
573
574 eq_hsCD env (IfNewTyCon c1)  (IfNewTyCon c2)  = eq_ConDecl env c1 c2
575 eq_hsCD env IfAbstractTyCon  IfAbstractTyCon  = Equal
576 eq_hsCD env IfOpenDataTyCon  IfOpenDataTyCon  = Equal
577 eq_hsCD env IfOpenNewTyCon   IfOpenNewTyCon   = Equal
578 eq_hsCD env d1               d2               = NotEqual
579
580 eq_ConDecl env c1 c2
581   = bool (ifConOcc c1     == ifConOcc c2 && 
582           ifConInfix c1   == ifConInfix c2 && 
583           ifConStricts c1 == ifConStricts c2 && 
584           ifConFields c1  == ifConFields c2) &&&
585     eq_ifTvBndrs env (ifConUnivTvs c1) (ifConUnivTvs c2) (\ env ->
586     eq_ifTvBndrs env (ifConExTvs c1) (ifConExTvs c2) (\ env ->
587         eq_ifContext env (ifConCtxt c1) (ifConCtxt c2) &&&
588         eq_ifTypes env (ifConArgTys c1) (ifConArgTys c2)))
589
590 eq_hsFD env (ns1,ms1) (ns2,ms2)
591   = eqListBy (eqIfOcc env) ns1 ns2 &&& eqListBy (eqIfOcc env) ms1 ms2
592
593 eq_cls_sig env (IfaceClassOp n1 dm1 ty1) (IfaceClassOp n2 dm2 ty2)
594   = bool (n1==n2 && dm1 == dm2) &&& eq_ifType env ty1 ty2
595 \end{code}
596
597
598 \begin{code}
599 -----------------
600 eqIfIdInfo NoInfo        NoInfo        = Equal
601 eqIfIdInfo (HasInfo is1) (HasInfo is2) = eqListBy eq_item is1 is2
602 eqIfIdInfo i1            i2 = NotEqual
603
604 eq_item (HsInline a1)      (HsInline a2)      = bool (a1 == a2)
605 eq_item (HsArity a1)       (HsArity a2)       = bool (a1 == a2)
606 eq_item (HsStrictness s1)  (HsStrictness s2)  = bool (s1 == s2)
607 eq_item (HsUnfold u1)   (HsUnfold u2)         = eq_ifaceExpr emptyEqEnv u1 u2
608 eq_item HsNoCafRefs        HsNoCafRefs        = Equal
609 eq_item (HsWorker wkr1 a1) (HsWorker wkr2 a2) = bool (a1==a2) &&& (wkr1 `eqIfExt` wkr2)
610 eq_item _ _ = NotEqual
611
612 -----------------
613 eq_ifaceExpr :: EqEnv -> IfaceExpr -> IfaceExpr -> IfaceEq
614 eq_ifaceExpr env (IfaceLcl v1)        (IfaceLcl v2)        = eqIfOcc env v1 v2
615 eq_ifaceExpr env (IfaceExt v1)        (IfaceExt v2)        = eqIfExt v1 v2
616 eq_ifaceExpr env (IfaceLit l1)        (IfaceLit l2)        = bool (l1 == l2)
617 eq_ifaceExpr env (IfaceFCall c1 ty1)  (IfaceFCall c2 ty2)  = bool (c1==c2) &&& eq_ifType env ty1 ty2
618 eq_ifaceExpr env (IfaceType ty1)      (IfaceType ty2)      = eq_ifType env ty1 ty2
619 eq_ifaceExpr env (IfaceTuple n1 as1)  (IfaceTuple n2 as2)  = bool (n1==n2) &&& eqListBy (eq_ifaceExpr env) as1 as2
620 eq_ifaceExpr env (IfaceLam b1 body1)  (IfaceLam b2 body2)  = eq_ifBndr env b1 b2 (\env -> eq_ifaceExpr env body1 body2)
621 eq_ifaceExpr env (IfaceApp f1 a1)     (IfaceApp f2 a2)     = eq_ifaceExpr env f1 f2 &&& eq_ifaceExpr env a1 a2
622 eq_ifaceExpr env (IfaceCast e1 co1)   (IfaceCast e2 co2)   = eq_ifaceExpr env e1 e2 &&& eq_ifType env co1 co2
623 eq_ifaceExpr env (IfaceNote n1 r1)    (IfaceNote n2 r2)    = eq_ifaceNote env n1 n2 &&& eq_ifaceExpr env r1 r2
624
625 eq_ifaceExpr env (IfaceCase s1 b1 ty1 as1) (IfaceCase s2 b2 ty2 as2)
626   = eq_ifaceExpr env s1 s2 &&&
627     eq_ifType env ty1 ty2 &&&
628     eq_ifNakedBndr env b1 b2 (\env -> eqListBy (eq_ifaceAlt env) as1 as2)
629   where
630     eq_ifaceAlt env (c1,bs1,r1) (c2,bs2,r2)
631         = bool (eq_ifaceConAlt c1 c2) &&& 
632           eq_ifNakedBndrs env bs1 bs2 (\env -> eq_ifaceExpr env r1 r2)
633
634 eq_ifaceExpr env (IfaceLet (IfaceNonRec b1 r1) x1) (IfaceLet (IfaceNonRec b2 r2) x2)
635   = eq_ifaceExpr env r1 r2 &&& eq_ifIdBndr env b1 b2 (\env -> eq_ifaceExpr env x1 x2)
636
637 eq_ifaceExpr env (IfaceLet (IfaceRec as1) x1) (IfaceLet (IfaceRec as2) x2)
638   = eq_ifIdBndrs env bs1 bs2 (\env -> eqListBy (eq_ifaceExpr env) rs1 rs2 &&& eq_ifaceExpr env x1 x2)
639   where
640     (bs1,rs1) = unzip as1
641     (bs2,rs2) = unzip as2
642
643
644 eq_ifaceExpr env _ _ = NotEqual
645
646 -----------------
647 eq_ifaceConAlt :: IfaceConAlt -> IfaceConAlt -> Bool
648 eq_ifaceConAlt IfaceDefault       IfaceDefault          = True
649 eq_ifaceConAlt (IfaceDataAlt n1)  (IfaceDataAlt n2)     = n1==n2
650 eq_ifaceConAlt (IfaceTupleAlt c1) (IfaceTupleAlt c2)    = c1==c2
651 eq_ifaceConAlt (IfaceLitAlt l1)   (IfaceLitAlt l2)      = l1==l2
652 eq_ifaceConAlt _ _ = False
653
654 -----------------
655 eq_ifaceNote :: EqEnv -> IfaceNote -> IfaceNote -> IfaceEq
656 eq_ifaceNote env (IfaceSCC c1)    (IfaceSCC c2)        = bool (c1==c2)
657 eq_ifaceNote env IfaceInlineMe    IfaceInlineMe        = Equal
658 eq_ifaceNote env (IfaceCoreNote s1) (IfaceCoreNote s2) = bool (s1==s2)
659 eq_ifaceNote env _ _ = NotEqual
660 \end{code}
661
662 \begin{code}
663 ---------------------
664 eqIfType t1 t2 = eq_ifType emptyEqEnv t1 t2
665
666 -------------------
667 eq_ifType env (IfaceTyVar n1)         (IfaceTyVar n2)         = eqIfOcc env n1 n2
668 eq_ifType env (IfaceAppTy s1 t1)      (IfaceAppTy s2 t2)      = eq_ifType env s1 s2 &&& eq_ifType env t1 t2
669 eq_ifType env (IfacePredTy st1)       (IfacePredTy st2)       = eq_ifPredType env st1 st2
670 eq_ifType env (IfaceTyConApp tc1 ts1) (IfaceTyConApp tc2 ts2) = tc1 `eqIfTc` tc2 &&& eq_ifTypes env ts1 ts2
671 eq_ifType env (IfaceForAllTy tv1 t1)  (IfaceForAllTy tv2 t2)  = eq_ifTvBndr env tv1 tv2 (\env -> eq_ifType env t1 t2)
672 eq_ifType env (IfaceFunTy s1 t1)      (IfaceFunTy s2 t2)      = eq_ifType env s1 s2 &&& eq_ifType env t1 t2
673 eq_ifType env _ _ = NotEqual
674
675 -------------------
676 eq_ifTypes env = eqListBy (eq_ifType env)
677
678 -------------------
679 eq_ifContext env a b = eqListBy (eq_ifPredType env) a b
680
681 -------------------
682 eq_ifPredType env (IfaceClassP c1 tys1) (IfaceClassP c2 tys2) = c1 `eqIfExt` c2 &&&  eq_ifTypes env tys1 tys2
683 eq_ifPredType env (IfaceIParam n1 ty1) (IfaceIParam n2 ty2)   = bool (n1 == n2) &&& eq_ifType env ty1 ty2
684 eq_ifPredType env _ _ = NotEqual
685
686 -------------------
687 eqIfTc (IfaceTc tc1) (IfaceTc tc2) = tc1 `eqIfExt` tc2
688 eqIfTc IfaceIntTc    IfaceIntTc    = Equal
689 eqIfTc IfaceCharTc   IfaceCharTc   = Equal
690 eqIfTc IfaceBoolTc   IfaceBoolTc   = Equal
691 eqIfTc IfaceListTc   IfaceListTc   = Equal
692 eqIfTc IfacePArrTc   IfacePArrTc   = Equal
693 eqIfTc (IfaceTupTc bx1 ar1) (IfaceTupTc bx2 ar2) = bool (bx1==bx2 && ar1==ar2)
694 eqIfTc _ _ = NotEqual
695 \end{code}
696
697 -----------------------------------------------------------
698         Support code for equality checking
699 -----------------------------------------------------------
700
701 \begin{code}
702 ------------------------------------
703 type EqEnv = UniqFM FastString  -- Tracks the mapping from L-variables to R-variables
704
705 eqIfOcc :: EqEnv -> FastString -> FastString -> IfaceEq
706 eqIfOcc env n1 n2 = case lookupUFM env n1 of
707                         Just n1 -> bool (n1 == n2)
708                         Nothing -> bool (n1 == n2)
709
710 extendEqEnv :: EqEnv -> FastString -> FastString -> EqEnv
711 extendEqEnv env n1 n2 | n1 == n2  = env
712                       | otherwise = addToUFM env n1 n2
713
714 emptyEqEnv :: EqEnv
715 emptyEqEnv = emptyUFM
716
717 ------------------------------------
718 type ExtEnv bndr = EqEnv -> bndr -> bndr -> (EqEnv -> IfaceEq) -> IfaceEq
719
720 eq_ifNakedBndr :: ExtEnv FastString
721 eq_ifBndr      :: ExtEnv IfaceBndr
722 eq_ifTvBndr    :: ExtEnv IfaceTvBndr
723 eq_ifIdBndr    :: ExtEnv IfaceIdBndr
724
725 eq_ifNakedBndr env n1 n2 k = k (extendEqEnv env n1 n2)
726
727 eq_ifBndr env (IfaceIdBndr b1) (IfaceIdBndr b2) k = eq_ifIdBndr env b1 b2 k
728 eq_ifBndr env (IfaceTvBndr b1) (IfaceTvBndr b2) k = eq_ifTvBndr env b1 b2 k
729 eq_ifBndr _ _ _ _ = NotEqual
730
731 eq_ifTvBndr env (v1, k1) (v2, k2) k = eq_ifType env k1 k2 &&& k (extendEqEnv env v1 v2)
732 eq_ifIdBndr env (v1, t1) (v2, t2) k = eq_ifType env t1 t2 &&& k (extendEqEnv env v1 v2)
733
734 eq_ifBndrs      :: ExtEnv [IfaceBndr]
735 eq_ifIdBndrs    :: ExtEnv [IfaceIdBndr]
736 eq_ifTvBndrs    :: ExtEnv [IfaceTvBndr]
737 eq_ifNakedBndrs :: ExtEnv [FastString]
738 eq_ifBndrs      = eq_bndrs_with eq_ifBndr
739 eq_ifIdBndrs    = eq_bndrs_with eq_ifIdBndr
740 eq_ifTvBndrs    = eq_bndrs_with eq_ifTvBndr
741 eq_ifNakedBndrs = eq_bndrs_with eq_ifNakedBndr
742
743 eq_bndrs_with eq env []       []       k = k env
744 eq_bndrs_with eq env (b1:bs1) (b2:bs2) k = eq env b1 b2 (\env -> eq_bndrs_with eq env bs1 bs2 k)
745 eq_bndrs_with eq env _        _        _ = NotEqual
746 \end{code}
747
748 \begin{code}
749 eqListBy :: (a->a->IfaceEq) -> [a] -> [a] -> IfaceEq
750 eqListBy eq []     []     = Equal
751 eqListBy eq (x:xs) (y:ys) = eq x y &&& eqListBy eq xs ys
752 eqListBy eq xs     ys     = NotEqual
753
754 eqMaybeBy :: (a->a->IfaceEq) -> Maybe a -> Maybe a -> IfaceEq
755 eqMaybeBy eq Nothing Nothing   = Equal
756 eqMaybeBy eq (Just x) (Just y) = eq x y
757 eqMaybeBy eq x        y        = NotEqual
758 \end{code}