Moved canonicalisation inside solveInteract
[ghc-hetmet.git] / compiler / typecheck / TcInstDcls.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 TcInstDecls: Typechecking instance declarations
7
8 \begin{code}
9 module TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where
10
11 import HsSyn
12 import TcBinds
13 import TcTyClsDecls
14 import TcClassDcl
15 import TcPat( addInlinePrags )
16 import TcRnMonad
17 import TcMType
18 import TcType
19 import Inst
20 import InstEnv
21 import FamInst
22 import FamInstEnv
23 import MkCore   ( nO_METHOD_BINDING_ERROR_ID )
24 import TcDeriv
25 import TcEnv
26 import RnSource ( addTcgDUs )
27 import TcSimplify( simplifySuperClass )
28 import TcHsType
29 import TcUnify
30 import Type
31 import Coercion
32 import TyCon
33 import DataCon
34 import Class
35 import Var
36 import CoreUtils  ( mkPiTypes )
37 import CoreUnfold ( mkDFunUnfolding )
38 import CoreSyn    ( Expr(Var) )
39 import Id
40 import MkId
41 import Name
42 import NameSet
43 import DynFlags
44 import SrcLoc
45 import Util
46 import Outputable
47 import Bag
48 import BasicTypes
49 import HscTypes
50 import FastString
51 import Maybes   ( orElse )
52 import Data.Maybe
53 import Control.Monad
54 import Data.List
55
56 #include "HsVersions.h"
57 \end{code}
58
59 Typechecking instance declarations is done in two passes. The first
60 pass, made by @tcInstDecls1@, collects information to be used in the
61 second pass.
62
63 This pre-processed info includes the as-yet-unprocessed bindings
64 inside the instance declaration.  These are type-checked in the second
65 pass, when the class-instance envs and GVE contain all the info from
66 all the instance and value decls.  Indeed that's the reason we need
67 two passes over the instance decls.
68
69
70 Note [How instance declarations are translated]
71 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
72 Here is how we translation instance declarations into Core
73
74 Running example:
75         class C a where
76            op1, op2 :: Ix b => a -> b -> b
77            op2 = <dm-rhs>
78
79         instance C a => C [a]
80            {-# INLINE [2] op1 #-}
81            op1 = <rhs>
82 ===>
83         -- Method selectors
84         op1,op2 :: forall a. C a => forall b. Ix b => a -> b -> b
85         op1 = ...
86         op2 = ...
87
88         -- Default methods get the 'self' dictionary as argument
89         -- so they can call other methods at the same type
90         -- Default methods get the same type as their method selector
91         $dmop2 :: forall a. C a => forall b. Ix b => a -> b -> b
92         $dmop2 = /\a. \(d:C a). /\b. \(d2: Ix b). <dm-rhs>
93                -- NB: type variables 'a' and 'b' are *both* in scope in <dm-rhs>
94                -- Note [Tricky type variable scoping]
95
96         -- A top-level definition for each instance method
97         -- Here op1_i, op2_i are the "instance method Ids"
98         -- The INLINE pragma comes from the user pragma
99         {-# INLINE [2] op1_i #-}  -- From the instance decl bindings
100         op1_i, op2_i :: forall a. C a => forall b. Ix b => [a] -> b -> b
101         op1_i = /\a. \(d:C a). 
102                let this :: C [a]
103                    this = df_i a d
104                      -- Note [Subtle interaction of recursion and overlap]
105
106                    local_op1 :: forall b. Ix b => [a] -> b -> b
107                    local_op1 = <rhs>
108                      -- Source code; run the type checker on this
109                      -- NB: Type variable 'a' (but not 'b') is in scope in <rhs>
110                      -- Note [Tricky type variable scoping]
111
112                in local_op1 a d
113
114         op2_i = /\a \d:C a. $dmop2 [a] (df_i a d) 
115
116         -- The dictionary function itself
117         {-# NOINLINE CONLIKE df_i #-}   -- Never inline dictionary functions
118         df_i :: forall a. C a -> C [a]
119         df_i = /\a. \d:C a. MkC (op1_i a d) (op2_i a d)
120                 -- But see Note [Default methods in instances]
121                 -- We can't apply the type checker to the default-method call
122
123         -- Use a RULE to short-circuit applications of the class ops
124         {-# RULE "op1@C[a]" forall a, d:C a. 
125                             op1 [a] (df_i d) = op1_i a d #-}
126
127 Note [Instances and loop breakers]
128 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
129 * Note that df_i may be mutually recursive with both op1_i and op2_i.
130   It's crucial that df_i is not chosen as the loop breaker, even 
131   though op1_i has a (user-specified) INLINE pragma.
132
133 * Instead the idea is to inline df_i into op1_i, which may then select
134   methods from the MkC record, and thereby break the recursion with
135   df_i, leaving a *self*-recurisve op1_i.  (If op1_i doesn't call op at
136   the same type, it won't mention df_i, so there won't be recursion in
137   the first place.)  
138
139 * If op1_i is marked INLINE by the user there's a danger that we won't
140   inline df_i in it, and that in turn means that (since it'll be a
141   loop-breaker because df_i isn't), op1_i will ironically never be 
142   inlined.  But this is OK: the recursion breaking happens by way of
143   a RULE (the magic ClassOp rule above), and RULES work inside InlineRule
144   unfoldings. See Note [RULEs enabled in SimplGently] in SimplUtils
145
146 Note [ClassOp/DFun selection]
147 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
148 One thing we see a lot is stuff like
149     op2 (df d1 d2)
150 where 'op2' is a ClassOp and 'df' is DFun.  Now, we could inline *both*
151 'op2' and 'df' to get
152      case (MkD ($cop1 d1 d2) ($cop2 d1 d2) ... of
153        MkD _ op2 _ _ _ -> op2
154 And that will reduce to ($cop2 d1 d2) which is what we wanted.
155
156 But it's tricky to make this work in practice, because it requires us to 
157 inline both 'op2' and 'df'.  But neither is keen to inline without having
158 seen the other's result; and it's very easy to get code bloat (from the 
159 big intermediate) if you inline a bit too much.
160
161 Instead we use a cunning trick.
162  * We arrange that 'df' and 'op2' NEVER inline.  
163
164  * We arrange that 'df' is ALWAYS defined in the sylised form
165       df d1 d2 = MkD ($cop1 d1 d2) ($cop2 d1 d2) ...
166
167  * We give 'df' a magical unfolding (DFunUnfolding [$cop1, $cop2, ..])
168    that lists its methods.
169
170  * We make CoreUnfold.exprIsConApp_maybe spot a DFunUnfolding and return
171    a suitable constructor application -- inlining df "on the fly" as it 
172    were.
173
174  * We give the ClassOp 'op2' a BuiltinRule that extracts the right piece
175    iff its argument satisfies exprIsConApp_maybe.  This is done in
176    MkId mkDictSelId
177
178  * We make 'df' CONLIKE, so that shared uses stil match; eg
179       let d = df d1 d2
180       in ...(op2 d)...(op1 d)...
181
182 Note [Single-method classes]
183 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
184 If the class has just one method (or, more accurately, just one element
185 of {superclasses + methods}), then we still use the *same* strategy
186
187    class C a where op :: a -> a
188    instance C a => C [a] where op = <blah>
189
190 We translate the class decl into a newtype, which just gives
191 a top-level axiom:
192
193    axiom Co:C a :: C a ~ (a->a)
194
195    op :: forall a. C a -> (a -> a)
196    op a d = d |> (Co:C a)
197
198    MkC :: forall a. (a->a) -> C a
199    MkC = /\a.\op. op |> (sym Co:C a)
200
201    df :: forall a. C a => C [a]
202    {-# NOINLINE df   DFun[ $cop_list ] #-}
203    df = /\a. \d. MkC ($cop_list a d)
204
205    $cop_list :: forall a. C a => [a] -> [a]
206    $cop_list = <blah>
207
208 The "constructor" MkC expands to a cast, as does the class-op selector.
209 The RULE works just like for multi-field dictionaries:
210
211   * (df a d) returns (Just (MkC,..,[$cop_list a d])) 
212     to exprIsConApp_Maybe
213
214   * The RULE for op picks the right result
215
216 This is a bit of a hack, because (df a d) isn't *really* a constructor
217 application.  But it works just fine in this case, exprIsConApp_maybe
218 is otherwise used only when we hit a case expression which will have
219 a real data constructor in it.
220
221 The biggest reason for doing it this way, apart from uniformity, is
222 that we want to be very careful when we have
223     instance C a => C [a] where
224       {-# INLINE op #-}
225       op = ...
226 then we'll get an INLINE pragma on $cop_list but it's important that
227 $cop_list only inlines when it's applied to *two* arguments (the
228 dictionary and the list argument
229
230 The danger is that we'll get something like
231       op_list :: C a => [a] -> [a]
232       op_list = /\a.\d. $cop_list a d
233 and then we'll eta expand, and then we'll inline TOO EARLY. This happened in 
234 Trac #3772 and I spent far too long fiddling around trying to fix it.
235 Look at the test for Trac #3772.
236
237      (Note: re-reading the above, I can't see how using the
238             uniform story solves the problem.)
239
240 Note [Subtle interaction of recursion and overlap]
241 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
242 Consider this
243   class C a where { op1,op2 :: a -> a }
244   instance C a => C [a] where
245     op1 x = op2 x ++ op2 x
246     op2 x = ...
247   instance C [Int] where
248     ...
249
250 When type-checking the C [a] instance, we need a C [a] dictionary (for
251 the call of op2).  If we look up in the instance environment, we find
252 an overlap.  And in *general* the right thing is to complain (see Note
253 [Overlapping instances] in InstEnv).  But in *this* case it's wrong to
254 complain, because we just want to delegate to the op2 of this same
255 instance.  
256
257 Why is this justified?  Because we generate a (C [a]) constraint in 
258 a context in which 'a' cannot be instantiated to anything that matches
259 other overlapping instances, or else we would not be excecuting this
260 version of op1 in the first place.
261
262 It might even be a bit disguised:
263
264   nullFail :: C [a] => [a] -> [a]
265   nullFail x = op2 x ++ op2 x
266
267   instance C a => C [a] where
268     op1 x = nullFail x
269
270 Precisely this is used in package 'regex-base', module Context.hs.
271 See the overlapping instances for RegexContext, and the fact that they
272 call 'nullFail' just like the example above.  The DoCon package also
273 does the same thing; it shows up in module Fraction.hs
274
275 Conclusion: when typechecking the methods in a C [a] instance, we want
276 to have C [a] available.  That is why we have the strange local
277 definition for 'this' in the definition of op1_i in the example above.
278 We can typecheck the defintion of local_op1, and when doing tcSimplifyCheck
279 we supply 'this' as a given dictionary.  Only needed, though, if there
280 are some type variables involved; otherwise there can be no overlap and
281 none of this arises.
282
283 Note [Tricky type variable scoping]
284 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
285 In our example
286         class C a where
287            op1, op2 :: Ix b => a -> b -> b
288            op2 = <dm-rhs>
289
290         instance C a => C [a]
291            {-# INLINE [2] op1 #-}
292            op1 = <rhs>
293
294 note that 'a' and 'b' are *both* in scope in <dm-rhs>, but only 'a' is
295 in scope in <rhs>.  In particular, we must make sure that 'b' is in
296 scope when typechecking <dm-rhs>.  This is achieved by subFunTys,
297 which brings appropriate tyvars into scope. This happens for both
298 <dm-rhs> and for <rhs>, but that doesn't matter: the *renamer* will have
299 complained if 'b' is mentioned in <rhs>.
300
301
302
303 %************************************************************************
304 %*                                                                      *
305 \subsection{Extracting instance decls}
306 %*                                                                      *
307 %************************************************************************
308
309 Gather up the instance declarations from their various sources
310
311 \begin{code}
312 tcInstDecls1    -- Deal with both source-code and imported instance decls
313    :: [LTyClDecl Name]          -- For deriving stuff
314    -> [LInstDecl Name]          -- Source code instance decls
315    -> [LDerivDecl Name]         -- Source code stand-alone deriving decls
316    -> TcM (TcGblEnv,            -- The full inst env
317            [InstInfo Name],     -- Source-code instance decls to process;
318                                 -- contains all dfuns for this module
319            HsValBinds Name)     -- Supporting bindings for derived instances
320
321 tcInstDecls1 tycl_decls inst_decls deriv_decls
322   = checkNoErrs $
323     do {        -- Stop if addInstInfos etc discovers any errors
324                 -- (they recover, so that we get more than one error each
325                 -- round)
326
327                 -- (1) Do class and family instance declarations
328        ; idx_tycons        <- mapAndRecoverM (tcFamInstDecl TopLevel) $
329                               filter (isFamInstDecl . unLoc) tycl_decls 
330        ; local_info_tycons <- mapAndRecoverM tcLocalInstDecl1  inst_decls
331
332        ; let { (local_info,
333                 at_tycons_s)   = unzip local_info_tycons
334              ; at_idx_tycons   = concat at_tycons_s ++ idx_tycons
335              ; clas_decls      = filter (isClassDecl.unLoc) tycl_decls
336              ; implicit_things = concatMap implicitTyThings at_idx_tycons
337              ; aux_binds       = mkRecSelBinds at_idx_tycons
338              }
339
340                 -- (2) Add the tycons of indexed types and their implicit
341                 --     tythings to the global environment
342        ; tcExtendGlobalEnv (at_idx_tycons ++ implicit_things) $ do {
343
344                 -- (3) Instances from generic class declarations
345        ; generic_inst_info <- getGenericInstances clas_decls
346
347                 -- Next, construct the instance environment so far, consisting
348                 -- of
349                 --   (a) local instance decls
350                 --   (b) generic instances
351                 --   (c) local family instance decls
352        ; addInsts local_info         $
353          addInsts generic_inst_info  $
354          addFamInsts at_idx_tycons   $ do {
355
356                 -- (4) Compute instances from "deriving" clauses;
357                 -- This stuff computes a context for the derived instance
358                 -- decl, so it needs to know about all the instances possible
359                 -- NB: class instance declarations can contain derivings as
360                 --     part of associated data type declarations
361          failIfErrsM            -- If the addInsts stuff gave any errors, don't
362                                 -- try the deriving stuff, becuase that may give
363                                 -- more errors still
364        ; (deriv_inst_info, deriv_binds, deriv_dus) 
365               <- tcDeriving tycl_decls inst_decls deriv_decls
366        ; gbl_env <- addInsts deriv_inst_info getGblEnv
367        ; return ( addTcgDUs gbl_env deriv_dus,
368                   generic_inst_info ++ deriv_inst_info ++ local_info,
369                   aux_binds `plusHsValBinds` deriv_binds)
370     }}}
371
372 addInsts :: [InstInfo Name] -> TcM a -> TcM a
373 addInsts infos thing_inside
374   = tcExtendLocalInstEnv (map iSpec infos) thing_inside
375
376 addFamInsts :: [TyThing] -> TcM a -> TcM a
377 addFamInsts tycons thing_inside
378   = tcExtendLocalFamInstEnv (map mkLocalFamInstTyThing tycons) thing_inside
379   where
380     mkLocalFamInstTyThing (ATyCon tycon) = mkLocalFamInst tycon
381     mkLocalFamInstTyThing tything        = pprPanic "TcInstDcls.addFamInsts"
382                                                     (ppr tything)
383 \end{code}
384
385 \begin{code}
386 tcLocalInstDecl1 :: LInstDecl Name
387                  -> TcM (InstInfo Name, [TyThing])
388         -- A source-file instance declaration
389         -- Type-check all the stuff before the "where"
390         --
391         -- We check for respectable instance type, and context
392 tcLocalInstDecl1 (L loc (InstDecl poly_ty binds uprags ats))
393   = setSrcSpan loc                      $
394     addErrCtxt (instDeclCtxt1 poly_ty)  $
395
396     do  { is_boot <- tcIsHsBoot
397         ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags))
398                   badBootDeclErr
399
400         ; (tyvars, theta, tau) <- tcHsInstHead poly_ty
401
402         -- Now, check the validity of the instance.
403         ; (clas, inst_tys) <- checkValidInstance poly_ty tyvars theta tau
404
405         -- Next, process any associated types.
406         ; idx_tycons <- recoverM (return []) $
407                      do { idx_tycons <- checkNoErrs $ 
408                                         mapAndRecoverM (tcFamInstDecl NotTopLevel) ats
409                         ; checkValidAndMissingATs clas (tyvars, inst_tys)
410                                                   (zip ats idx_tycons)
411                         ; return idx_tycons }
412
413         -- Finally, construct the Core representation of the instance.
414         -- (This no longer includes the associated types.)
415         ; dfun_name <- newDFunName clas inst_tys (getLoc poly_ty)
416                 -- Dfun location is that of instance *header*
417         ; overlap_flag <- getOverlapFlag
418         ; let (eq_theta,dict_theta) = partition isEqPred theta
419               theta'         = eq_theta ++ dict_theta
420               dfun           = mkDictFunId dfun_name tyvars theta' clas inst_tys
421               ispec          = mkLocalInstance dfun overlap_flag
422
423         ; return (InstInfo { iSpec  = ispec,
424                              iBinds = VanillaInst binds uprags False },
425                   idx_tycons)
426         }
427   where
428     -- We pass in the source form and the type checked form of the ATs.  We
429     -- really need the source form only to be able to produce more informative
430     -- error messages.
431     checkValidAndMissingATs :: Class
432                             -> ([TyVar], [TcType])     -- instance types
433                             -> [(LTyClDecl Name,       -- source form of AT
434                                  TyThing)]             -- Core form of AT
435                             -> TcM ()
436     checkValidAndMissingATs clas inst_tys ats
437       = do { -- Issue a warning for each class AT that is not defined in this
438              -- instance.
439            ; let class_ats   = map tyConName (classATs clas)
440                  defined_ats = listToNameSet . map (tcdName.unLoc.fst)  $ ats
441                  omitted     = filterOut (`elemNameSet` defined_ats) class_ats
442            ; warn <- doptM Opt_WarnMissingMethods
443            ; mapM_ (warnTc warn . omittedATWarn) omitted
444
445              -- Ensure that all AT indexes that correspond to class parameters
446              -- coincide with the types in the instance head.  All remaining
447              -- AT arguments must be variables.  Also raise an error for any
448              -- type instances that are not associated with this class.
449            ; mapM_ (checkIndexes clas inst_tys) ats
450            }
451
452     checkIndexes clas inst_tys (hsAT, ATyCon tycon)
453 -- !!!TODO: check that this does the Right Thing for indexed synonyms, too!
454       = checkIndexes' clas inst_tys hsAT
455                       (tyConTyVars tycon,
456                        snd . fromJust . tyConFamInst_maybe $ tycon)
457     checkIndexes _ _ _ = panic "checkIndexes"
458
459     checkIndexes' clas (instTvs, instTys) hsAT (atTvs, atTys)
460       = let atName = tcdName . unLoc $ hsAT
461         in
462         setSrcSpan (getLoc hsAT)       $
463         addErrCtxt (atInstCtxt atName) $
464         case find ((atName ==) . tyConName) (classATs clas) of
465           Nothing     -> addErrTc $ badATErr clas atName  -- not in this class
466           Just atycon ->
467                 -- The following is tricky!  We need to deal with three
468                 -- complications: (1) The AT possibly only uses a subset of
469                 -- the class parameters as indexes and those it uses may be in
470                 -- a different order; (2) the AT may have extra arguments,
471                 -- which must be type variables; and (3) variables in AT and
472                 -- instance head will be different `Name's even if their
473                 -- source lexemes are identical.
474                 --
475                 -- e.g.    class C a b c where 
476                 --           data D b a :: * -> *           -- NB (1) b a, omits c
477                 --         instance C [x] Bool Char where 
478                 --           data D Bool [x] v = MkD x [v]  -- NB (2) v
479                 --                -- NB (3) the x in 'instance C...' have differnt
480                 --                --        Names to x's in 'data D...'
481                 --
482                 -- Re (1), `poss' contains a permutation vector to extract the
483                 -- class parameters in the right order.
484                 --
485                 -- Re (2), we wrap the (permuted) class parameters in a Maybe
486                 -- type and use Nothing for any extra AT arguments.  (First
487                 -- equation of `checkIndex' below.)
488                 --
489                 -- Re (3), we replace any type variable in the AT parameters
490                 -- that has the same source lexeme as some variable in the
491                 -- instance types with the instance type variable sharing its
492                 -- source lexeme.
493                 --
494                 let poss :: [Int]
495                     -- For *associated* type families, gives the position
496                     -- of that 'TyVar' in the class argument list (0-indexed)
497                     -- e.g.  class C a b c where { type F c a :: *->* }
498                     --       Then we get Just [2,0]
499                     poss = catMaybes [ tv `elemIndex` classTyVars clas 
500                                      | tv <- tyConTyVars atycon]
501                        -- We will get Nothings for the "extra" type 
502                        -- variables in an associated data type
503                        -- e.g. class C a where { data D a :: *->* }
504                        -- here D gets arity 2 and has two tyvars
505
506                     relevantInstTys = map (instTys !!) poss
507                     instArgs        = map Just relevantInstTys ++
508                                       repeat Nothing  -- extra arguments
509                     renaming        = substSameTyVar atTvs instTvs
510                 in
511                 zipWithM_ checkIndex (substTys renaming atTys) instArgs
512
513     checkIndex ty Nothing
514       | isTyVarTy ty         = return ()
515       | otherwise            = addErrTc $ mustBeVarArgErr ty
516     checkIndex ty (Just instTy)
517       | ty `tcEqType` instTy = return ()
518       | otherwise            = addErrTc $ wrongATArgErr ty instTy
519
520     listToNameSet = addListToNameSet emptyNameSet
521
522     substSameTyVar []       _            = emptyTvSubst
523     substSameTyVar (tv:tvs) replacingTvs =
524       let replacement = case find (tv `sameLexeme`) replacingTvs of
525                         Nothing  -> mkTyVarTy tv
526                         Just rtv -> mkTyVarTy rtv
527           --
528           tv1 `sameLexeme` tv2 =
529             nameOccName (tyVarName tv1) == nameOccName (tyVarName tv2)
530       in
531       extendTvSubst (substSameTyVar tvs replacingTvs) tv replacement
532 \end{code}
533
534
535 %************************************************************************
536 %*                                                                      *
537       Type-checking instance declarations, pass 2
538 %*                                                                      *
539 %************************************************************************
540
541 \begin{code}
542 tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo Name]
543              -> TcM (LHsBinds Id)
544 -- (a) From each class declaration,
545 --      generate any default-method bindings
546 -- (b) From each instance decl
547 --      generate the dfun binding
548
549 tcInstDecls2 tycl_decls inst_decls
550   = do  { -- (a) Default methods from class decls
551           let class_decls = filter (isClassDecl . unLoc) tycl_decls
552         ; dm_binds_s <- mapM tcClassDecl2 class_decls
553         ; let dm_binds = unionManyBags dm_binds_s
554                                     
555           -- (b) instance declarations
556         ; let dm_ids = collectHsBindsBinders dm_binds
557               -- Add the default method Ids (again)
558               -- See Note [Default methods and instances]
559         ; inst_binds_s <- tcExtendIdEnv dm_ids $
560                           mapM tcInstDecl2 inst_decls
561
562           -- Done
563         ; return (dm_binds `unionBags` unionManyBags inst_binds_s) }
564
565 tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id)
566 tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds })
567   = recoverM (return emptyLHsBinds)             $
568     setSrcSpan loc                              $
569     addErrCtxt (instDeclCtxt2 (idType dfun_id)) $ 
570     tc_inst_decl2 dfun_id ibinds
571  where
572     dfun_id = instanceDFunId ispec
573     loc     = getSrcSpan dfun_id
574 \end{code}
575
576 See Note [Default methods and instances]
577 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
578 The default method Ids are already in the type environment (see Note
579 [Default method Ids and Template Haskell] in TcTyClsDcls), BUT they
580 don't have their InlinePragmas yet.  Usually that would not matter,
581 because the simplifier propagates information from binding site to
582 use.  But, unusually, when compiling instance decls we *copy* the
583 INLINE pragma from the default method to the method for that
584 particular operation (see Note [INLINE and default methods] below).
585
586 So right here in tcInstDecl2 we must re-extend the type envt with
587 the default method Ids replete with their INLINE pragmas.  Urk.
588
589 \begin{code}
590 tc_inst_decl2 :: Id -> InstBindings Name -> TcM (LHsBinds Id)
591 -- Returns a binding for the dfun
592 tc_inst_decl2 dfun_id inst_binds
593  = do { let rigid_info = InstSkol
594             inst_ty    = idType dfun_id
595             loc        = getSrcSpan dfun_id
596
597         -- Instantiate the instance decl with skolem constants
598        ; (inst_tyvars', dfun_theta', inst_head') <- tcSkolSigType rigid_info inst_ty
599                 -- These inst_tyvars' scope over the 'where' part
600                 -- Those tyvars are inside the dfun_id's type, which is a bit
601                 -- bizarre, but OK so long as you realise it!
602        ; let
603             (clas, inst_tys') = tcSplitDFunHead inst_head'
604             (class_tyvars, sc_theta, sc_sels, op_items) = classBigSig clas
605
606              -- Instantiate the super-class context with inst_tys
607             sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys') sc_theta
608
609          -- Create dictionary Ids from the specified instance contexts.
610        ; dfun_ev_vars <- newEvVars dfun_theta'
611        ; self_dict    <- newSelfDict clas inst_tys'
612                 -- Default-method Ids may be mentioned in synthesised RHSs,
613                 -- but they'll already be in the environment.
614
615         -- Cook up a binding for "self = df d1 .. dn",
616         -- to use in each method binding
617         -- Why?  See Note [Subtle interaction of recursion and overlap]
618        ; let self_ev_bind = EvBind self_dict $ 
619                             EvDFunApp dfun_id (mkTyVarTys inst_tyvars') dfun_ev_vars []
620                                       -- Empty dependencies [], since it only
621                                       -- depends on "given" things
622
623        -- Deal with 'SPECIALISE instance' pragmas
624        -- See Note [SPECIALISE instance pragmas]
625        ; spec_info <- tcSpecInstPrags dfun_id inst_binds
626
627         -- Typecheck the methods
628        ; (meth_ids, meth_binds) 
629            <- tcExtendTyVarEnv inst_tyvars' $
630               tcInstanceMethods dfun_id clas inst_tyvars' dfun_ev_vars 
631                                 inst_tys' self_ev_bind spec_info
632                                 op_items inst_binds
633
634          -- Figure out bindings for the superclass context
635        ; let tc_sc = tcSuperClass inst_tyvars' dfun_ev_vars self_ev_bind
636              (sc_eqs, sc_dicts) = splitAt (classSCNEqs clas) sc_theta'
637        ; (sc_dict_ids, sc_binds) <- ASSERT( equalLength sc_sels sc_dicts )
638                                     ASSERT( all isEqPred sc_eqs )
639                                     mapAndUnzipM tc_sc (sc_sels `zip` sc_dicts)
640
641                                     -- NOT FINISHED!
642        ; (_eq_sc_binds, sc_eq_vars) <- checkConstraints InstSkol
643                                            inst_tyvars' dfun_ev_vars $
644                                       emitWanteds ScOrigin sc_eqs
645
646        -- Create the result bindings
647        ; let dict_constr       = classDataCon clas
648              dict_bind         = mkVarBind self_dict dict_rhs
649              dict_rhs          = foldl mk_app inst_constr dict_and_meth_ids
650              dict_and_meth_ids = sc_dict_ids ++ meth_ids
651              inst_constr   = L loc $ wrapId (mkWpEvVarApps sc_eq_vars 
652                                              <.> mkWpTyApps inst_tys')
653                                             (dataConWrapId dict_constr)
654                      -- We don't produce a binding for the dict_constr; instead we
655                      -- rely on the simplifier to unfold this saturated application
656                      -- We do this rather than generate an HsCon directly, because
657                      -- it means that the special cases (e.g. dictionary with only one
658                      -- member) are dealt with by the common MkId.mkDataConWrapId code rather
659                      -- than needing to be repeated here.
660
661              mk_app :: LHsExpr Id -> Id -> LHsExpr Id
662              mk_app fun arg_id = L loc (HsApp fun (L loc (wrapId arg_wrapper arg_id)))
663              arg_wrapper = mkWpEvVarApps dfun_ev_vars <.> mkWpTyApps (mkTyVarTys inst_tyvars')
664
665                 -- Do not inline the dfun; instead give it a magic DFunFunfolding
666                 -- See Note [ClassOp/DFun selection]
667                 -- See also note [Single-method classes]
668              dfun_id_w_fun = dfun_id  
669                              `setIdUnfolding`  mkDFunUnfolding inst_ty (map Var dict_and_meth_ids)
670                                                         -- Not right for equality superclasses
671                              `setInlinePragma` dfunInlinePragma
672
673              (spec_inst_prags, _) = spec_info
674              main_bind = AbsBinds { abs_tvs = inst_tyvars'
675                                   , abs_ev_vars = dfun_ev_vars
676                                   , abs_exports = [(inst_tyvars', dfun_id_w_fun, self_dict, 
677                                                     SpecPrags spec_inst_prags)]
678                                   , abs_ev_binds = emptyTcEvBinds
679                                   , abs_binds = unitBag dict_bind }
680
681        ; return (unitBag (L loc main_bind) `unionBags` 
682                  listToBag meth_binds      `unionBags` 
683                  listToBag sc_binds)
684        }
685
686 ------------------------------
687 tcSpecInstPrags :: DFunId -> InstBindings Name 
688                 -> TcM ([Located TcSpecPrag], PragFun)
689 tcSpecInstPrags _ (NewTypeDerived {})
690   = return ([], \_ -> [])
691 tcSpecInstPrags dfun_id (VanillaInst binds uprags _)
692   = do { spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) $
693                             filter isSpecInstLSig uprags
694              -- The filter removes the pragmas for methods
695        ; return (spec_inst_prags, mkPragFun uprags binds) }
696
697 ------------------------------
698 tcSuperClass :: [TyVar] -> [EvVar]
699              -> EvBind
700              -> (Id, PredType) -> TcM (Id, LHsBind Id)
701 -- Build a top level decl like
702 --      sc_op = /\a \d. let this = ... in 
703 --                      let sc = ... in
704 --                      sc
705 -- The "this" part is just-in-case (discarded if not used)
706 -- See Note [Recursive superclasses]
707 tcSuperClass tyvars dicts 
708              self_ev_bind
709              (sc_sel, sc_pred)
710  = do { sc_dict <- newWantedEvVar sc_pred
711       ; ev_binds <- simplifySuperClass tyvars dicts sc_dict self_ev_bind
712
713        ; uniq <- newUnique
714        ; let sc_op_ty   = mkForAllTys tyvars $ mkPiTypes dicts (varType sc_dict)
715              sc_op_name = mkDerivedInternalName mkClassOpAuxOcc uniq
716                                                 (getName sc_sel)
717              sc_op_id   = mkLocalId sc_op_name sc_op_ty
718              sc_op_bind = VarBind { var_id = sc_op_id, var_inline = False
719                                   , var_rhs = L noSrcSpan $ wrapId sc_wrapper sc_dict }
720              sc_wrapper = mkWpTyLams tyvars
721                           <.> mkWpLams dicts
722                           <.> mkWpLet ev_binds
723
724        ; return (sc_op_id, noLoc sc_op_bind) }
725 \end{code}
726
727 Note [Recursive superclasses]
728 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
729 See Trac #1470 for why we would *like* to add "self_dict" to the 
730 available instances here.  But we can't do so because then the superclases
731 get satisfied by selection from self_dict, and that leads to an immediate
732 loop.  What we need is to add self_dict to Avails without adding its 
733 superclasses, and we currently have no way to do that.
734
735 Note [SPECIALISE instance pragmas]
736 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
737 Consider
738
739    instance (Ix a, Ix b) => Ix (a,b) where
740      {-# SPECIALISE instance Ix (Int,Int) #-}
741      range (x,y) = ...
742
743 We do *not* want to make a specialised version of the dictionary
744 function.  Rather, we want specialised versions of each method.
745 Thus we should generate something like this:
746
747   $dfIx :: (Ix a, Ix x) => Ix (a,b)
748   {- DFUN [$crange, ...] -}
749   $dfIx da db = Ix ($crange da db) (...other methods...)
750
751   $dfIxPair :: (Ix a, Ix x) => Ix (a,b)
752   {- DFUN [$crangePair, ...] -}
753   $dfIxPair = Ix ($crangePair da db) (...other methods...)
754
755   $crange :: (Ix a, Ix b) -> ((a,b),(a,b)) -> [(a,b)]
756   {-# SPECIALISE $crange :: ((Int,Int),(Int,Int)) -> [(Int,Int)] #-}
757   $crange da db = <blah>
758
759   {-# RULE  range ($dfIx da db) = $crange da db #-}
760
761 Note that  
762
763   * The RULE is unaffected by the specialisation.  We don't want to
764     specialise $dfIx, because then it would need a specialised RULE
765     which is a pain.  The single RULE works fine at all specialisations.
766     See Note [How instance declarations are translated] above
767
768   * Instead, we want to specialise the *method*, $crange
769
770 In practice, rather than faking up a SPECIALISE pragama for each
771 method (which is painful, since we'd have to figure out its
772 specialised type), we call tcSpecPrag *as if* were going to specialise
773 $dfIx -- you can see that in the call to tcSpecInst.  That generates a
774 SpecPrag which, as it turns out, can be used unchanged for each method.
775 The "it turns out" bit is delicate, but it works fine!
776
777 \begin{code}
778 tcSpecInst :: Id -> Sig Name -> TcM TcSpecPrag
779 tcSpecInst dfun_id prag@(SpecInstSig hs_ty) 
780   = addErrCtxt (spec_ctxt prag) $
781     do  { let name = idName dfun_id
782         ; (tyvars, theta, tau) <- tcHsInstHead hs_ty    
783         ; let spec_ty = mkSigmaTy tyvars theta tau
784         ; co_fn <- tcSubType (SpecPragOrigin name) (SigSkol SpecInstCtxt) 
785                              (idType dfun_id) spec_ty
786         ; return (SpecPrag dfun_id co_fn defaultInlinePragma) }
787   where
788     spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
789
790 tcSpecInst _  _ = panic "tcSpecInst"
791 \end{code}
792
793 %************************************************************************
794 %*                                                                      *
795       Type-checking an instance method
796 %*                                                                      *
797 %************************************************************************
798
799 tcInstanceMethod
800 - Make the method bindings, as a [(NonRec, HsBinds)], one per method
801 - Remembering to use fresh Name (the instance method Name) as the binder
802 - Bring the instance method Ids into scope, for the benefit of tcInstSig
803 - Use sig_fn mapping instance method Name -> instance tyvars
804 - Ditto prag_fn
805 - Use tcValBinds to do the checking
806
807 \begin{code}
808 tcInstanceMethods :: DFunId -> Class -> [TcTyVar]
809                   -> [EvVar]
810                   -> [TcType]
811                   -> EvBind               -- "This" and its binding
812                   -> ([Located TcSpecPrag], PragFun)
813                   -> [(Id, DefMeth)]
814                   -> InstBindings Name 
815                   -> TcM ([Id], [LHsBind Id])
816         -- The returned inst_meth_ids all have types starting
817         --      forall tvs. theta => ...
818 tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys 
819                   self_dict_ev (spec_inst_prags, prag_fn)
820                   op_items (VanillaInst binds _ standalone_deriv)
821   = mapAndUnzipM tc_item op_items
822   where
823     ----------------------
824     tc_item :: (Id, DefMeth) -> TcM (Id, LHsBind Id)
825     tc_item (sel_id, dm_info)
826       = case findMethodBind (idName sel_id) binds of
827             Just user_bind -> tc_body sel_id standalone_deriv user_bind
828             Nothing        -> tc_default sel_id dm_info
829
830     ----------------------
831     tc_body :: Id -> Bool -> LHsBind Name -> TcM (TcId, LHsBind Id)
832     tc_body sel_id generated_code rn_bind 
833       = add_meth_ctxt sel_id generated_code rn_bind $
834         do { (meth_id, local_meth_id) <- mkMethIds clas tyvars dfun_ev_vars 
835                                                    inst_tys sel_id
836            ; let prags = prag_fn (idName sel_id)
837            ; meth_id1 <- addInlinePrags meth_id prags
838            ; spec_prags <- tcSpecPrags meth_id1 prags
839            ; bind <- tcInstanceMethodBody InstSkol
840                           tyvars dfun_ev_vars mb_dict_ev
841                           meth_id1 local_meth_id meth_sig_fn 
842                           (mk_meth_spec_prags meth_id1 spec_prags)
843                           rn_bind 
844            ; return (meth_id1, bind) }
845
846     ----------------------
847     tc_default :: Id -> DefMeth -> TcM (TcId, LHsBind Id)
848     tc_default sel_id GenDefMeth    -- Derivable type classes stuff
849       = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id
850            ; tc_body sel_id False {- Not generated code? -} meth_bind }
851           
852     tc_default sel_id NoDefMeth     -- No default method at all
853       = do { warnMissingMethod sel_id
854            ; (meth_id, _) <- mkMethIds clas tyvars dfun_ev_vars 
855                                          inst_tys sel_id
856            ; return (meth_id, mkVarBind meth_id $ 
857                               mkLHsWrap lam_wrapper error_rhs) }
858       where
859         error_rhs    = L loc $ HsApp error_fun error_msg
860         error_fun    = L loc $ wrapId (WpTyApp meth_tau) nO_METHOD_BINDING_ERROR_ID
861         error_msg    = L loc (HsLit (HsStringPrim (mkFastString error_string)))
862         meth_tau     = funResultTy (applyTys (idType sel_id) inst_tys)
863         error_string = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
864         lam_wrapper  = mkWpTyLams tyvars <.> mkWpLams dfun_ev_vars
865
866     tc_default sel_id (DefMeth dm_name) -- A polymorphic default method
867       = do {   -- Build the typechecked version directly, 
868                  -- without calling typecheck_method; 
869                  -- see Note [Default methods in instances]
870                  -- Generate   /\as.\ds. let this = df as ds 
871                --                      in $dm inst_tys this
872                  -- The 'let' is necessary only because HsSyn doesn't allow
873                  -- you to apply a function to a dictionary *expression*.
874
875            ; (meth_id, local_meth_id) <- mkMethIds clas tyvars dfun_ev_vars 
876                                                    inst_tys sel_id
877            ; dm_id <- tcLookupId dm_name
878            ; let dm_inline_prag = idInlinePragma dm_id
879                  EvBind self_dict _ = self_dict_ev
880                  rhs = HsWrap (mkWpEvVarApps [self_dict] <.> mkWpTyApps inst_tys) $
881                          HsVar dm_id 
882
883                  meth_bind = L loc $ VarBind { var_id = local_meth_id
884                                              , var_rhs = L loc rhs 
885                                                , var_inline = False }
886                  meth_id1 = meth_id `setInlinePragma` dm_inline_prag
887                             -- Copy the inline pragma (if any) from the default
888                             -- method to this version. Note [INLINE and default methods]
889                             
890                  bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars =  dfun_ev_vars
891                                  , abs_exports = [( tyvars, meth_id1, local_meth_id
892                                                   , mk_meth_spec_prags meth_id1 [])]
893                                  , abs_ev_binds = EvBinds (unitBag self_dict_ev)
894                                  , abs_binds    = unitBag meth_bind }
895              -- Default methods in an instance declaration can't have their own 
896              -- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but
897              -- currently they are rejected with 
898              --           "INLINE pragma lacks an accompanying binding"
899
900            ; return (meth_id1, L loc bind) } 
901
902     ----------------------
903     mk_meth_spec_prags :: Id -> [LTcSpecPrag] -> TcSpecPrags
904         -- Adapt the SPECIALISE pragmas to work for this method Id
905         -- There are two sources: 
906         --   * spec_inst_prags: {-# SPECIALISE instance :: <blah> #-}
907         --     These ones have the dfun inside, but [perhaps surprisingly] 
908         --     the correct wrapper
909         --   * spec_prags_for_me: {-# SPECIALISE op :: <blah> #-}
910     mk_meth_spec_prags meth_id spec_prags_for_me
911       = SpecPrags (spec_prags_for_me ++ 
912                    [ L loc (SpecPrag meth_id wrap inl)
913                    | L loc (SpecPrag _ wrap inl) <- spec_inst_prags])
914    
915     loc = getSrcSpan dfun_id
916     meth_sig_fn _ = Just ([],loc)       -- The 'Just' says "yes, there's a type sig"
917         -- But there are no scoped type variables from local_method_id
918         -- Only the ones from the instance decl itself, which are already
919         -- in scope.  Example:
920         --      class C a where { op :: forall b. Eq b => ... }
921         --      instance C [c] where { op = <rhs> }
922         -- In <rhs>, 'c' is scope but 'b' is not!
923
924     mb_dict_ev = if null tyvars then Nothing else Just self_dict_ev
925                 -- Only need the self_dict stuff if there are type 
926                 -- variables involved; otherwise overlap is not possible
927                 -- See Note [Subtle interaction of recursion and overlap]
928                 -- in TcInstDcls
929
930         -- For instance decls that come from standalone deriving clauses
931         -- we want to print out the full source code if there's an error
932         -- because otherwise the user won't see the code at all
933     add_meth_ctxt sel_id generated_code rn_bind thing 
934       | generated_code = addLandmarkErrCtxt (derivBindCtxt sel_id clas inst_tys rn_bind) thing
935       | otherwise      = thing
936
937
938 tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys 
939                   _ _ op_items (NewTypeDerived coi _)
940
941 -- Running example:
942 --   class Show b => Foo a b where
943 --     op :: a -> b -> b
944 --   newtype N a = MkN (Tree [a]) 
945 --   deriving instance (Show p, Foo Int p) => Foo Int (N p)
946 --               -- NB: standalone deriving clause means
947 --               --     that the contex is user-specified
948 -- Hence op :: forall a b. Foo a b => a -> b -> b
949 --
950 -- We're going to make an instance like
951 --   instance (Show p, Foo Int p) => Foo Int (N p)
952 --      op = $copT
953 --
954 --   $copT :: forall p. (Show p, Foo Int p) => Int -> N p -> N p
955 --   $copT p (d1:Show p) (d2:Foo Int p) 
956 --     = op Int (Tree [p]) rep_d |> op_co
957 --     where 
958 --       rep_d :: Foo Int (Tree [p]) = ...d1...d2...
959 --       op_co :: (Int -> Tree [p] -> Tree [p]) ~ (Int -> T p -> T p)
960 -- We get op_co by substituting [Int/a] and [co/b] in type for op
961 -- where co : [p] ~ T p
962 --
963 -- Notice that the dictionary bindings "..d1..d2.." must be generated
964 -- by the constraint solver, since the <context> may be
965 -- user-specified.
966
967   = do { rep_d_stuff <- checkConstraints InstSkol tyvars dfun_ev_vars $
968                         emitWanted ScOrigin rep_pred
969                          
970        ; mapAndUnzipM (tc_item rep_d_stuff) op_items }
971   where
972      loc = getSrcSpan dfun_id
973
974      inst_tvs = fst (tcSplitForAllTys (idType dfun_id))
975      Just (init_inst_tys, _) = snocView inst_tys
976      rep_ty   = fst (coercionKind co)  -- [p]
977      rep_pred = mkClassPred clas (init_inst_tys ++ [rep_ty])
978
979      -- co : [p] ~ T p
980      co = substTyWith inst_tvs (mkTyVarTys tyvars) $
981           case coi of { IdCo ty -> ty ;
982                         ACo co  -> mkSymCoercion co }
983
984      ----------------
985      tc_item :: (TcEvBinds, EvVar) -> (Id, DefMeth) -> TcM (TcId, LHsBind TcId)
986      tc_item (rep_ev_binds, rep_d) (sel_id, _)
987        = do { (meth_id, local_meth_id) <- mkMethIds clas tyvars dfun_ev_vars 
988                                                     inst_tys sel_id
989
990             ; let meth_rhs  = wrapId (mk_op_wrapper sel_id rep_d) sel_id
991                   meth_bind = VarBind { var_id = local_meth_id
992                                       , var_rhs = L loc meth_rhs
993                                       , var_inline = False }
994
995                   bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars
996                                    , abs_exports = [(tyvars, meth_id, 
997                                                      local_meth_id, noSpecPrags)]
998                                    , abs_ev_binds = rep_ev_binds
999                                    , abs_binds = unitBag $ L loc meth_bind }
1000
1001             ; return (meth_id, L loc bind) }
1002
1003      ----------------
1004      mk_op_wrapper :: Id -> EvVar -> HsWrapper
1005      mk_op_wrapper sel_id rep_d 
1006        = WpCast (substTyWith sel_tvs (init_inst_tys ++ [co]) local_meth_ty)
1007          <.> WpEvApp (EvId rep_d)
1008          <.> mkWpTyApps (init_inst_tys ++ [rep_ty]) 
1009        where
1010          (sel_tvs, sel_rho) = tcSplitForAllTys (idType sel_id)
1011          (_, local_meth_ty) = tcSplitPredFunTy_maybe sel_rho
1012                               `orElse` pprPanic "tcInstanceMethods" (ppr sel_id)
1013
1014 ----------------------
1015 mkMethIds :: Class -> [TcTyVar] -> [EvVar] -> [TcType] -> Id -> TcM (TcId, TcId)
1016 mkMethIds clas tyvars dfun_ev_vars inst_tys sel_id
1017   = do  { uniq <- newUnique
1018         ; let meth_name = mkDerivedInternalName mkClassOpAuxOcc uniq sel_name
1019         ; local_meth_name <- newLocalName sel_name
1020                   -- Base the local_meth_name on the selector name, becuase
1021                   -- type errors from tcInstanceMethodBody come from here
1022
1023         ; let meth_id       = mkLocalId meth_name meth_ty
1024               local_meth_id = mkLocalId local_meth_name local_meth_ty
1025         ; return (meth_id, local_meth_id) }
1026   where
1027     local_meth_ty = instantiateMethod clas sel_id inst_tys
1028     meth_ty = mkForAllTys tyvars $ mkPiTypes dfun_ev_vars local_meth_ty
1029     sel_name = idName sel_id
1030
1031 ----------------------
1032 wrapId :: HsWrapper -> id -> HsExpr id
1033 wrapId wrapper id = mkHsWrap wrapper (HsVar id)
1034
1035 derivBindCtxt :: Id -> Class -> [Type ] -> LHsBind Name -> SDoc
1036 derivBindCtxt sel_id clas tys _bind
1037    = vcat [ ptext (sLit "When typechecking the code for ") <+> quotes (ppr sel_id)
1038           , nest 2 (ptext (sLit "in a standalone derived instance for")
1039                     <+> quotes (pprClassPred clas tys) <> colon)
1040           , nest 2 $ ptext (sLit "To see the code I am typechecking, use -ddump-deriv") ]
1041
1042 -- Too voluminous
1043 --        , nest 2 $ pprSetDepth AllTheWay $ ppr bind ]
1044
1045 warnMissingMethod :: Id -> TcM ()
1046 warnMissingMethod sel_id
1047   = do { warn <- doptM Opt_WarnMissingMethods           
1048        ; warnTc (warn  -- Warn only if -fwarn-missing-methods
1049                  && not (startsWithUnderscore (getOccName sel_id)))
1050                                         -- Don't warn about _foo methods
1051                 (ptext (sLit "No explicit method nor default method for")
1052                  <+> quotes (ppr sel_id)) }
1053 \end{code}
1054
1055 Note [Export helper functions]
1056 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1057 We arrange to export the "helper functions" of an instance declaration,
1058 so that they are not subject to preInlineUnconditionally, even if their
1059 RHS is trivial.  Reason: they are mentioned in the DFunUnfolding of
1060 the dict fun as Ids, not as CoreExprs, so we can't substitute a 
1061 non-variable for them.
1062
1063 We could change this by making DFunUnfoldings have CoreExprs, but it
1064 seems a bit simpler this way.
1065
1066 Note [Default methods in instances]
1067 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1068 Consider this
1069
1070    class Baz v x where
1071       foo :: x -> x
1072       foo y = <blah>
1073
1074    instance Baz Int Int
1075
1076 From the class decl we get
1077
1078    $dmfoo :: forall v x. Baz v x => x -> x
1079    $dmfoo y = <blah>
1080
1081 Notice that the type is ambiguous.  That's fine, though. The instance
1082 decl generates
1083
1084    $dBazIntInt = MkBaz fooIntInt
1085    fooIntInt = $dmfoo Int Int $dBazIntInt
1086
1087 BUT this does mean we must generate the dictionary translation of
1088 fooIntInt directly, rather than generating source-code and
1089 type-checking it.  That was the bug in Trac #1061. In any case it's
1090 less work to generate the translated version!
1091
1092 Note [INLINE and default methods]
1093 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1094 Default methods need special case.  They are supposed to behave rather like
1095 macros.  For exmample
1096
1097   class Foo a where
1098     op1, op2 :: Bool -> a -> a
1099
1100     {-# INLINE op1 #-}
1101     op1 b x = op2 (not b) x
1102
1103   instance Foo Int where
1104     -- op1 via default method
1105     op2 b x = <blah>
1106    
1107 The instance declaration should behave
1108
1109    just as if 'op1' had been defined with the
1110    code, and INLINE pragma, from its original
1111    definition. 
1112
1113 That is, just as if you'd written
1114
1115   instance Foo Int where
1116     op2 b x = <blah>
1117
1118     {-# INLINE op1 #-}
1119     op1 b x = op2 (not b) x
1120
1121 So for the above example we generate:
1122
1123
1124   {-# INLINE $dmop1 #-}
1125   -- $dmop1 has an InlineCompulsory unfolding
1126   $dmop1 d b x = op2 d (not b) x
1127
1128   $fFooInt = MkD $cop1 $cop2
1129
1130   {-# INLINE $cop1 #-}
1131   $cop1 = $dmop1 $fFooInt
1132
1133   $cop2 = <blah>
1134
1135 Note carefullly:
1136
1137 * We *copy* any INLINE pragma from the default method $dmop1 to the
1138   instance $cop1.  Otherwise we'll just inline the former in the
1139   latter and stop, which isn't what the user expected
1140
1141 * Regardless of its pragma, we give the default method an 
1142   unfolding with an InlineCompulsory source. That means
1143   that it'll be inlined at every use site, notably in
1144   each instance declaration, such as $cop1.  This inlining
1145   must happen even though 
1146     a) $dmop1 is not saturated in $cop1
1147     b) $cop1 itself has an INLINE pragma
1148
1149   It's vital that $dmop1 *is* inlined in this way, to allow the mutual
1150   recursion between $fooInt and $cop1 to be broken
1151
1152 * To communicate the need for an InlineCompulsory to the desugarer
1153   (which makes the Unfoldings), we use the IsDefaultMethod constructor
1154   in TcSpecPrags.
1155
1156
1157 %************************************************************************
1158 %*                                                                      *
1159 \subsection{Error messages}
1160 %*                                                                      *
1161 %************************************************************************
1162
1163 \begin{code}
1164 instDeclCtxt1 :: LHsType Name -> SDoc
1165 instDeclCtxt1 hs_inst_ty
1166   = inst_decl_ctxt (case unLoc hs_inst_ty of
1167                         HsForAllTy _ _ _ (L _ (HsPredTy pred)) -> ppr pred
1168                         HsPredTy pred                    -> ppr pred
1169                         _                                -> ppr hs_inst_ty)     -- Don't expect this
1170 instDeclCtxt2 :: Type -> SDoc
1171 instDeclCtxt2 dfun_ty
1172   = inst_decl_ctxt (ppr (mkClassPred cls tys))
1173   where
1174     (_,cls,tys) = tcSplitDFunTy dfun_ty
1175
1176 inst_decl_ctxt :: SDoc -> SDoc
1177 inst_decl_ctxt doc = ptext (sLit "In the instance declaration for") <+> quotes doc
1178
1179 atInstCtxt :: Name -> SDoc
1180 atInstCtxt name = ptext (sLit "In the associated type instance for") <+>
1181                   quotes (ppr name)
1182
1183 mustBeVarArgErr :: Type -> SDoc
1184 mustBeVarArgErr ty =
1185   sep [ ptext (sLit "Arguments that do not correspond to a class parameter") <+>
1186         ptext (sLit "must be variables")
1187       , ptext (sLit "Instead of a variable, found") <+> ppr ty
1188       ]
1189
1190 wrongATArgErr :: Type -> Type -> SDoc
1191 wrongATArgErr ty instTy =
1192   sep [ ptext (sLit "Type indexes must match class instance head")
1193       , ptext (sLit "Found") <+> quotes (ppr ty)
1194         <+> ptext (sLit "but expected") <+> quotes (ppr instTy)
1195       ]
1196 \end{code}