remove empty dir
[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         -- Converting things to IfaceSyn
26         tyThingToIfaceDecl, instanceToIfaceInst, coreRuleToIfaceRule, 
27
28         -- Equality
29         IfaceEq(..), (&&&), bool, eqListBy, eqMaybeBy,
30         eqIfDecl, eqIfInst, eqIfRule, 
31         
32         -- Pretty printing
33         pprIfaceExpr, pprIfaceDecl, pprIfaceDeclHead 
34     ) where
35
36 #include "HsVersions.h"
37
38 import CoreSyn
39 import IfaceType
40
41 import FunDeps          ( pprFundeps )
42 import NewDemand        ( StrictSig, pprIfaceStrictSig )
43 import TcType           ( deNoteType )
44 import Type             ( TyThing(..), splitForAllTys, funResultTy )
45 import InstEnv          ( Instance(..), OverlapFlag )
46 import Id               ( Id, idName, idType, idInfo, idArity, isDataConWorkId_maybe, isFCallId_maybe )
47 import NewDemand        ( isTopSig )
48 import IdInfo           ( IdInfo, CafInfo(..), WorkerInfo(..), 
49                           arityInfo, cafInfo, newStrictnessInfo, 
50                           workerInfo, unfoldingInfo, inlinePragInfo )
51 import TyCon            ( TyCon, ArgVrcs, AlgTyConRhs(..), isRecursiveTyCon, isForeignTyCon,
52                           isSynTyCon, isAlgTyCon, isPrimTyCon, isFunTyCon,
53                           isTupleTyCon, tupleTyConBoxity, tyConStupidTheta,
54                           tyConHasGenerics, tyConArgVrcs, synTyConRhs,
55                           tyConArity, tyConTyVars, algTyConRhs, tyConExtName  )
56 import DataCon          ( dataConName, dataConSig, dataConFieldLabels, dataConStrictMarks,
57                           dataConTyCon, dataConIsInfix, isVanillaDataCon )
58 import Class            ( FunDep, DefMeth, classExtraBigSig, classTyCon )
59 import OccName          ( OccName, OccEnv, emptyOccEnv, 
60                           lookupOccEnv, extendOccEnv, parenSymOcc,
61                           OccSet, unionOccSets, unitOccSet )
62 import Name             ( Name, NamedThing(..), nameOccName, isExternalName )
63 import CostCentre       ( CostCentre, pprCostCentreCore )
64 import Literal          ( Literal )
65 import ForeignCall      ( ForeignCall )
66 import TysPrim          ( alphaTyVars )
67 import BasicTypes       ( Arity, Activation(..), StrictnessMark, 
68                           RecFlag(..), boolToRecFlag, Boxity(..), 
69                           tupleParens )
70 import Outputable
71 import FastString
72 import Maybes           ( catMaybes )
73 import Util             ( lengthIs )
74
75 infixl 3 &&&
76 infix  4 `eqIfExt`, `eqIfIdInfo`, `eqIfType`
77 \end{code}
78
79
80 %************************************************************************
81 %*                                                                      *
82                 Data type declarations
83 %*                                                                      *
84 %************************************************************************
85
86 \begin{code}
87 data IfaceDecl 
88   = IfaceId { ifName   :: OccName,
89               ifType   :: IfaceType, 
90               ifIdInfo :: IfaceIdInfo }
91
92   | IfaceData { ifName     :: OccName,          -- Type constructor
93                 ifTyVars   :: [IfaceTvBndr],    -- Type variables
94                 ifCtxt     :: IfaceContext,     -- The "stupid theta"
95                 ifCons     :: IfaceConDecls,    -- Includes new/data info
96                 ifRec      :: RecFlag,          -- Recursive or not?
97                 ifVrcs     :: ArgVrcs,
98                 ifGeneric  :: Bool              -- True <=> generic converter functions available
99     }                                           -- We need this for imported data decls, since the
100                                                 -- imported modules may have been compiled with
101                                                 -- different flags to the current compilation unit
102
103   | IfaceSyn  { ifName   :: OccName,            -- Type constructor
104                 ifTyVars :: [IfaceTvBndr],      -- Type variables
105                 ifVrcs   :: ArgVrcs,
106                 ifSynRhs :: IfaceType           -- synonym expansion
107     }
108
109   | IfaceClass { ifCtxt    :: IfaceContext,     -- Context...
110                  ifName    :: OccName,          -- Name of the class
111                  ifTyVars  :: [IfaceTvBndr],    -- Type variables
112                  ifFDs     :: [FunDep OccName], -- Functional dependencies
113                  ifSigs    :: [IfaceClassOp],   -- Method signatures
114                  ifRec     :: RecFlag,          -- Is newtype/datatype associated with the class recursive?
115                  ifVrcs    :: ArgVrcs           -- ... and what are its argument variances ...
116     }
117
118   | IfaceForeign { ifName :: OccName,           -- Needs expanding when we move beyond .NET
119                    ifExtName :: Maybe FastString }
120
121 data IfaceClassOp = IfaceClassOp OccName DefMeth IfaceType
122         -- Nothing    => no default method
123         -- Just False => ordinary polymorphic default method
124         -- Just True  => generic default method
125
126 data IfaceConDecls
127   = IfAbstractTyCon             -- No info
128   | IfDataTyCon [IfaceConDecl]  -- data type decls
129   | IfNewTyCon  IfaceConDecl    -- newtype decls
130
131 visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl]
132 visibleIfConDecls IfAbstractTyCon  = []
133 visibleIfConDecls (IfDataTyCon cs) = cs
134 visibleIfConDecls (IfNewTyCon c)   = [c]
135
136 data IfaceConDecl 
137   = IfVanillaCon {
138         ifConOcc     :: OccName,                -- Constructor name
139         ifConInfix   :: Bool,                   -- True <=> declared infix
140         ifConArgTys  :: [IfaceType],            -- Arg types
141         ifConStricts :: [StrictnessMark],       -- Empty (meaning all lazy), or 1-1 corresp with arg types
142         ifConFields  :: [OccName] }             -- ...ditto... (field labels)
143   | IfGadtCon {
144         ifConOcc     :: OccName,                -- Constructor name
145         ifConTyVars  :: [IfaceTvBndr],          -- All tyvars
146         ifConCtxt    :: IfaceContext,           -- Non-stupid context
147         ifConArgTys  :: [IfaceType],            -- Arg types
148         ifConResTys  :: [IfaceType],            -- Result type args
149         ifConStricts :: [StrictnessMark] }      -- Empty (meaning all lazy), or 1-1 corresp with arg types
150                         
151 data IfaceInst 
152   = IfaceInst { ifInstCls  :: IfaceExtName,             -- See comments with
153                 ifInstTys  :: [Maybe IfaceTyCon],       -- the defn of Instance
154                 ifDFun     :: OccName,                  -- The dfun
155                 ifOFlag    :: OverlapFlag,              -- Overlap flag
156                 ifInstOrph :: Maybe OccName }           -- See is_orph in defn of Instance
157         -- There's always a separate IfaceDecl for the DFun, which gives 
158         -- its IdInfo with its full type and version number.
159         -- The instance declarations taken together have a version number,
160         -- and we don't want that to wobble gratuitously
161         -- If this instance decl is *used*, we'll record a usage on the dfun;
162         -- and if the head does not change it won't be used if it wasn't before
163
164 data IfaceRule
165   = IfaceRule { 
166         ifRuleName   :: RuleName,
167         ifActivation :: Activation,
168         ifRuleBndrs  :: [IfaceBndr],    -- Tyvars and term vars
169         ifRuleHead   :: IfaceExtName,   -- Head of lhs
170         ifRuleArgs   :: [IfaceExpr],    -- Args of LHS
171         ifRuleRhs    :: IfaceExpr,
172         ifRuleOrph   :: Maybe OccName   -- Just like IfaceInst
173     }
174
175 data IfaceIdInfo
176   = NoInfo                      -- When writing interface file without -O
177   | HasInfo [IfaceInfoItem]     -- Has info, and here it is
178
179 -- Here's a tricky case:
180 --   * Compile with -O module A, and B which imports A.f
181 --   * Change function f in A, and recompile without -O
182 --   * When we read in old A.hi we read in its IdInfo (as a thunk)
183 --      (In earlier GHCs we used to drop IdInfo immediately on reading,
184 --       but we do not do that now.  Instead it's discarded when the
185 --       ModIface is read into the various decl pools.)
186 --   * The version comparsion sees that new (=NoInfo) differs from old (=HasInfo *)
187 --      and so gives a new version.
188
189 data IfaceInfoItem
190   = HsArity      Arity
191   | HsStrictness StrictSig
192   | HsUnfold     Activation IfaceExpr
193   | HsNoCafRefs
194   | HsWorker     IfaceExtName Arity     -- Worker, if any see IdInfo.WorkerInfo
195                                         -- for why we want arity here.
196         -- NB: we need IfaceExtName (not just OccName) because the worker
197         --     can simplify to a function in another module.
198 -- NB: Specialisations and rules come in separately and are
199 -- only later attached to the Id.  Partial reason: some are orphans.
200
201 --------------------------------
202 data IfaceExpr
203   = IfaceLcl    OccName
204   | IfaceExt    IfaceExtName
205   | IfaceType   IfaceType
206   | IfaceTuple  Boxity [IfaceExpr]              -- Saturated; type arguments omitted
207   | IfaceLam    IfaceBndr IfaceExpr
208   | IfaceApp    IfaceExpr IfaceExpr
209   | IfaceCase   IfaceExpr OccName IfaceType [IfaceAlt]
210   | IfaceLet    IfaceBinding  IfaceExpr
211   | IfaceNote   IfaceNote IfaceExpr
212   | IfaceLit    Literal
213   | IfaceFCall  ForeignCall IfaceType
214
215 data IfaceNote = IfaceSCC CostCentre
216                | IfaceCoerce IfaceType
217                | IfaceInlineCall
218                | IfaceInlineMe
219                | IfaceCoreNote String
220
221 type IfaceAlt = (IfaceConAlt, [OccName], IfaceExpr)
222         -- Note: OccName, not IfaceBndr (and same with the case binder)
223         -- We reconstruct the kind/type of the thing from the context
224         -- thus saving bulk in interface files
225
226 data IfaceConAlt = IfaceDefault
227                  | IfaceDataAlt OccName
228                  | IfaceTupleAlt Boxity
229                  | IfaceLitAlt Literal
230
231 data IfaceBinding
232   = IfaceNonRec IfaceIdBndr IfaceExpr
233   | IfaceRec    [(IfaceIdBndr, IfaceExpr)]
234 \end{code}
235
236
237 %************************************************************************
238 %*                                                                      *
239 \subsection[HsCore-print]{Printing Core unfoldings}
240 %*                                                                      *
241 %************************************************************************
242
243 ----------------------------- Printing IfaceDecl ------------------------------------
244
245 \begin{code}
246 instance Outputable IfaceDecl where
247   ppr = pprIfaceDecl
248
249 pprIfaceDecl (IfaceId {ifName = var, ifType = ty, ifIdInfo = info})
250   = sep [ ppr var <+> dcolon <+> ppr ty, 
251           nest 2 (ppr info) ]
252
253 pprIfaceDecl (IfaceForeign {ifName = tycon})
254   = hsep [ptext SLIT("foreign import type dotnet"), ppr tycon]
255
256 pprIfaceDecl (IfaceSyn {ifName = tycon, ifTyVars = tyvars, ifSynRhs = mono_ty, ifVrcs = vrcs})
257   = hang (ptext SLIT("type") <+> pprIfaceDeclHead [] tycon tyvars)
258        4 (vcat [equals <+> ppr mono_ty,
259                 pprVrcs vrcs])
260
261 pprIfaceDecl (IfaceData {ifName = tycon, ifGeneric = gen, ifCtxt = context,
262                          ifTyVars = tyvars, ifCons = condecls, 
263                          ifRec = isrec, ifVrcs = vrcs})
264   = hang (pp_nd <+> pprIfaceDeclHead context tycon tyvars)
265        4 (vcat [pprVrcs vrcs, pprRec isrec, pprGen gen, pp_condecls tycon condecls])
266   where
267     pp_nd = case condecls of
268                 IfAbstractTyCon -> ptext SLIT("data")
269                 IfDataTyCon _   -> ptext SLIT("data")
270                 IfNewTyCon _    -> ptext SLIT("newtype")
271
272 pprIfaceDecl (IfaceClass {ifCtxt = context, ifName = clas, ifTyVars = tyvars, 
273                           ifFDs = fds, ifSigs = sigs, ifVrcs = vrcs, ifRec = isrec})
274   = hang (ptext SLIT("class") <+> pprIfaceDeclHead context clas tyvars <+> pprFundeps fds)
275        4 (vcat [pprVrcs vrcs, 
276                 pprRec isrec,
277                 sep (map ppr sigs)])
278
279 pprVrcs vrcs = ptext SLIT("Variances") <+> ppr vrcs
280 pprRec isrec = ptext SLIT("RecFlag") <+> ppr isrec
281 pprGen True  = ptext SLIT("Generics: yes")
282 pprGen False = ptext SLIT("Generics: no")
283
284 instance Outputable IfaceClassOp where
285    ppr (IfaceClassOp n dm ty) = ppr n <+> ppr dm <+> dcolon <+> ppr ty
286
287 pprIfaceDeclHead :: IfaceContext -> OccName -> [IfaceTvBndr] -> SDoc
288 pprIfaceDeclHead context thing tyvars 
289   = hsep [pprIfaceContext context, parenSymOcc thing (ppr thing), pprIfaceTvBndrs tyvars]
290
291 pp_condecls tc IfAbstractTyCon  = ptext SLIT("{- abstract -}")
292 pp_condecls tc (IfNewTyCon c)   = equals <+> pprIfaceConDecl tc c
293 pp_condecls tc (IfDataTyCon cs) = equals <+> sep (punctuate (ptext SLIT(" |"))
294                                                      (map (pprIfaceConDecl tc) cs))
295
296 pprIfaceConDecl tc (IfVanillaCon { 
297                       ifConOcc = name, ifConInfix = is_infix, 
298                       ifConArgTys = arg_tys, 
299                       ifConStricts = strs, ifConFields = fields })
300     = sep [ppr name <+> sep (map pprParendIfaceType arg_tys),
301            if is_infix then ptext SLIT("Infix") else empty,
302            if null strs then empty 
303               else nest 4 (ptext SLIT("Stricts:") <+> hsep (map ppr strs)),
304            if null fields then empty
305               else nest 4 (ptext SLIT("Fields:") <+> hsep (map ppr fields))]
306
307 pprIfaceConDecl tc (IfGadtCon { 
308                       ifConOcc = name, 
309                       ifConTyVars = tvs, ifConCtxt = ctxt,
310                       ifConArgTys = arg_tys, ifConResTys = res_tys, 
311                       ifConStricts = strs })
312     = sep [ppr name <+> dcolon <+> pprIfaceForAllPart tvs ctxt (ppr con_tau),
313            if null strs then empty 
314               else nest 4 (ptext SLIT("Stricts:") <+> hsep (map ppr strs))]
315     where
316       con_tau = foldr1 IfaceFunTy (arg_tys ++ [tc_app])
317       tc_app  = IfaceTyConApp (IfaceTc (LocalTop tc)) res_tys   
318         -- Gruesome, but jsut for debug print
319
320 instance Outputable IfaceRule where
321   ppr (IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
322                    ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs }) 
323     = sep [hsep [doubleQuotes (ftext name), ppr act,
324                  ptext SLIT("forall") <+> pprIfaceBndrs bndrs],
325            nest 2 (sep [ppr fn <+> sep (map (pprIfaceExpr parens) args),
326                         ptext SLIT("=") <+> ppr rhs])
327       ]
328
329 instance Outputable IfaceInst where
330   ppr (IfaceInst {ifDFun = dfun_id, ifOFlag = flag, 
331                   ifInstCls = cls, ifInstTys = mb_tcs})
332     = hang (ptext SLIT("instance") <+> ppr flag 
333                 <+> ppr cls <+> brackets (pprWithCommas ppr_mb mb_tcs))
334          2 (equals <+> ppr dfun_id)
335     where
336       ppr_mb Nothing   = dot
337       ppr_mb (Just tc) = ppr tc
338 \end{code}
339
340
341 ----------------------------- Printing IfaceExpr ------------------------------------
342
343 \begin{code}
344 instance Outputable IfaceExpr where
345     ppr e = pprIfaceExpr noParens e
346
347 pprIfaceExpr :: (SDoc -> SDoc) -> IfaceExpr -> SDoc
348         -- The function adds parens in context that need
349         -- an atomic value (e.g. function args)
350
351 pprIfaceExpr add_par (IfaceLcl v)       = ppr v
352 pprIfaceExpr add_par (IfaceExt v)       = ppr v
353 pprIfaceExpr add_par (IfaceLit l)       = ppr l
354 pprIfaceExpr add_par (IfaceFCall cc ty) = braces (ppr cc <+> ppr ty)
355 pprIfaceExpr add_par (IfaceType ty)     = char '@' <+> pprParendIfaceType ty
356
357 pprIfaceExpr add_par app@(IfaceApp _ _) = add_par (pprIfaceApp app [])
358 pprIfaceExpr add_par (IfaceTuple c as)  = tupleParens c (interpp'SP as)
359
360 pprIfaceExpr add_par e@(IfaceLam _ _)   
361   = add_par (sep [char '\\' <+> sep (map ppr bndrs) <+> arrow,
362                   pprIfaceExpr noParens body])
363   where 
364     (bndrs,body) = collect [] e
365     collect bs (IfaceLam b e) = collect (b:bs) e
366     collect bs e              = (reverse bs, e)
367
368 -- gaw 2004 
369 pprIfaceExpr add_par (IfaceCase scrut bndr ty [(con, bs, rhs)])
370 -- gaw 2004
371   = add_par (sep [ptext SLIT("case") <+> char '@' <+> pprParendIfaceType ty <+> pprIfaceExpr noParens scrut <+> ptext SLIT("of") 
372                         <+> ppr bndr <+> char '{' <+> ppr_con_bs con bs <+> arrow,
373                   pprIfaceExpr noParens rhs <+> char '}'])
374
375 -- gaw 2004
376 pprIfaceExpr add_par (IfaceCase scrut bndr ty alts)
377 -- gaw 2004
378   = add_par (sep [ptext SLIT("case") <+> char '@' <+> pprParendIfaceType ty <+> pprIfaceExpr noParens scrut <+> ptext SLIT("of") 
379                         <+> ppr bndr <+> char '{',
380                   nest 2 (sep (map ppr_alt alts)) <+> char '}'])
381
382 pprIfaceExpr add_par (IfaceLet (IfaceNonRec b rhs) body)
383   = add_par (sep [ptext SLIT("let {"), 
384                   nest 2 (ppr_bind (b, rhs)),
385                   ptext SLIT("} in"), 
386                   pprIfaceExpr noParens body])
387
388 pprIfaceExpr add_par (IfaceLet (IfaceRec pairs) body)
389   = add_par (sep [ptext SLIT("letrec {"),
390                   nest 2 (sep (map ppr_bind pairs)), 
391                   ptext SLIT("} in"),
392                   pprIfaceExpr noParens body])
393
394 pprIfaceExpr add_par (IfaceNote note body) = add_par (ppr note <+> pprIfaceExpr parens body)
395
396 ppr_alt (con, bs, rhs) = sep [ppr_con_bs con bs, 
397                               arrow <+> pprIfaceExpr noParens rhs]
398
399 ppr_con_bs (IfaceTupleAlt tup_con) bs = tupleParens tup_con (interpp'SP bs)
400 ppr_con_bs con bs                     = ppr con <+> hsep (map ppr bs)
401   
402 ppr_bind ((b,ty),rhs) = sep [ppr b <+> dcolon <+> ppr ty, 
403                              equals <+> pprIfaceExpr noParens rhs]
404
405 ------------------
406 pprIfaceApp (IfaceApp fun arg) args = pprIfaceApp fun (nest 2 (pprIfaceExpr parens arg) : args)
407 pprIfaceApp fun                args = sep (pprIfaceExpr parens fun : args)
408
409 ------------------
410 instance Outputable IfaceNote where
411     ppr (IfaceSCC cc)     = pprCostCentreCore cc
412     ppr (IfaceCoerce ty)  = ptext SLIT("__coerce") <+> pprParendIfaceType ty
413     ppr IfaceInlineCall   = ptext SLIT("__inline_call")
414     ppr IfaceInlineMe     = ptext SLIT("__inline_me")
415     ppr (IfaceCoreNote s) = ptext SLIT("__core_note") <+> pprHsString (mkFastString s)
416
417 instance Outputable IfaceConAlt where
418     ppr IfaceDefault      = text "DEFAULT"
419     ppr (IfaceLitAlt l)   = ppr l
420     ppr (IfaceDataAlt d)  = ppr d
421     ppr (IfaceTupleAlt b) = panic "ppr IfaceConAlt" 
422         -- IfaceTupleAlt is handled by the case-alternative printer
423
424 ------------------
425 instance Outputable IfaceIdInfo where
426    ppr NoInfo       = empty
427    ppr (HasInfo is) = ptext SLIT("{-") <+> fsep (map ppr_hs_info is) <+> ptext SLIT("-}")
428
429 ppr_hs_info (HsUnfold prag unf) = sep [ptext SLIT("Unfolding: ") <> ppr prag,
430                                        parens (pprIfaceExpr noParens unf)]
431 ppr_hs_info (HsArity arity)     = ptext SLIT("Arity:") <+> int arity
432 ppr_hs_info (HsStrictness str)  = ptext SLIT("Strictness:") <+> pprIfaceStrictSig str
433 ppr_hs_info HsNoCafRefs         = ptext SLIT("HasNoCafRefs")
434 ppr_hs_info (HsWorker w a)      = ptext SLIT("Worker:") <+> ppr w <+> int a
435 \end{code}
436
437
438 %************************************************************************
439 %*                                                                      *
440         Converting things to their Iface equivalents
441 %*                                                                      *
442 %************************************************************************
443
444                  
445 \begin{code}
446 tyThingToIfaceDecl :: (Name -> IfaceExtName) -> TyThing -> IfaceDecl
447 -- Assumption: the thing is already tidied, so that locally-bound names
448 --             (lambdas, for-alls) already have non-clashing OccNames
449 -- Reason: Iface stuff uses OccNames, and the conversion here does
450 --         not do tidying on the way
451 tyThingToIfaceDecl ext (AnId id)
452   = IfaceId { ifName   = getOccName id, 
453               ifType   = toIfaceType ext (idType id),
454               ifIdInfo = info }
455   where
456     info = case toIfaceIdInfo ext (idInfo id) of
457                 []    -> NoInfo
458                 items -> HasInfo items
459
460 tyThingToIfaceDecl ext (AClass clas)
461   = IfaceClass { ifCtxt   = toIfaceContext ext sc_theta,
462                  ifName   = getOccName clas,
463                  ifTyVars = toIfaceTvBndrs clas_tyvars,
464                  ifFDs    = map toIfaceFD clas_fds,
465                  ifSigs   = map toIfaceClassOp op_stuff,
466                  ifRec    = boolToRecFlag (isRecursiveTyCon tycon),
467                  ifVrcs   = tyConArgVrcs tycon }
468   where
469     (clas_tyvars, clas_fds, sc_theta, _, op_stuff) = classExtraBigSig clas
470     tycon = classTyCon clas
471
472     toIfaceClassOp (sel_id, def_meth)
473         = ASSERT(sel_tyvars == clas_tyvars)
474           IfaceClassOp (getOccName sel_id) def_meth (toIfaceType ext op_ty)
475         where
476                 -- Be careful when splitting the type, because of things
477                 -- like         class Foo a where
478                 --                op :: (?x :: String) => a -> a
479                 -- and          class Baz a where
480                 --                op :: (Ord a) => a -> a
481           (sel_tyvars, rho_ty) = splitForAllTys (idType sel_id)
482           op_ty                = funResultTy rho_ty
483
484     toIfaceFD (tvs1, tvs2) = (map getOccName tvs1, map getOccName tvs2)
485
486 tyThingToIfaceDecl ext (ATyCon tycon)
487   | isSynTyCon tycon
488   = IfaceSyn {  ifName   = getOccName tycon,
489                 ifTyVars = toIfaceTvBndrs tyvars,
490                 ifVrcs    = tyConArgVrcs tycon,
491                 ifSynRhs = toIfaceType ext syn_ty }
492
493   | isAlgTyCon tycon
494   = IfaceData { ifName    = getOccName tycon,
495                 ifTyVars  = toIfaceTvBndrs tyvars,
496                 ifCtxt    = toIfaceContext ext (tyConStupidTheta tycon),
497                 ifCons    = ifaceConDecls (algTyConRhs tycon),
498                 ifRec     = boolToRecFlag (isRecursiveTyCon tycon),
499                 ifVrcs    = tyConArgVrcs tycon,
500                 ifGeneric = tyConHasGenerics tycon }
501
502   | isForeignTyCon tycon
503   = IfaceForeign { ifName    = getOccName tycon,
504                    ifExtName = tyConExtName tycon }
505
506   | isPrimTyCon tycon || isFunTyCon tycon
507         -- Needed in GHCi for ':info Int#', for example
508   = IfaceData { ifName    = getOccName tycon,
509                 ifTyVars  = toIfaceTvBndrs (take (tyConArity tycon) alphaTyVars),
510                 ifCtxt    = [],
511                 ifCons    = IfAbstractTyCon,
512                 ifGeneric = False,
513                 ifRec     = NonRecursive,
514                 ifVrcs    = tyConArgVrcs tycon }
515
516   | otherwise = pprPanic "toIfaceDecl" (ppr tycon)
517   where
518     tyvars = tyConTyVars tycon
519     syn_ty = synTyConRhs tycon
520
521     ifaceConDecls (NewTyCon { data_con = con })    = IfNewTyCon  (ifaceConDecl con)
522     ifaceConDecls (DataTyCon { data_cons = cons }) = IfDataTyCon (map ifaceConDecl cons)
523     ifaceConDecls AbstractTyCon                    = IfAbstractTyCon
524         -- The last case happens when a TyCon has been trimmed during tidying
525         -- Furthermore, tyThingToIfaceDecl is also used
526         -- in TcRnDriver for GHCi, when browsing a module, in which case the
527         -- AbstractTyCon case is perfectly sensible.
528
529     ifaceConDecl data_con 
530         | isVanillaDataCon data_con
531         = IfVanillaCon {ifConOcc = getOccName (dataConName data_con),
532                         ifConInfix = dataConIsInfix data_con,
533                         ifConArgTys = map (toIfaceType ext) arg_tys,
534                         ifConStricts = strict_marks,
535                         ifConFields = map getOccName field_labels }
536         | otherwise
537         = IfGadtCon   { ifConOcc = getOccName (dataConName data_con),
538                         ifConTyVars = toIfaceTvBndrs tyvars,
539                         ifConCtxt = toIfaceContext ext theta,
540                         ifConArgTys = map (toIfaceType ext) arg_tys,
541                         ifConResTys = map (toIfaceType ext) res_tys,
542                         ifConStricts = strict_marks }
543         where
544           (tyvars, theta, arg_tys, _, res_tys) = dataConSig data_con
545           field_labels = dataConFieldLabels data_con
546           strict_marks = dataConStrictMarks data_con
547
548 tyThingToIfaceDecl ext (ADataCon dc)
549  = pprPanic "toIfaceDecl" (ppr dc)      -- Should be trimmed out earlier
550
551
552 --------------------------
553 instanceToIfaceInst :: (Name -> IfaceExtName) -> Instance -> IfaceInst
554 instanceToIfaceInst ext_lhs ispec@(Instance { is_dfun = dfun_id, is_flag = oflag,
555                                               is_cls = cls, is_tcs = mb_tcs, 
556                                               is_orph = orph })
557   = IfaceInst { ifDFun    = getOccName dfun_id, 
558                 ifOFlag   = oflag,
559                 ifInstCls = ext_lhs cls,
560                 ifInstTys = map do_rough mb_tcs,
561                 ifInstOrph = orph }
562   where
563     do_rough Nothing  = Nothing
564     do_rough (Just n) = Just (toIfaceTyCon_name ext_lhs n)
565
566 --------------------------
567 toIfaceIdInfo :: (Name -> IfaceExtName) -> IdInfo -> [IfaceInfoItem]
568 toIfaceIdInfo ext id_info
569   = catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo, 
570                wrkr_hsinfo,  unfold_hsinfo] 
571   where
572     ------------  Arity  --------------
573     arity_info = arityInfo id_info
574     arity_hsinfo | arity_info == 0 = Nothing
575                  | otherwise       = Just (HsArity arity_info)
576
577     ------------ Caf Info --------------
578     caf_info   = cafInfo id_info
579     caf_hsinfo = case caf_info of
580                    NoCafRefs -> Just HsNoCafRefs
581                    _other    -> Nothing
582
583     ------------  Strictness  --------------
584         -- No point in explicitly exporting TopSig
585     strict_hsinfo = case newStrictnessInfo id_info of
586                         Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
587                         _other                        -> Nothing
588
589     ------------  Worker  --------------
590     work_info   = workerInfo id_info
591     has_worker  = case work_info of { HasWorker _ _ -> True; other -> False }
592     wrkr_hsinfo = case work_info of
593                     HasWorker work_id wrap_arity -> 
594                         Just (HsWorker (ext (idName work_id)) wrap_arity)
595                     NoWorker -> Nothing
596
597     ------------  Unfolding  --------------
598     -- The unfolding is redundant if there is a worker
599     unfold_info = unfoldingInfo id_info
600     inline_prag = inlinePragInfo id_info
601     rhs         = unfoldingTemplate unfold_info
602     unfold_hsinfo |  neverUnfold unfold_info 
603                   || has_worker = Nothing
604                   | otherwise   = Just (HsUnfold inline_prag (toIfaceExpr ext rhs))
605
606 --------------------------
607 coreRuleToIfaceRule :: (Name -> IfaceExtName)   -- For the LHS names
608                     -> (Name -> IfaceExtName)   -- For the RHS names
609                     -> CoreRule -> IfaceRule
610 coreRuleToIfaceRule ext_lhs ext_rhs (BuiltinRule { ru_fn = fn})
611   = pprTrace "toHsRule: builtin" (ppr fn) $
612     bogusIfaceRule (mkIfaceExtName fn)
613
614 coreRuleToIfaceRule ext_lhs ext_rhs
615     (Rule { ru_name = name, ru_fn = fn, ru_act = act, ru_bndrs = bndrs,
616             ru_args = args, ru_rhs = rhs, ru_orph = orph })
617   = IfaceRule { ifRuleName  = name, ifActivation = act, 
618                 ifRuleBndrs = map (toIfaceBndr ext_lhs) bndrs,
619                 ifRuleHead  = ext_lhs fn, 
620                 ifRuleArgs  = map do_arg args,
621                 ifRuleRhs   = toIfaceExpr ext_rhs rhs,
622                 ifRuleOrph  = orph }
623   where
624         -- For type args we must remove synonyms from the outermost
625         -- level.  Reason: so that when we read it back in we'll
626         -- construct the same ru_rough field as we have right now;
627         -- see tcIfaceRule
628     do_arg (Type ty) = IfaceType (toIfaceType ext_lhs (deNoteType ty))
629     do_arg arg       = toIfaceExpr ext_lhs arg
630
631 bogusIfaceRule :: IfaceExtName -> IfaceRule
632 bogusIfaceRule id_name
633   = IfaceRule { ifRuleName = FSLIT("bogus"), ifActivation = NeverActive,  
634         ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [], 
635         ifRuleRhs = IfaceExt id_name, ifRuleOrph = Nothing }
636
637 ---------------------
638 toIfaceExpr :: (Name -> IfaceExtName) -> CoreExpr -> IfaceExpr
639 toIfaceExpr ext (Var v)       = toIfaceVar ext v
640 toIfaceExpr ext (Lit l)       = IfaceLit l
641 toIfaceExpr ext (Type ty)     = IfaceType (toIfaceType ext ty)
642 toIfaceExpr ext (Lam x b)     = IfaceLam (toIfaceBndr ext x) (toIfaceExpr ext b)
643 toIfaceExpr ext (App f a)     = toIfaceApp ext f [a]
644 -- gaw 2004
645 toIfaceExpr ext (Case s x ty as) = IfaceCase (toIfaceExpr ext s) (getOccName x) (toIfaceType ext ty) (map (toIfaceAlt ext) as)
646 toIfaceExpr ext (Let b e)     = IfaceLet (toIfaceBind ext b) (toIfaceExpr ext e)
647 toIfaceExpr ext (Note n e)    = IfaceNote (toIfaceNote ext n) (toIfaceExpr ext e)
648
649 ---------------------
650 toIfaceNote ext (SCC cc)      = IfaceSCC cc
651 toIfaceNote ext (Coerce t1 _) = IfaceCoerce (toIfaceType ext t1)
652 toIfaceNote ext InlineCall    = IfaceInlineCall
653 toIfaceNote ext InlineMe      = IfaceInlineMe
654 toIfaceNote ext (CoreNote s)  = IfaceCoreNote s
655
656 ---------------------
657 toIfaceBind ext (NonRec b r) = IfaceNonRec (toIfaceIdBndr ext b) (toIfaceExpr ext r)
658 toIfaceBind ext (Rec prs)    = IfaceRec [(toIfaceIdBndr ext b, toIfaceExpr ext r) | (b,r) <- prs]
659
660 ---------------------
661 toIfaceAlt ext (c,bs,r) = (toIfaceCon c, map getOccName bs, toIfaceExpr ext r)
662
663 ---------------------
664 toIfaceCon (DataAlt dc) | isTupleTyCon tc = IfaceTupleAlt (tupleTyConBoxity tc)
665                         | otherwise       = IfaceDataAlt (getOccName dc)
666                         where
667                           tc = dataConTyCon dc
668            
669 toIfaceCon (LitAlt l) = IfaceLitAlt l
670 toIfaceCon DEFAULT    = IfaceDefault
671
672 ---------------------
673 toIfaceApp ext (App f a) as = toIfaceApp ext f (a:as)
674 toIfaceApp ext (Var v) as
675   = case isDataConWorkId_maybe v of
676         -- We convert the *worker* for tuples into IfaceTuples
677         Just dc |  isTupleTyCon tc && saturated 
678                 -> IfaceTuple (tupleTyConBoxity tc) tup_args
679           where
680             val_args  = dropWhile isTypeArg as
681             saturated = val_args `lengthIs` idArity v
682             tup_args  = map (toIfaceExpr ext) val_args
683             tc        = dataConTyCon dc
684
685         other -> mkIfaceApps ext (toIfaceVar ext v) as
686
687 toIfaceApp ext e as = mkIfaceApps ext (toIfaceExpr ext e) as
688
689 mkIfaceApps ext f as = foldl (\f a -> IfaceApp f (toIfaceExpr ext a)) f as
690
691 ---------------------
692 toIfaceVar :: (Name -> IfaceExtName) -> Id -> IfaceExpr
693 toIfaceVar ext v 
694   | Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType ext (idType v))
695           -- Foreign calls have special syntax
696   | isExternalName name             = IfaceExt (ext name)
697   | otherwise                       = IfaceLcl (nameOccName name)
698   where
699     name = idName v
700 \end{code}
701
702
703 %************************************************************************
704 %*                                                                      *
705         Equality, for interface file version generaion only
706 %*                                                                      *
707 %************************************************************************
708
709 Equality over IfaceSyn returns an IfaceEq, not a Bool.  The new constructor is
710 EqBut, which gives the set of *locally-defined* things whose version must be equal
711 for the whole thing to be equal.  So the key function is eqIfExt, which compares
712 IfaceExtNames.
713
714 Of course, equality is also done modulo alpha conversion.
715
716 \begin{code}
717 data IfaceEq 
718   = Equal               -- Definitely exactly the same
719   | NotEqual            -- Definitely different
720   | EqBut OccSet        -- The same provided these local things have not changed
721
722 bool :: Bool -> IfaceEq
723 bool True  = Equal
724 bool False = NotEqual
725
726 zapEq :: IfaceEq -> IfaceEq     -- Used to forget EqBut information
727 zapEq (EqBut _) = Equal
728 zapEq other     = other
729
730 (&&&) :: IfaceEq -> IfaceEq -> IfaceEq
731 Equal       &&& x           = x
732 NotEqual    &&& x           = NotEqual
733 EqBut occs  &&& Equal       = EqBut occs
734 EqBut occs  &&& NotEqual    = NotEqual
735 EqBut occs1 &&& EqBut occs2 = EqBut (occs1 `unionOccSets` occs2)
736
737 ---------------------
738 eqIfExt :: IfaceExtName -> IfaceExtName -> IfaceEq
739 -- This function is the core of the EqBut stuff
740 eqIfExt (ExtPkg mod1 occ1)     (ExtPkg mod2 occ2)     = bool (mod1==mod2 && occ1==occ2)
741 eqIfExt (HomePkg mod1 occ1 v1) (HomePkg mod2 occ2 v2) = bool (mod1==mod2 && occ1==occ2 && v1==v2)
742 eqIfExt (LocalTop occ1)       (LocalTop occ2)      | occ1 == occ2 = EqBut (unitOccSet occ1)
743 eqIfExt (LocalTopSub occ1 p1) (LocalTop occ2)      | occ1 == occ2 = EqBut (unitOccSet p1)
744 eqIfExt (LocalTopSub occ1 p1) (LocalTopSub occ2 _) | occ1 == occ2 = EqBut (unitOccSet p1)
745 eqIfExt n1 n2 = NotEqual
746 \end{code}
747
748
749 \begin{code}
750 ---------------------
751 eqIfDecl :: IfaceDecl -> IfaceDecl -> IfaceEq
752 eqIfDecl (IfaceId s1 t1 i1) (IfaceId s2 t2 i2)
753   = bool (s1 == s2) &&& (t1 `eqIfType` t2) &&& (i1 `eqIfIdInfo` i2)
754
755 eqIfDecl d1@(IfaceForeign {}) d2@(IfaceForeign {})
756   = bool (ifName d1 == ifName d2 && ifExtName d1 == ifExtName d2)
757
758 eqIfDecl d1@(IfaceData {}) d2@(IfaceData {})
759   = bool (ifName d1    == ifName d2 && 
760           ifRec d1     == ifRec   d2 && 
761           ifVrcs d1    == ifVrcs   d2 && 
762           ifGeneric d1 == ifGeneric d2) &&&
763     eqWith (ifTyVars d1) (ifTyVars d2) (\ env -> 
764             eq_ifContext env (ifCtxt d1) (ifCtxt d2) &&& 
765             eq_hsCD env (ifCons d1) (ifCons d2) 
766         )
767         -- The type variables of the data type do not scope
768         -- over the constructors (any more), but they do scope
769         -- over the stupid context in the IfaceConDecls
770
771 eqIfDecl d1@(IfaceSyn {}) d2@(IfaceSyn {})
772   = bool (ifName d1 == ifName d2) &&&
773     eqWith (ifTyVars d1) (ifTyVars d2) (\ env -> 
774           eq_ifType env (ifSynRhs d1) (ifSynRhs d2)
775         )
776
777 eqIfDecl d1@(IfaceClass {}) d2@(IfaceClass {})
778   = bool (ifName d1 == ifName d2 && 
779           ifRec d1  == ifRec  d2 && 
780           ifVrcs d1 == ifVrcs d2) &&&
781     eqWith (ifTyVars d1) (ifTyVars d2) (\ env -> 
782           eq_ifContext env (ifCtxt d1) (ifCtxt d2)  &&&
783           eqListBy (eq_hsFD env)    (ifFDs d1)  (ifFDs d2) &&&
784           eqListBy (eq_cls_sig env) (ifSigs d1) (ifSigs d2)
785        )
786
787 eqIfDecl _ _ = NotEqual -- default case
788
789 -- Helper
790 eqWith :: [IfaceTvBndr] -> [IfaceTvBndr] -> (EqEnv -> IfaceEq) -> IfaceEq
791 eqWith = eq_ifTvBndrs emptyEqEnv
792
793 -----------------------
794 eqIfInst d1 d2 = bool (ifDFun d1 == ifDFun d2)
795 -- All other changes are handled via the version info on the dfun
796
797 eqIfRule (IfaceRule n1 a1 bs1 f1 es1 rhs1 o1)
798          (IfaceRule n2 a2 bs2 f2 es2 rhs2 o2)
799        = bool (n1==n2 && a1==a2 && o1 == o2) &&&
800          f1 `eqIfExt` f2 &&&
801          eq_ifBndrs emptyEqEnv bs1 bs2 (\env -> 
802          zapEq (eqListBy (eq_ifaceExpr env) es1 es2) &&&
803                 -- zapEq: for the LHSs, ignore the EqBut part
804          eq_ifaceExpr env rhs1 rhs2)
805
806 eq_hsCD env (IfDataTyCon c1) (IfDataTyCon c2) 
807   = eqListBy (eq_ConDecl env) c1 c2
808
809 eq_hsCD env (IfNewTyCon c1)  (IfNewTyCon c2)  = eq_ConDecl env c1 c2
810 eq_hsCD env IfAbstractTyCon  IfAbstractTyCon  = Equal
811 eq_hsCD env d1               d2               = NotEqual
812
813 eq_ConDecl env c1@(IfVanillaCon {}) c2@(IfVanillaCon {})
814   = bool (ifConOcc c1     == ifConOcc c2 && 
815           ifConInfix c1   == ifConInfix c2 && 
816           ifConStricts c1 == ifConStricts c2 && 
817           ifConFields c1  == ifConFields c2) &&&
818    eq_ifTypes env (ifConArgTys c1) (ifConArgTys c2)
819
820 eq_ConDecl env c1@(IfGadtCon {}) c2@(IfGadtCon {})
821   = bool (ifConOcc c1     == ifConOcc c2 && 
822           ifConStricts c1 == ifConStricts c2) &&& 
823     eq_ifTvBndrs env (ifConTyVars c1) (ifConTyVars c2) (\ env ->
824         eq_ifContext env (ifConCtxt c1) (ifConCtxt c2) &&&
825         eq_ifTypes env (ifConResTys c1) (ifConResTys c2) &&&
826         eq_ifTypes env (ifConArgTys c1) (ifConArgTys c2))
827
828 eq_ConDecl env c1 c2 = NotEqual
829
830 eq_hsFD env (ns1,ms1) (ns2,ms2)
831   = eqListBy (eqIfOcc env) ns1 ns2 &&& eqListBy (eqIfOcc env) ms1 ms2
832
833 eq_cls_sig env (IfaceClassOp n1 dm1 ty1) (IfaceClassOp n2 dm2 ty2)
834   = bool (n1==n2 && dm1 == dm2) &&& eq_ifType env ty1 ty2
835 \end{code}
836
837
838 \begin{code}
839 -----------------
840 eqIfIdInfo NoInfo        NoInfo        = Equal
841 eqIfIdInfo (HasInfo is1) (HasInfo is2) = eqListBy eq_item is1 is2
842 eqIfIdInfo i1 i2 = NotEqual
843
844 eq_item (HsArity a1)       (HsArity a2)       = bool (a1 == a2)
845 eq_item (HsStrictness s1)  (HsStrictness s2)  = bool (s1 == s2)
846 eq_item (HsUnfold a1 u1)   (HsUnfold a2 u2)   = bool (a1 == a2) &&& eq_ifaceExpr emptyEqEnv u1 u2
847 eq_item HsNoCafRefs        HsNoCafRefs        = Equal
848 eq_item (HsWorker wkr1 a1) (HsWorker wkr2 a2) = bool (a1==a2) &&& (wkr1 `eqIfExt` wkr2)
849 eq_item _ _ = NotEqual
850
851 -----------------
852 eq_ifaceExpr :: EqEnv -> IfaceExpr -> IfaceExpr -> IfaceEq
853 eq_ifaceExpr env (IfaceLcl v1)        (IfaceLcl v2)        = eqIfOcc env v1 v2
854 eq_ifaceExpr env (IfaceExt v1)        (IfaceExt v2)        = eqIfExt v1 v2
855 eq_ifaceExpr env (IfaceLit l1)        (IfaceLit l2)        = bool (l1 == l2)
856 eq_ifaceExpr env (IfaceFCall c1 ty1)  (IfaceFCall c2 ty2)  = bool (c1==c2) &&& eq_ifType env ty1 ty2
857 eq_ifaceExpr env (IfaceType ty1)      (IfaceType ty2)      = eq_ifType env ty1 ty2
858 eq_ifaceExpr env (IfaceTuple n1 as1)  (IfaceTuple n2 as2)  = bool (n1==n2) &&& eqListBy (eq_ifaceExpr env) as1 as2
859 eq_ifaceExpr env (IfaceLam b1 body1)  (IfaceLam b2 body2)  = eq_ifBndr env b1 b2 (\env -> eq_ifaceExpr env body1 body2)
860 eq_ifaceExpr env (IfaceApp f1 a1)     (IfaceApp f2 a2)     = eq_ifaceExpr env f1 f2 &&& eq_ifaceExpr env a1 a2
861 eq_ifaceExpr env (IfaceNote n1 r1)    (IfaceNote n2 r2)    = eq_ifaceNote env n1 n2 &&& eq_ifaceExpr env r1 r2
862
863 eq_ifaceExpr env (IfaceCase s1 b1 ty1 as1) (IfaceCase s2 b2 ty2 as2)
864   = eq_ifaceExpr env s1 s2 &&&
865     eq_ifType env ty1 ty2 &&&
866     eq_ifNakedBndr env b1 b2 (\env -> eqListBy (eq_ifaceAlt env) as1 as2)
867   where
868     eq_ifaceAlt env (c1,bs1,r1) (c2,bs2,r2)
869         = bool (eq_ifaceConAlt c1 c2) &&& 
870           eq_ifNakedBndrs env bs1 bs2 (\env -> eq_ifaceExpr env r1 r2)
871
872 eq_ifaceExpr env (IfaceLet (IfaceNonRec b1 r1) x1) (IfaceLet (IfaceNonRec b2 r2) x2)
873   = eq_ifaceExpr env r1 r2 &&& eq_ifIdBndr env b1 b2 (\env -> eq_ifaceExpr env x1 x2)
874
875 eq_ifaceExpr env (IfaceLet (IfaceRec as1) x1) (IfaceLet (IfaceRec as2) x2)
876   = eq_ifIdBndrs env bs1 bs2 (\env -> eqListBy (eq_ifaceExpr env) rs1 rs2 &&& eq_ifaceExpr env x1 x2)
877   where
878     (bs1,rs1) = unzip as1
879     (bs2,rs2) = unzip as2
880
881
882 eq_ifaceExpr env _ _ = NotEqual
883
884 -----------------
885 eq_ifaceConAlt :: IfaceConAlt -> IfaceConAlt -> Bool
886 eq_ifaceConAlt IfaceDefault       IfaceDefault          = True
887 eq_ifaceConAlt (IfaceDataAlt n1)  (IfaceDataAlt n2)     = n1==n2
888 eq_ifaceConAlt (IfaceTupleAlt c1) (IfaceTupleAlt c2)    = c1==c2
889 eq_ifaceConAlt (IfaceLitAlt l1)   (IfaceLitAlt l2)      = l1==l2
890 eq_ifaceConAlt _ _ = False
891
892 -----------------
893 eq_ifaceNote :: EqEnv -> IfaceNote -> IfaceNote -> IfaceEq
894 eq_ifaceNote env (IfaceSCC c1)    (IfaceSCC c2)        = bool (c1==c2)
895 eq_ifaceNote env (IfaceCoerce t1) (IfaceCoerce t2)     = eq_ifType env t1 t2
896 eq_ifaceNote env IfaceInlineCall  IfaceInlineCall      = Equal
897 eq_ifaceNote env IfaceInlineMe    IfaceInlineMe        = Equal
898 eq_ifaceNote env (IfaceCoreNote s1) (IfaceCoreNote s2) = bool (s1==s2)
899 eq_ifaceNote env _ _ = NotEqual
900 \end{code}
901
902 \begin{code}
903 ---------------------
904 eqIfType t1 t2 = eq_ifType emptyEqEnv t1 t2
905
906 -------------------
907 eq_ifType env (IfaceTyVar n1)         (IfaceTyVar n2)         = eqIfOcc env n1 n2
908 eq_ifType env (IfaceAppTy s1 t1)      (IfaceAppTy s2 t2)      = eq_ifType env s1 s2 &&& eq_ifType env t1 t2
909 eq_ifType env (IfacePredTy st1)       (IfacePredTy st2)       = eq_ifPredType env st1 st2
910 eq_ifType env (IfaceTyConApp tc1 ts1) (IfaceTyConApp tc2 ts2) = tc1 `eqIfTc` tc2 &&& eq_ifTypes env ts1 ts2
911 eq_ifType env (IfaceForAllTy tv1 t1)  (IfaceForAllTy tv2 t2)  = eq_ifTvBndr env tv1 tv2 (\env -> eq_ifType env t1 t2)
912 eq_ifType env (IfaceFunTy s1 t1)      (IfaceFunTy s2 t2)      = eq_ifType env s1 s2 &&& eq_ifType env t1 t2
913 eq_ifType env _ _ = NotEqual
914
915 -------------------
916 eq_ifTypes env = eqListBy (eq_ifType env)
917
918 -------------------
919 eq_ifContext env a b = eqListBy (eq_ifPredType env) a b
920
921 -------------------
922 eq_ifPredType env (IfaceClassP c1 tys1) (IfaceClassP c2 tys2) = c1 `eqIfExt` c2 &&&  eq_ifTypes env tys1 tys2
923 eq_ifPredType env (IfaceIParam n1 ty1) (IfaceIParam n2 ty2)   = bool (n1 == n2) &&& eq_ifType env ty1 ty2
924 eq_ifPredType env _ _ = NotEqual
925
926 -------------------
927 eqIfTc (IfaceTc tc1) (IfaceTc tc2) = tc1 `eqIfExt` tc2
928 eqIfTc IfaceIntTc    IfaceIntTc    = Equal
929 eqIfTc IfaceCharTc   IfaceCharTc   = Equal
930 eqIfTc IfaceBoolTc   IfaceBoolTc   = Equal
931 eqIfTc IfaceListTc   IfaceListTc   = Equal
932 eqIfTc IfacePArrTc   IfacePArrTc   = Equal
933 eqIfTc (IfaceTupTc bx1 ar1) (IfaceTupTc bx2 ar2) = bool (bx1==bx2 && ar1==ar2)
934 eqIfTc _ _ = NotEqual
935 \end{code}
936
937 -----------------------------------------------------------
938         Support code for equality checking
939 -----------------------------------------------------------
940
941 \begin{code}
942 ------------------------------------
943 type EqEnv = OccEnv OccName     -- Tracks the mapping from L-variables to R-variables
944
945 eqIfOcc :: EqEnv -> OccName -> OccName -> IfaceEq
946 eqIfOcc env n1 n2 = case lookupOccEnv env n1 of
947                         Just n1 -> bool (n1 == n2)
948                         Nothing -> bool (n1 == n2)
949
950 extendEqEnv :: EqEnv -> OccName -> OccName -> EqEnv
951 extendEqEnv env n1 n2 | n1 == n2  = env
952                       | otherwise = extendOccEnv env n1 n2
953
954 emptyEqEnv :: EqEnv
955 emptyEqEnv = emptyOccEnv
956
957 ------------------------------------
958 type ExtEnv bndr = EqEnv -> bndr -> bndr -> (EqEnv -> IfaceEq) -> IfaceEq
959
960 eq_ifNakedBndr :: ExtEnv OccName
961 eq_ifBndr      :: ExtEnv IfaceBndr
962 eq_ifTvBndr    :: ExtEnv IfaceTvBndr
963 eq_ifIdBndr    :: ExtEnv IfaceIdBndr
964
965 eq_ifNakedBndr env n1 n2 k = k (extendEqEnv env n1 n2)
966
967 eq_ifBndr env (IfaceIdBndr b1) (IfaceIdBndr b2) k = eq_ifIdBndr env b1 b2 k
968 eq_ifBndr env (IfaceTvBndr b1) (IfaceTvBndr b2) k = eq_ifTvBndr env b1 b2 k
969 eq_ifBndr _ _ _ _ = NotEqual
970
971 eq_ifTvBndr env (v1, k1) (v2, k2) k = bool (k1 == k2)     &&& k (extendEqEnv env v1 v2)
972 eq_ifIdBndr env (v1, t1) (v2, t2) k = eq_ifType env t1 t2 &&& k (extendEqEnv env v1 v2)
973
974 eq_ifBndrs      :: ExtEnv [IfaceBndr]
975 eq_ifIdBndrs    :: ExtEnv [IfaceIdBndr]
976 eq_ifTvBndrs    :: ExtEnv [IfaceTvBndr]
977 eq_ifNakedBndrs :: ExtEnv [OccName]
978 eq_ifBndrs      = eq_bndrs_with eq_ifBndr
979 eq_ifIdBndrs    = eq_bndrs_with eq_ifIdBndr
980 eq_ifTvBndrs    = eq_bndrs_with eq_ifTvBndr
981 eq_ifNakedBndrs = eq_bndrs_with eq_ifNakedBndr
982
983 eq_bndrs_with eq env []       []       k = k env
984 eq_bndrs_with eq env (b1:bs1) (b2:bs2) k = eq env b1 b2 (\env -> eq_bndrs_with eq env bs1 bs2 k)
985 eq_bndrs_with eq env _        _        _ = NotEqual
986 \end{code}
987
988 \begin{code}
989 eqListBy :: (a->a->IfaceEq) -> [a] -> [a] -> IfaceEq
990 eqListBy eq []     []     = Equal
991 eqListBy eq (x:xs) (y:ys) = eq x y &&& eqListBy eq xs ys
992 eqListBy eq xs     ys     = NotEqual
993
994 eqMaybeBy :: (a->a->IfaceEq) -> Maybe a -> Maybe a -> IfaceEq
995 eqMaybeBy eq Nothing Nothing   = Equal
996 eqMaybeBy eq (Just x) (Just y) = eq x y
997 eqMaybeBy eq x        y        = NotEqual
998 \end{code}