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