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