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