Checking conformance of AT indexes with instance heads
[ghc-hetmet.git] / compiler / typecheck / TcInstDcls.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcInstDecls]{Typechecking instance declarations}
5
6 \begin{code}
7 module TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where
8
9 #include "HsVersions.h"
10
11 import HsSyn
12 import TcBinds          ( mkPragFun, tcPrags, badBootDeclErr )
13 import TcTyClsDecls     ( tcIdxTyInstDecl )
14 import TcClassDcl       ( tcMethodBind, mkMethodBind, badMethodErr, badATErr,
15                           omittedATWarn, tcClassDecl2, getGenericInstances )
16 import TcRnMonad       
17 import TcMType          ( tcSkolSigType, checkValidInstance,
18                           checkValidInstHead )
19 import TcType           ( TcType, mkClassPred, tcSplitSigmaTy,
20                           tcSplitDFunHead,  SkolemInfo(InstSkol),
21                           tcSplitDFunTy, mkFunTy ) 
22 import Inst             ( newDictBndr, newDictBndrs, instToId, showLIE, 
23                           getOverlapFlag, tcExtendLocalInstEnv )
24 import InstEnv          ( mkLocalInstance, instanceDFunId )
25 import TcDeriv          ( tcDeriving )
26 import TcEnv            ( InstInfo(..), InstBindings(..), 
27                           newDFunName, tcExtendIdEnv, tcExtendGlobalEnv
28                         )
29 import TcHsType         ( kcHsSigType, tcHsKindedType )
30 import TcUnify          ( checkSigTyVars )
31 import TcSimplify       ( tcSimplifySuperClasses )
32 import Type             ( zipOpenTvSubst, substTheta, mkTyConApp, mkTyVarTy,
33                           splitFunTys, TyThing(ATyCon), isTyVarTy, tcEqType,
34                           substTys, emptyTvSubst, extendTvSubst )
35 import Coercion         ( mkSymCoercion )
36 import TyCon            ( TyCon, tyConName, newTyConCo, tyConTyVars,
37                           isTyConAssoc, tyConFamInst_maybe,
38                           assocTyConArgPoss_maybe )
39 import DataCon          ( classDataCon, dataConTyCon, dataConInstArgTys )
40 import Class            ( Class, classBigSig, classATs )
41 import Var              ( TyVar, Id, idName, idType, tyVarKind, tyVarName )
42 import VarEnv           ( rnBndrs2, mkRnEnv2, emptyInScopeSet )
43 import Id               ( mkSysLocal )
44 import UniqSupply       ( uniqsFromSupply, splitUniqSupply )
45 import MkId             ( mkDictFunId )
46 import Name             ( Name, getSrcLoc, nameOccName )
47 import NameSet          ( addListToNameSet, emptyNameSet, minusNameSet,
48                           nameSetToList ) 
49 import Maybe            ( isNothing, fromJust, catMaybes )
50 import Monad            ( when )
51 import List             ( find )
52 import DynFlags         ( DynFlag(Opt_WarnMissingMethods) )
53 import SrcLoc           ( srcLocSpan, unLoc, noLoc, Located(..), srcSpanStart,
54                           getLoc)
55 import ListSetOps       ( minusList )
56 import Outputable
57 import Bag
58 import BasicTypes       ( Activation( AlwaysActive ), InlineSpec(..) )
59 import HscTypes         ( implicitTyThings )
60 import FastString
61 \end{code}
62
63 Typechecking instance declarations is done in two passes. The first
64 pass, made by @tcInstDecls1@, collects information to be used in the
65 second pass.
66
67 This pre-processed info includes the as-yet-unprocessed bindings
68 inside the instance declaration.  These are type-checked in the second
69 pass, when the class-instance envs and GVE contain all the info from
70 all the instance and value decls.  Indeed that's the reason we need
71 two passes over the instance decls.
72
73 Here is the overall algorithm.
74 Assume that we have an instance declaration
75
76     instance c => k (t tvs) where b
77
78 \begin{enumerate}
79 \item
80 $LIE_c$ is the LIE for the context of class $c$
81 \item
82 $betas_bar$ is the free variables in the class method type, excluding the
83    class variable
84 \item
85 $LIE_cop$ is the LIE constraining a particular class method
86 \item
87 $tau_cop$ is the tau type of a class method
88 \item
89 $LIE_i$ is the LIE for the context of instance $i$
90 \item
91 $X$ is the instance constructor tycon
92 \item
93 $gammas_bar$ is the set of type variables of the instance
94 \item
95 $LIE_iop$ is the LIE for a particular class method instance
96 \item
97 $tau_iop$ is the tau type for this instance of a class method
98 \item
99 $alpha$ is the class variable
100 \item
101 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
102 \item
103 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
104 \end{enumerate}
105
106 ToDo: Update the list above with names actually in the code.
107
108 \begin{enumerate}
109 \item
110 First, make the LIEs for the class and instance contexts, which means
111 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
112 and make LIElistI and LIEI.
113 \item
114 Then process each method in turn.
115 \item
116 order the instance methods according to the ordering of the class methods
117 \item
118 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
119 \item
120 Create final dictionary function from bindings generated already
121 \begin{pseudocode}
122 df = lambda inst_tyvars
123        lambda LIEI
124          let Bop1
125              Bop2
126              ...
127              Bopn
128          and dbinds_super
129               in <op1,op2,...,opn,sd1,...,sdm>
130 \end{pseudocode}
131 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
132 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
133 \end{enumerate}
134
135
136 %************************************************************************
137 %*                                                                      *
138 \subsection{Extracting instance decls}
139 %*                                                                      *
140 %************************************************************************
141
142 Gather up the instance declarations from their various sources
143
144 \begin{code}
145 tcInstDecls1    -- Deal with both source-code and imported instance decls
146    :: [LTyClDecl Name]          -- For deriving stuff
147    -> [LInstDecl Name]          -- Source code instance decls
148    -> TcM (TcGblEnv,            -- The full inst env
149            [InstInfo],          -- Source-code instance decls to process; 
150                                 -- contains all dfuns for this module
151            HsValBinds Name)     -- Supporting bindings for derived instances
152
153 tcInstDecls1 tycl_decls inst_decls
154   = checkNoErrs $
155     do {        -- Stop if addInstInfos etc discovers any errors
156                 -- (they recover, so that we get more than one error each
157                 -- round) 
158
159                 -- (1) Do class instance declarations and instances of indexed
160                 --     types 
161        ; let { idxty_decls = filter (isIdxTyDecl . unLoc) tycl_decls }
162        ; local_info_tycons <- mappM tcLocalInstDecl1  inst_decls
163        ; idxty_info_tycons <- mappM tcIdxTyInstDeclTL idxty_decls
164
165        ; let { (local_infos,
166                 local_tycons)    = unzip local_info_tycons
167              ; (idxty_infos, 
168                 idxty_tycons)    = unzip idxty_info_tycons
169              ; local_idxty_info  = concat local_infos ++ catMaybes idxty_infos
170              ; local_idxty_tycon = concat local_tycons ++ 
171                                    catMaybes idxty_tycons
172              ; clas_decls        = filter (isClassDecl.unLoc) tycl_decls 
173              ; implicit_things   = concatMap implicitTyThings local_idxty_tycon
174              }
175
176                 -- (2) Add the tycons of associated types and their implicit
177                 --     tythings to the global environment
178        ; tcExtendGlobalEnv (local_idxty_tycon ++ implicit_things) $ do {
179
180                 -- (3) Instances from generic class declarations
181        ; generic_inst_info <- getGenericInstances clas_decls
182
183                 -- Next, construct the instance environment so far, consisting
184                 -- of 
185                 --   a) local instance decls
186                 --   b) generic instances
187        ; addInsts local_idxty_info  $ do {
188        ; addInsts generic_inst_info $ do {
189
190                 -- (4) Compute instances from "deriving" clauses; 
191                 -- This stuff computes a context for the derived instance
192                 -- decl, so it needs to know about all the instances possible
193        ; (deriv_inst_info, deriv_binds) <- tcDeriving tycl_decls
194        ; addInsts deriv_inst_info   $ do {
195
196        ; gbl_env <- getGblEnv
197        ; returnM (gbl_env, 
198                   generic_inst_info ++ deriv_inst_info ++ local_idxty_info,
199                   deriv_binds) 
200     }}}}}
201   where
202     -- Make sure that toplevel type instance are not for associated types.
203     -- !!!TODO: Need to perform this check for the InstInfo structures of type
204     --          functions, too.
205     tcIdxTyInstDeclTL ldecl@(L loc decl) =
206       do { (info, tything) <- tcIdxTyInstDecl ldecl
207          ; setSrcSpan loc $
208              when (isAssocFamily tything) $
209                addErr $ assocInClassErr (tcdName decl)
210          ; return (info, tything)
211          }
212     isAssocFamily (Just (ATyCon tycon)) =
213       case tyConFamInst_maybe tycon of
214         Nothing       -> panic "isAssocFamily: no family?!?"
215         Just (fam, _) -> isTyConAssoc fam
216     isAssocFamily (Just _             ) = panic "isAssocFamily: no tycon?!?"
217     isAssocFamily Nothing               = False
218
219 assocInClassErr name = 
220   ptext SLIT("Associated type") <+> quotes (ppr name) <+> 
221   ptext SLIT("must be inside a class instance")
222
223 addInsts :: [InstInfo] -> TcM a -> TcM a
224 addInsts infos thing_inside
225   = tcExtendLocalInstEnv (map iSpec infos) thing_inside
226 \end{code} 
227
228 \begin{code}
229 tcLocalInstDecl1 :: LInstDecl Name 
230                  -> TcM ([InstInfo], [TyThing]) -- [] if there was an error
231         -- A source-file instance declaration
232         -- Type-check all the stuff before the "where"
233         --
234         -- We check for respectable instance type, and context
235 tcLocalInstDecl1 decl@(L loc (InstDecl poly_ty binds uprags ats))
236   =     -- Prime error recovery, set source location
237     recoverM (returnM ([], []))         $
238     setSrcSpan loc                      $
239     addErrCtxt (instDeclCtxt1 poly_ty)  $
240
241     do  { is_boot <- tcIsHsBoot
242         ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags))
243                   badBootDeclErr
244
245         -- Typecheck the instance type itself.  We can't use 
246         -- tcHsSigType, because it's not a valid user type.
247         ; kinded_ty <- kcHsSigType poly_ty
248         ; poly_ty'  <- tcHsKindedType kinded_ty
249         ; let (tyvars, theta, tau) = tcSplitSigmaTy poly_ty'
250         
251         -- Next, process any associated types.
252         ; idxty_info_tycons <- mappM tcIdxTyInstDecl ats
253
254         -- Now, check the validity of the instance.
255         ; (clas, inst_tys) <- checkValidInstHead tau
256         ; checkValidInstance tyvars theta clas inst_tys
257         ; checkValidAndMissingATs clas (tyvars, inst_tys) 
258                                   (zip ats idxty_info_tycons)
259
260         -- Finally, construct the Core representation of the instance.
261         -- (This no longer includes the associated types.)
262         ; dfun_name <- newDFunName clas inst_tys (srcSpanStart loc)
263         ; overlap_flag <- getOverlapFlag
264         ; let dfun           = mkDictFunId dfun_name tyvars theta clas inst_tys
265               ispec          = mkLocalInstance dfun overlap_flag
266               (idxty_infos, 
267                idxty_tycons) = unzip idxty_info_tycons
268
269         ; return ([InstInfo { iSpec  = ispec, 
270                               iBinds = VanillaInst binds uprags }] ++
271                   catMaybes idxty_infos,
272                   catMaybes idxty_tycons)
273         }
274   where
275     -- We pass in the source form and the type checked form of the ATs.  We
276     -- really need the source form only to be able to produce more informative
277     -- error messages.
278     checkValidAndMissingATs :: Class
279                             -> ([TyVar], [TcType])     -- instance types
280                             -> [(LTyClDecl Name,       -- source form of AT
281                                  (Maybe InstInfo,      -- Core form for type
282                                   Maybe TyThing))]     -- Core form for data
283                             -> TcM ()
284     checkValidAndMissingATs clas inst_tys ats
285       = do { -- Issue a warning for each class AT that is not defined in this
286              -- instance.
287            ; let classDefATs = listToNameSet . map tyConName . classATs $ clas
288                  definedATs  = listToNameSet . map (tcdName.unLoc.fst)  $ ats
289                  omitted     = classDefATs `minusNameSet` definedATs
290            ; warn <- doptM Opt_WarnMissingMethods
291            ; mapM_ (warnTc warn . omittedATWarn) (nameSetToList omitted)
292            
293              -- Ensure that all AT indexes that correspond to class parameters
294              -- coincide with the types in the instance head.  All remaining
295              -- AT arguments must be variables.  Also raise an error for any
296              -- type instances that are not associated with this class.
297            ; mapM_ (checkIndexes clas inst_tys) ats
298            }
299
300     checkIndexes _    _        (hsAT, (Nothing, Nothing))              = 
301       return ()    -- skip, we already had an error here
302     checkIndexes clas inst_tys (hsAT, (Just _  , Nothing            )) = 
303       panic "do impl for AT syns"  -- !!!TODO: also call checkIndexes'
304     checkIndexes clas inst_tys (hsAT, (Nothing , Just (ATyCon tycon))) = 
305       checkIndexes' clas inst_tys hsAT 
306                     (tyConTyVars tycon, 
307                      snd . fromJust . tyConFamInst_maybe $ tycon)
308     checkIndexes _ _ _ = panic "checkIndexes"
309
310     checkIndexes' clas (instTvs, instTys) hsAT (atTvs, atTys)
311       = let atName = tcdName . unLoc $ hsAT
312         in
313         setSrcSpan (getLoc hsAT)       $
314         addErrCtxt (atInstCtxt atName) $
315         case find ((atName ==) . tyConName) (classATs clas) of
316           Nothing     -> addErrTc $ badATErr clas atName  -- not in this class
317           Just atDecl -> 
318             case assocTyConArgPoss_maybe atDecl of
319               Nothing   -> panic "checkIndexes': AT has no args poss?!?"
320               Just poss -> 
321
322                 -- The following is tricky!  We need to deal with three
323                 -- complications: (1) The AT possibly only uses a subset of
324                 -- the class parameters as indexes and those it uses may be in
325                 -- a different order; (2) the AT may have extra arguments,
326                 -- which must be type variables; and (3) variables in AT and
327                 -- instance head will be different `Name's even if their
328                 -- source lexemes are identical.
329                 --
330                 -- Re (1), `poss' contains a permutation vector to extract the
331                 -- class parameters in the right order.
332                 --
333                 -- Re (2), we wrap the (permuted) class parameters in a Maybe
334                 -- type and use Nothing for any extra AT arguments.  (First
335                 -- equation of `checkIndex' below.)
336                 --
337                 -- Re (3), we replace any type variable in the AT parameters
338                 -- that has the same source lexeme as some variable in the
339                 -- instance types with the instance type variable sharing its
340                 -- source lexeme.
341                 --
342                 let relevantInstTys = map (instTys !!) poss
343                     instArgs        = map Just relevantInstTys ++ 
344                                       repeat Nothing  -- extra arguments
345                     renaming        = substSameTyVar atTvs instTvs
346                 in
347                 zipWithM_ checkIndex (substTys renaming atTys) instArgs
348
349     checkIndex ty Nothing 
350       | isTyVarTy ty         = return ()
351       | otherwise            = addErrTc $ mustBeVarArgErr ty
352     checkIndex ty (Just instTy) 
353       | ty `tcEqType` instTy = return ()
354       | otherwise            = addErrTc $ wrongATArgErr ty instTy
355
356     listToNameSet = addListToNameSet emptyNameSet 
357
358     substSameTyVar []       _            = emptyTvSubst
359     substSameTyVar (tv:tvs) replacingTvs = 
360       let replacement = case find (tv `sameLexeme`) replacingTvs of
361                           Nothing  -> mkTyVarTy tv
362                           Just rtv -> mkTyVarTy rtv
363           --
364           tv1 `sameLexeme` tv2 = 
365             nameOccName (tyVarName tv1) == nameOccName (tyVarName tv2)
366       in
367       extendTvSubst (substSameTyVar tvs replacingTvs) tv replacement
368 \end{code}
369
370
371 %************************************************************************
372 %*                                                                      *
373 \subsection{Type-checking instance declarations, pass 2}
374 %*                                                                      *
375 %************************************************************************
376
377 \begin{code}
378 tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo] 
379              -> TcM (LHsBinds Id, TcLclEnv)
380 -- (a) From each class declaration, 
381 --      generate any default-method bindings
382 -- (b) From each instance decl
383 --      generate the dfun binding
384
385 tcInstDecls2 tycl_decls inst_decls
386   = do  {       -- (a) Default methods from class decls
387           (dm_binds_s, dm_ids_s) <- mapAndUnzipM tcClassDecl2 $
388                                     filter (isClassDecl.unLoc) tycl_decls
389         ; tcExtendIdEnv (concat dm_ids_s)       $ do 
390     
391                 -- (b) instance declarations
392         ; inst_binds_s <- mappM tcInstDecl2 inst_decls
393
394                 -- Done
395         ; let binds = unionManyBags dm_binds_s `unionBags` 
396                       unionManyBags inst_binds_s
397         ; tcl_env <- getLclEnv          -- Default method Ids in here
398         ; returnM (binds, tcl_env) }
399 \end{code}
400
401 ======= New documentation starts here (Sept 92)  ==============
402
403 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
404 the dictionary function for this instance declaration.  For example
405 \begin{verbatim}
406         instance Foo a => Foo [a] where
407                 op1 x = ...
408                 op2 y = ...
409 \end{verbatim}
410 might generate something like
411 \begin{verbatim}
412         dfun.Foo.List dFoo_a = let op1 x = ...
413                                    op2 y = ...
414                                in
415                                    Dict [op1, op2]
416 \end{verbatim}
417
418 HOWEVER, if the instance decl has no context, then it returns a
419 bigger @HsBinds@ with declarations for each method.  For example
420 \begin{verbatim}
421         instance Foo [a] where
422                 op1 x = ...
423                 op2 y = ...
424 \end{verbatim}
425 might produce
426 \begin{verbatim}
427         dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
428         const.Foo.op1.List a x = ...
429         const.Foo.op2.List a y = ...
430 \end{verbatim}
431 This group may be mutually recursive, because (for example) there may
432 be no method supplied for op2 in which case we'll get
433 \begin{verbatim}
434         const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
435 \end{verbatim}
436 that is, the default method applied to the dictionary at this type.
437
438 What we actually produce in either case is:
439
440         AbsBinds [a] [dfun_theta_dicts]
441                  [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
442                  { d = (sd1,sd2, ..., op1, op2, ...)
443                    op1 = ...
444                    op2 = ...
445                  }
446
447 The "maybe" says that we only ask AbsBinds to make global constant methods
448 if the dfun_theta is empty.
449
450                 
451 For an instance declaration, say,
452
453         instance (C1 a, C2 b) => C (T a b) where
454                 ...
455
456 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
457 function whose type is
458
459         (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
460
461 Notice that we pass it the superclass dictionaries at the instance type; this
462 is the ``Mark Jones optimisation''.  The stuff before the "=>" here
463 is the @dfun_theta@ below.
464
465 First comes the easy case of a non-local instance decl.
466
467
468 \begin{code}
469 tcInstDecl2 :: InstInfo -> TcM (LHsBinds Id)
470 -- Returns a binding for the dfun
471
472 ------------------------
473 -- Derived newtype instances
474 --
475 -- We need to make a copy of the dictionary we are deriving from
476 -- because we may need to change some of the superclass dictionaries
477 -- see Note [Newtype deriving superclasses] in TcDeriv.lhs
478 --
479 -- In the case of a newtype, things are rather easy
480 --      class Show a => Foo a b where ...
481 --      newtype T a = MkT (Tree [a]) deriving( Foo Int )
482 -- The newtype gives an FC axiom looking like
483 --      axiom CoT a ::  T a :=: Tree [a]
484 --
485 -- So all need is to generate a binding looking like
486 --      dfunFooT :: forall a. (Foo Int (Tree [a], Show (T a)) => Foo Int (T a)
487 --      dfunFooT = /\a. \(ds:Show (T a)) (df:Foo (Tree [a])).
488 --                case df `cast` (Foo Int (sym (CoT a))) of
489 --                   Foo _ op1 .. opn -> Foo ds op1 .. opn
490
491 tcInstDecl2 (InstInfo { iSpec = ispec, 
492                         iBinds = NewTypeDerived tycon rep_tys })
493   = do  { let dfun_id      = instanceDFunId ispec 
494               rigid_info   = InstSkol dfun_id
495               origin       = SigOrigin rigid_info
496               inst_ty      = idType dfun_id
497         ; inst_loc <- getInstLoc origin
498         ; (tvs, theta, inst_head) <- tcSkolSigType rigid_info inst_ty
499         ; dicts <- newDictBndrs inst_loc theta
500         ; uniqs <- newUniqueSupply
501         ; let (cls, cls_inst_tys) = tcSplitDFunHead inst_head
502         ; this_dict <- newDictBndr inst_loc (mkClassPred cls rep_tys)
503         ; let (rep_dict_id:sc_dict_ids)
504                  | null dicts = [instToId this_dict]
505                  | otherwise  = map instToId dicts
506
507                 -- (Here, we are relying on the order of dictionary 
508                 -- arguments built by NewTypeDerived in TcDeriv.)
509
510               wrap_fn = mkCoTyLams tvs <.> mkCoLams (rep_dict_id:sc_dict_ids)
511            
512                 -- we need to find the kind that this class applies to
513                 -- and drop trailing tvs appropriately
514               cls_kind = tyVarKind (head (reverse (tyConTyVars cls_tycon)))
515               the_tvs  = drop_tail (length (fst (splitFunTys cls_kind))) tvs
516
517               coerced_rep_dict = mkHsCoerce (co_fn the_tvs cls_tycon cls_inst_tys) (HsVar rep_dict_id)
518
519               body | null sc_dict_ids = coerced_rep_dict
520                    | otherwise = HsCase (noLoc coerced_rep_dict) $
521                                  MatchGroup [the_match] (mkFunTy in_dict_ty inst_head)
522               in_dict_ty = mkTyConApp cls_tycon cls_inst_tys
523
524               the_match = mkSimpleMatch [noLoc the_pat] the_rhs
525               the_rhs = mkHsConApp cls_data_con cls_inst_tys (map HsVar (sc_dict_ids ++ op_ids))
526
527               (uniqs1, uniqs2) = splitUniqSupply uniqs
528
529               op_ids = zipWith (mkSysLocal FSLIT("op"))
530                                       (uniqsFromSupply uniqs1) op_tys
531
532               dict_ids = zipWith (mkSysLocal FSLIT("dict"))
533                           (uniqsFromSupply uniqs2) (map idType sc_dict_ids)
534
535               the_pat = ConPatOut { pat_con = noLoc cls_data_con, pat_tvs = [],
536                                     pat_dicts = dict_ids,
537                                     pat_binds = emptyLHsBinds,
538                                     pat_args = PrefixCon (map nlVarPat op_ids),
539                                     pat_ty = in_dict_ty} 
540
541               cls_data_con = classDataCon cls
542               cls_tycon    = dataConTyCon cls_data_con
543               cls_arg_tys  = dataConInstArgTys cls_data_con cls_inst_tys 
544               
545               n_dict_args = if length dicts == 0 then 0 else length dicts - 1
546               op_tys = drop n_dict_args cls_arg_tys
547               
548               dict    = mkHsCoerce wrap_fn body
549         ; return (unitBag (noLoc $ VarBind dfun_id (noLoc dict))) }
550   where
551         -- For newtype T a = MkT <ty>
552         -- The returned coercion has kind :: C (T a):=:C <ty>
553     co_fn tvs cls_tycon cls_inst_tys | Just co_con <- newTyConCo tycon
554           = ExprCoFn (mkTyConApp cls_tycon (drop_tail 1 cls_inst_tys ++
555                       [mkSymCoercion (mkTyConApp co_con (map mkTyVarTy tvs))]))
556           | otherwise
557           = idCoercion
558     drop_tail n l = take (length l - n) l
559
560 ------------------------
561 -- Ordinary instances
562
563 tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = VanillaInst monobinds uprags })
564   = let 
565         dfun_id    = instanceDFunId ispec
566         rigid_info = InstSkol dfun_id
567         inst_ty    = idType dfun_id
568     in
569          -- Prime error recovery
570     recoverM (returnM emptyLHsBinds)            $
571     setSrcSpan (srcLocSpan (getSrcLoc dfun_id)) $
572     addErrCtxt (instDeclCtxt2 (idType dfun_id)) $
573
574         -- Instantiate the instance decl with skolem constants 
575     tcSkolSigType rigid_info inst_ty    `thenM` \ (inst_tyvars', dfun_theta', inst_head') ->
576                 -- These inst_tyvars' scope over the 'where' part
577                 -- Those tyvars are inside the dfun_id's type, which is a bit
578                 -- bizarre, but OK so long as you realise it!
579     let
580         (clas, inst_tys') = tcSplitDFunHead inst_head'
581         (class_tyvars, sc_theta, _, op_items) = classBigSig clas
582
583         -- Instantiate the super-class context with inst_tys
584         sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys') sc_theta
585         origin    = SigOrigin rigid_info
586     in
587          -- Create dictionary Ids from the specified instance contexts.
588     getInstLoc InstScOrigin                             `thenM` \ sc_loc -> 
589     newDictBndrs sc_loc sc_theta'                       `thenM` \ sc_dicts ->
590     getInstLoc origin                                   `thenM` \ inst_loc -> 
591     newDictBndrs inst_loc dfun_theta'                   `thenM` \ dfun_arg_dicts ->
592     newDictBndr inst_loc (mkClassPred clas inst_tys')   `thenM` \ this_dict ->
593                 -- Default-method Ids may be mentioned in synthesised RHSs,
594                 -- but they'll already be in the environment.
595
596         -- Typecheck the methods
597     let         -- These insts are in scope; quite a few, eh?
598         avail_insts = [this_dict] ++ dfun_arg_dicts ++ sc_dicts
599     in
600     tcMethods origin clas inst_tyvars' 
601               dfun_theta' inst_tys' avail_insts 
602               op_items monobinds uprags         `thenM` \ (meth_ids, meth_binds) ->
603
604         -- Figure out bindings for the superclass context
605         -- Don't include this_dict in the 'givens', else
606         -- sc_dicts get bound by just selecting  from this_dict!!
607     addErrCtxt superClassCtxt
608         (tcSimplifySuperClasses inst_tyvars'
609                          dfun_arg_dicts
610                          sc_dicts)      `thenM` \ sc_binds ->
611
612         -- It's possible that the superclass stuff might unified one
613         -- of the inst_tyavars' with something in the envt
614     checkSigTyVars inst_tyvars'         `thenM_`
615
616         -- Deal with 'SPECIALISE instance' pragmas 
617     tcPrags dfun_id (filter isSpecInstLSig uprags)      `thenM` \ prags -> 
618     
619         -- Create the result bindings
620     let
621         dict_constr   = classDataCon clas
622         scs_and_meths = map instToId sc_dicts ++ meth_ids
623         this_dict_id  = instToId this_dict
624         inline_prag | null dfun_arg_dicts = []
625                     | otherwise = [InlinePrag (Inline AlwaysActive True)]
626                 -- Always inline the dfun; this is an experimental decision
627                 -- because it makes a big performance difference sometimes.
628                 -- Often it means we can do the method selection, and then
629                 -- inline the method as well.  Marcin's idea; see comments below.
630                 --
631                 -- BUT: don't inline it if it's a constant dictionary;
632                 -- we'll get all the benefit without inlining, and we get
633                 -- a **lot** of code duplication if we inline it
634                 --
635                 --      See Note [Inline dfuns] below
636
637         dict_rhs
638           = mkHsConApp dict_constr inst_tys' (map HsVar scs_and_meths)
639                 -- We don't produce a binding for the dict_constr; instead we
640                 -- rely on the simplifier to unfold this saturated application
641                 -- We do this rather than generate an HsCon directly, because
642                 -- it means that the special cases (e.g. dictionary with only one
643                 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
644                 -- than needing to be repeated here.
645
646         dict_bind  = noLoc (VarBind this_dict_id dict_rhs)
647         all_binds  = dict_bind `consBag` (sc_binds `unionBags` meth_binds)
648
649         main_bind = noLoc $ AbsBinds
650                             inst_tyvars'
651                             (map instToId dfun_arg_dicts)
652                             [(inst_tyvars', dfun_id, this_dict_id, 
653                                             inline_prag ++ prags)] 
654                             all_binds
655     in
656     showLIE (text "instance")           `thenM_`
657     returnM (unitBag main_bind)
658
659
660 tcMethods origin clas inst_tyvars' dfun_theta' inst_tys' 
661           avail_insts op_items monobinds uprags
662   =     -- Check that all the method bindings come from this class
663     let
664         sel_names = [idName sel_id | (sel_id, _) <- op_items]
665         bad_bndrs = collectHsBindBinders monobinds `minusList` sel_names
666     in
667     mappM (addErrTc . badMethodErr clas) bad_bndrs      `thenM_`
668
669         -- Make the method bindings
670     let
671         mk_method_bind = mkMethodBind origin clas inst_tys' monobinds
672     in
673     mapAndUnzipM mk_method_bind op_items        `thenM` \ (meth_insts, meth_infos) ->
674
675         -- And type check them
676         -- It's really worth making meth_insts available to the tcMethodBind
677         -- Consider     instance Monad (ST s) where
678         --                {-# INLINE (>>) #-}
679         --                (>>) = ...(>>=)...
680         -- If we don't include meth_insts, we end up with bindings like this:
681         --      rec { dict = MkD then bind ...
682         --            then = inline_me (... (GHC.Base.>>= dict) ...)
683         --            bind = ... }
684         -- The trouble is that (a) 'then' and 'dict' are mutually recursive, 
685         -- and (b) the inline_me prevents us inlining the >>= selector, which
686         -- would unravel the loop.  Result: (>>) ends up as a loop breaker, and
687         -- is not inlined across modules. Rather ironic since this does not
688         -- happen without the INLINE pragma!  
689         --
690         -- Solution: make meth_insts available, so that 'then' refers directly
691         --           to the local 'bind' rather than going via the dictionary.
692         --
693         -- BUT WATCH OUT!  If the method type mentions the class variable, then
694         -- this optimisation is not right.  Consider
695         --      class C a where
696         --        op :: Eq a => a
697         --
698         --      instance C Int where
699         --        op = op
700         -- The occurrence of 'op' on the rhs gives rise to a constraint
701         --      op at Int
702         -- The trouble is that the 'meth_inst' for op, which is 'available', also
703         -- looks like 'op at Int'.  But they are not the same.
704     let
705         prag_fn        = mkPragFun uprags
706         all_insts      = avail_insts ++ catMaybes meth_insts
707         sig_fn n       = Just []        -- No scoped type variables, but every method has
708                                         -- a type signature, in effect, so that we check
709                                         -- the method has the right type
710         tc_method_bind = tcMethodBind inst_tyvars' dfun_theta' all_insts sig_fn prag_fn
711         meth_ids       = [meth_id | (_,meth_id,_) <- meth_infos]
712     in
713
714     mapM tc_method_bind meth_infos              `thenM` \ meth_binds_s ->
715    
716     returnM (meth_ids, unionManyBags meth_binds_s)
717 \end{code}
718
719
720                 ------------------------------
721         [Inline dfuns] Inlining dfuns unconditionally
722                 ------------------------------
723
724 The code above unconditionally inlines dict funs.  Here's why.
725 Consider this program:
726
727     test :: Int -> Int -> Bool
728     test x y = (x,y) == (y,x) || test y x
729     -- Recursive to avoid making it inline.
730
731 This needs the (Eq (Int,Int)) instance.  If we inline that dfun
732 the code we end up with is good:
733
734     Test.$wtest =
735         \r -> case ==# [ww ww1] of wild {
736                 PrelBase.False -> Test.$wtest ww1 ww;
737                 PrelBase.True ->
738                   case ==# [ww1 ww] of wild1 {
739                     PrelBase.False -> Test.$wtest ww1 ww;
740                     PrelBase.True -> PrelBase.True [];
741                   };
742             };
743     Test.test = \r [w w1]
744             case w of w2 {
745               PrelBase.I# ww ->
746                   case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
747             };
748
749 If we don't inline the dfun, the code is not nearly as good:
750
751     (==) = case PrelTup.$fEq(,) PrelBase.$fEqInt PrelBase.$fEqInt of tpl {
752               PrelBase.:DEq tpl1 tpl2 -> tpl2;
753             };
754     
755     Test.$wtest =
756         \r [ww ww1]
757             let { y = PrelBase.I#! [ww1]; } in
758             let { x = PrelBase.I#! [ww]; } in
759             let { sat_slx = PrelTup.(,)! [y x]; } in
760             let { sat_sly = PrelTup.(,)! [x y];
761             } in
762               case == sat_sly sat_slx of wild {
763                 PrelBase.False -> Test.$wtest ww1 ww;
764                 PrelBase.True -> PrelBase.True [];
765               };
766     
767     Test.test =
768         \r [w w1]
769             case w of w2 {
770               PrelBase.I# ww ->
771                   case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
772             };
773
774 Why doesn't GHC inline $fEq?  Because it looks big:
775
776     PrelTup.zdfEqZ1T{-rcX-}
777         = \ @ a{-reT-} :: * @ b{-reS-} :: *
778             zddEq{-rf6-} _Ks :: {PrelBase.Eq{-23-} a{-reT-}}
779             zddEq1{-rf7-} _Ks :: {PrelBase.Eq{-23-} b{-reS-}} ->
780             let {
781               zeze{-rf0-} _Kl :: (b{-reS-} -> b{-reS-} -> PrelBase.Bool{-3c-})
782               zeze{-rf0-} = PrelBase.zeze{-01L-}@ b{-reS-} zddEq1{-rf7-} } in
783             let {
784               zeze1{-rf3-} _Kl :: (a{-reT-} -> a{-reT-} -> PrelBase.Bool{-3c-})
785               zeze1{-rf3-} = PrelBase.zeze{-01L-} @ a{-reT-} zddEq{-rf6-} } in
786             let {
787               zeze2{-reN-} :: ((a{-reT-}, b{-reS-}) -> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
788               zeze2{-reN-} = \ ds{-rf5-} _Ks :: (a{-reT-}, b{-reS-})
789                                ds1{-rf4-} _Ks :: (a{-reT-}, b{-reS-}) ->
790                              case ds{-rf5-}
791                              of wild{-reW-} _Kd { (a1{-rf2-} _Ks, a2{-reZ-} _Ks) ->
792                              case ds1{-rf4-}
793                              of wild1{-reX-} _Kd { (b1{-rf1-} _Ks, b2{-reY-} _Ks) ->
794                              PrelBase.zaza{-r4e-}
795                                (zeze1{-rf3-} a1{-rf2-} b1{-rf1-})
796                                (zeze{-rf0-} a2{-reZ-} b2{-reY-})
797                              }
798                              } } in     
799             let {
800               a1{-reR-} :: ((a{-reT-}, b{-reS-})-> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
801               a1{-reR-} = \ a2{-reV-} _Ks :: (a{-reT-}, b{-reS-})
802                             b1{-reU-} _Ks :: (a{-reT-}, b{-reS-}) ->
803                           PrelBase.not{-r6I-} (zeze2{-reN-} a2{-reV-} b1{-reU-})
804             } in
805               PrelBase.zdwZCDEq{-r8J-} @ (a{-reT-}, b{-reS-}) a1{-reR-} zeze2{-reN-})
806
807 and it's not as bad as it seems, because it's further dramatically
808 simplified: only zeze2 is extracted and its body is simplified.
809
810
811 %************************************************************************
812 %*                                                                      *
813 \subsection{Error messages}
814 %*                                                                      *
815 %************************************************************************
816
817 \begin{code}
818 instDeclCtxt1 hs_inst_ty 
819   = inst_decl_ctxt (case unLoc hs_inst_ty of
820                         HsForAllTy _ _ _ (L _ (HsPredTy pred)) -> ppr pred
821                         HsPredTy pred                    -> ppr pred
822                         other                            -> ppr hs_inst_ty)     -- Don't expect this
823 instDeclCtxt2 dfun_ty
824   = inst_decl_ctxt (ppr (mkClassPred cls tys))
825   where
826     (_,_,cls,tys) = tcSplitDFunTy dfun_ty
827
828 inst_decl_ctxt doc = ptext SLIT("In the instance declaration for") <+> quotes doc
829
830 superClassCtxt = ptext SLIT("When checking the super-classes of an instance declaration")
831
832 atInstCtxt name = ptext SLIT("In the associated type instance for") <+> 
833                   quotes (ppr name)
834
835 mustBeVarArgErr ty = 
836   sep [ ptext SLIT("Arguments that do not correspond to a class parameter")
837       , ptext SLIT("must be variables:") <+> ppr ty
838       ]
839
840 wrongATArgErr ty instTy =
841   sep [ ptext SLIT("Type indexes must match class instance head")
842       , ptext SLIT("Found") <+> ppr ty <+> ptext SLIT("but expected") <+>
843          ppr instTy
844       ]
845 \end{code}