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