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