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