Initial commit for Pedro's new generic default methods
[ghc-hetmet.git] / compiler / typecheck / TcInstDcls.lhs
index 571cd70..0ffc466 100644 (file)
@@ -12,6 +12,7 @@ import HsSyn
 import TcBinds
 import TcTyClsDecls
 import TcClassDcl
+import TcPat( addInlinePrags )
 import TcRnMonad
 import TcMType
 import TcType
@@ -19,10 +20,10 @@ import Inst
 import InstEnv
 import FamInst
 import FamInstEnv
+import MkCore  ( nO_METHOD_BINDING_ERROR_ID )
 import TcDeriv
 import TcEnv
 import RnSource ( addTcgDUs )
-import TcSimplify( simplifySuperClass )
 import TcHsType
 import TcUnify
 import Type
@@ -31,10 +32,10 @@ import TyCon
 import DataCon
 import Class
 import Var
-import VarSet    ( emptyVarSet )
+import VarSet
 import CoreUtils  ( mkPiTypes )
 import CoreUnfold ( mkDFunUnfolding )
-import CoreSyn   ( Expr(Var) )
+import CoreSyn    ( Expr(Var), DFunArg(..), CoreExpr )
 import Id
 import MkId
 import Name
@@ -181,13 +182,14 @@ Instead we use a cunning trick.
 Note [Single-method classes]
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 If the class has just one method (or, more accurately, just one element
-of {superclasses + methods}), then we still use the *same* strategy
+of {superclasses + methods}), then we use a different strategy.
 
    class C a where op :: a -> a
    instance C a => C [a] where op = <blah>
 
-We translate the class decl into a newtype, which just gives
-a top-level axiom:
+We translate the class decl into a newtype, which just gives a
+top-level axiom. The "constructor" MkC expands to a cast, as does the
+class-op selector.
 
    axiom Co:C a :: C a ~ (a->a)
 
@@ -197,44 +199,82 @@ a top-level axiom:
    MkC :: forall a. (a->a) -> C a
    MkC = /\a.\op. op |> (sym Co:C a)
 
-   df :: forall a. C a => C [a]
-   {-# NOINLINE df   DFun[ $cop_list ] #-}
-   df = /\a. \d. MkC ($cop_list a d)
+The clever RULE stuff doesn't work now, because ($df a d) isn't
+a constructor application, so exprIsConApp_maybe won't return 
+Just <blah>.
 
-   $cop_list :: forall a. C a => [a] -> [a]
-   $cop_list = <blah>
+Instead, we simply rely on the fact that casts are cheap:
 
-The "constructor" MkC expands to a cast, as does the class-op selector.
-The RULE works just like for multi-field dictionaries:
+   $df :: forall a. C a => C [a]
+   {-# INLINE df #}  -- NB: INLINE this
+   $df = /\a. \d. MkC [a] ($cop_list a d)
+       = $cop_list |> forall a. C a -> (sym (Co:C [a]))
 
-  * (df a d) returns (Just (MkC,..,[$cop_list a d])) 
-    to exprIsConApp_Maybe
+   $cop_list :: forall a. C a => [a] -> [a]
+   $cop_list = <blah>
 
-  * The RULE for op picks the right result
+So if we see
+   (op ($df a d))
+we'll inline 'op' and '$df', since both are simply casts, and
+good things happen.
 
-This is a bit of a hack, because (df a d) isn't *really* a constructor
-application.  But it works just fine in this case, exprIsConApp_maybe
-is otherwise used only when we hit a case expression which will have
-a real data constructor in it.
+Why do we use this different strategy?  Because otherwise we
+end up with non-inlined dictionaries that look like
+    $df = $cop |> blah
+which adds an extra indirection to every use, which seems stupid.  See
+Trac #4138 for an example (although the regression reported there
+wasn't due to the indirction).
 
-The biggest reason for doing it this way, apart from uniformity, is
-that we want to be very careful when we have
+There is an awkward wrinkle though: we want to be very 
+careful when we have
     instance C a => C [a] where
       {-# INLINE op #-}
       op = ...
 then we'll get an INLINE pragma on $cop_list but it's important that
 $cop_list only inlines when it's applied to *two* arguments (the
-dictionary and the list argument
+dictionary and the list argument).  So we nust not eta-expand $df
+above.  We ensure that this doesn't happen by putting an INLINE 
+pragma on the dfun itself; after all, it ends up being just a cast.
+
+There is one more dark corner to the INLINE story, even more deeply 
+buried.  Consider this (Trac #3772):
+
+    class DeepSeq a => C a where
+      gen :: Int -> a
+
+    instance C a => C [a] where
+      gen n = ...
+
+    class DeepSeq a where
+      deepSeq :: a -> b -> b
+
+    instance DeepSeq a => DeepSeq [a] where
+      {-# INLINE deepSeq #-}
+      deepSeq xs b = foldr deepSeq b xs
+
+That gives rise to these defns:
+
+    $cdeepSeq :: DeepSeq a -> [a] -> b -> b
+    -- User INLINE( 3 args )!
+    $cdeepSeq a (d:DS a) b (x:[a]) (y:b) = ...
+
+    $fDeepSeq[] :: DeepSeq a -> DeepSeq [a]
+    -- DFun (with auto INLINE pragma)
+    $fDeepSeq[] a d = $cdeepSeq a d |> blah
+
+    $cp1 a d :: C a => DeepSep [a]
+    -- We don't want to eta-expand this, lest
+    -- $cdeepSeq gets inlined in it!
+    $cp1 a d = $fDeepSep[] a (scsel a d)
 
-The danger is that we'll get something like
-      op_list :: C a => [a] -> [a]
-      op_list = /\a.\d. $cop_list a d
-and then we'll eta expand, and then we'll inline TOO EARLY. This happened in 
-Trac #3772 and I spent far too long fiddling around trying to fix it.
-Look at the test for Trac #3772.
+    $fC[] :: C a => C [a]
+    -- Ordinary DFun
+    $fC[] a d = MkC ($cp1 a d) ($cgen a d)
 
-     (Note: re-reading the above, I can't see how using the
-            uniform story solves the problem.)
+Here $cp1 is the code that generates the superclass for C [a].  The
+issue is this: we must not eta-expand $cp1 either, or else $fDeepSeq[]
+and then $cdeepSeq will inline there, which is definitely wrong.  Like
+on the dfun, we solve this by adding an INLINE pragma to $cp1.
 
 Note [Subtle interaction of recursion and overlap]
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -271,13 +311,12 @@ See the overlapping instances for RegexContext, and the fact that they
 call 'nullFail' just like the example above.  The DoCon package also
 does the same thing; it shows up in module Fraction.hs
 
-Conclusion: when typechecking the methods in a C [a] instance, we want
-to have C [a] available.  That is why we have the strange local
-definition for 'this' in the definition of op1_i in the example above.
-We can typecheck the defintion of local_op1, and when doing tcSimplifyCheck
-we supply 'this' as a given dictionary.  Only needed, though, if there
-are some type variables involved; otherwise there can be no overlap and
-none of this arises.
+Conclusion: when typechecking the methods in a C [a] instance, we want to
+treat the 'a' as an *existential* type variable, in the sense described
+by Note [Binding when looking up instances].  That is why isOverlappableTyVar
+responds True to an InstSkol, which is the kind of skolem we use in
+tcInstDecl2.
+
 
 Note [Tricky type variable scoping]
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -331,7 +370,7 @@ tcInstDecls1 tycl_decls inst_decls deriv_decls
        ; let { (local_info,
                 at_tycons_s)   = unzip local_info_tycons
              ; at_idx_tycons   = concat at_tycons_s ++ idx_tycons
-             ; clas_decls      = filter (isClassDecl.unLoc) tycl_decls
+             ; clas_decls      = filter (isClassDecl . unLoc) tycl_decls
              ; implicit_things = concatMap implicitTyThings at_idx_tycons
             ; aux_binds       = mkRecSelBinds at_idx_tycons
              }
@@ -358,12 +397,18 @@ tcInstDecls1 tycl_decls inst_decls deriv_decls
                 -- NB: class instance declarations can contain derivings as
                 --     part of associated data type declarations
         failIfErrsM            -- If the addInsts stuff gave any errors, don't
-                               -- try the deriving stuff, becuase that may give
+                               -- try the deriving stuff, because that may give
                                -- more errors still
-       ; (deriv_inst_info, deriv_binds, deriv_dus) 
+       ; (deriv_inst_info, deriv_binds, deriv_dus, deriv_tys, deriv_ty_insts) 
               <- tcDeriving tycl_decls inst_decls deriv_decls
-       ; gbl_env <- addInsts deriv_inst_info getGblEnv
-       ; return ( addTcgDUs gbl_env deriv_dus,
+
+       -- Extend the global environment also with the generated datatypes for
+       -- the generic representation
+       ; gbl_env <- addFamInsts (map ATyCon deriv_ty_insts) $
+                      tcExtendGlobalEnv (map ATyCon (deriv_tys ++ deriv_ty_insts)) $
+                        addInsts deriv_inst_info getGblEnv
+--       ; traceTc "Generic deriving" (vcat (map pprInstInfo deriv_inst_info))
+         ; return ( addTcgDUs gbl_env deriv_dus,
                   generic_inst_info ++ deriv_inst_info ++ local_info,
                   aux_binds `plusHsValBinds` deriv_binds)
     }}}
@@ -396,10 +441,8 @@ tcLocalInstDecl1 (L loc (InstDecl poly_ty binds uprags ats))
         ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags))
                   badBootDeclErr
 
-        ; (tyvars, theta, tau) <- tcHsInstHead poly_ty
-
-        -- Now, check the validity of the instance.
-        ; (clas, inst_tys) <- checkValidInstance poly_ty tyvars theta tau
+        ; (tyvars, theta, clas, inst_tys) <- tcHsInstHead poly_ty
+        ; checkValidInstance poly_ty tyvars theta clas inst_tys
 
         -- Next, process any associated types.
         ; idx_tycons <- recoverM (return []) $
@@ -419,8 +462,7 @@ tcLocalInstDecl1 (L loc (InstDecl poly_ty binds uprags ats))
               dfun           = mkDictFunId dfun_name tyvars theta' clas inst_tys
               ispec          = mkLocalInstance dfun overlap_flag
 
-        ; return (InstInfo { iSpec  = ispec,
-                             iBinds = VanillaInst binds uprags False },
+        ; return (InstInfo { iSpec  = ispec, iBinds = VanillaInst binds uprags False },
                   idx_tycons)
         }
   where
@@ -560,16 +602,6 @@ tcInstDecls2 tycl_decls inst_decls
 
           -- Done
         ; return (dm_binds `unionBags` unionManyBags inst_binds_s) }
-
-tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id)
-tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds })
-  = recoverM (return emptyLHsBinds)             $
-    setSrcSpan loc                              $
-    addErrCtxt (instDeclCtxt2 (idType dfun_id)) $ 
-    tc_inst_decl2 dfun_id ibinds
- where
-    dfun_id = instanceDFunId ispec
-    loc     = getSrcSpan dfun_id
 \end{code}
 
 See Note [Default methods and instances]
@@ -586,102 +618,117 @@ So right here in tcInstDecl2 we must re-extend the type envt with
 the default method Ids replete with their INLINE pragmas.  Urk.
 
 \begin{code}
-tc_inst_decl2 :: Id -> InstBindings Name -> TcM (LHsBinds Id)
--- Returns a binding for the dfun
-tc_inst_decl2 dfun_id inst_binds
- = do { let rigid_info = InstSkol
-            inst_ty    = idType dfun_id
-            loc        = getSrcSpan dfun_id
-
-        -- Instantiate the instance decl with skolem constants
-       ; (inst_tyvars', dfun_theta', inst_head') <- tcSkolSigType rigid_info inst_ty
-                -- These inst_tyvars' scope over the 'where' part
-                -- Those tyvars are inside the dfun_id's type, which is a bit
-                -- bizarre, but OK so long as you realise it!
-       ; let
-            (clas, inst_tys') = tcSplitDFunHead inst_head'
-            (class_tyvars, sc_theta, sc_sels, op_items) = classBigSig clas
-
-             -- Instantiate the super-class context with inst_tys
-            sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys') sc_theta
 
-         -- Create dictionary Ids from the specified instance contexts.
-       ; dfun_ev_vars <- newEvVars dfun_theta'
-       ; self_dict    <- newSelfDict clas inst_tys'
-                -- Default-method Ids may be mentioned in synthesised RHSs,
-                -- but they'll already be in the environment.
-
-       -- Cook up a binding for "self = df d1 .. dn",
-       -- to use in each method binding
-       -- Why?  See Note [Subtle interaction of recursion and overlap]
-       ; let self_ev_bind = EvBind self_dict $ 
-                            EvDFunApp dfun_id (mkTyVarTys inst_tyvars') dfun_ev_vars
+tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id)
+            -- Returns a binding for the dfun
+tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds })
+  = recoverM (return emptyLHsBinds)             $
+    setSrcSpan loc                              $
+    addErrCtxt (instDeclCtxt2 (idType dfun_id)) $ 
+    do {  -- Instantiate the instance decl with skolem constants
+       ; (inst_tyvars, dfun_theta, inst_head) <- tcSkolDFunType (idType dfun_id)
+       ; let (clas, inst_tys) = tcSplitDFunHead inst_head
+             (class_tyvars, sc_theta, _, op_items) = classBigSig clas
+             sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys) sc_theta
+             n_ty_args = length inst_tyvars
+             n_silent  = dfunNSilent dfun_id
+             (silent_theta, orig_theta) = splitAt n_silent dfun_theta
+
+       ; silent_ev_vars <- mapM newSilentGiven silent_theta
+       ; orig_ev_vars   <- newEvVars orig_theta
+       ; let dfun_ev_vars = silent_ev_vars ++ orig_ev_vars
+
+       ; (sc_dicts, sc_args)
+             <- mapAndUnzipM (tcSuperClass n_ty_args dfun_ev_vars) sc_theta'
+
+       -- Check that any superclasses gotten from a silent arguemnt
+       -- can be deduced from the originally-specified dfun arguments
+       ; ct_loc <- getCtLoc ScOrigin
+       ; _ <- checkConstraints skol_info inst_tyvars orig_ev_vars $
+              emitFlats $ listToBag $
+              [ mkEvVarX sc ct_loc | sc <- sc_dicts, isSilentEvVar sc ]
 
        -- Deal with 'SPECIALISE instance' pragmas
        -- See Note [SPECIALISE instance pragmas]
-       ; spec_info <- tcSpecInstPrags dfun_id inst_binds
+       ; spec_info@(spec_inst_prags,_) <- tcSpecInstPrags dfun_id ibinds
 
         -- Typecheck the methods
        ; (meth_ids, meth_binds) 
-           <- tcExtendTyVarEnv inst_tyvars' $
-              tcInstanceMethods dfun_id clas inst_tyvars' dfun_ev_vars 
-                               inst_tys' self_ev_bind spec_info
-                                op_items inst_binds
-
-         -- Figure out bindings for the superclass context
-       ; let tc_sc = tcSuperClass inst_tyvars' dfun_ev_vars self_ev_bind
-             (sc_eqs, sc_dicts) = splitAt (classSCNEqs clas) sc_theta'
-       ; (sc_dict_ids, sc_binds) <- ASSERT( equalLength sc_sels sc_dicts )
-                                    ASSERT( all isEqPred sc_eqs )
-                                    mapAndUnzipM tc_sc (sc_sels `zip` sc_dicts)
-
-                                   -- NOT FINISHED!
-       ; (_eq_sc_binds, sc_eq_vars) <- checkConstraints InstSkol emptyVarSet 
-                                           inst_tyvars' dfun_ev_vars $
-                                      emitWanteds ScOrigin sc_eqs
+           <- tcExtendTyVarEnv inst_tyvars $
+                -- The inst_tyvars scope over the 'where' part
+                -- Those tyvars are inside the dfun_id's type, which is a bit
+                -- bizarre, but OK so long as you realise it!
+              tcInstanceMethods dfun_id clas inst_tyvars dfun_ev_vars
+                                inst_tys spec_info
+                                op_items ibinds
 
        -- Create the result bindings
-       ; let dict_constr       = classDataCon clas
-            dict_bind         = mkVarBind self_dict dict_rhs
-             dict_rhs          = foldl mk_app inst_constr dict_and_meth_ids
-             dict_and_meth_ids = sc_dict_ids ++ meth_ids
-            inst_constr   = L loc $ wrapId (mkWpEvVarApps sc_eq_vars 
-                                             <.> mkWpTyApps inst_tys')
-                                           (dataConWrapId dict_constr)
+       ; self_dict <- newEvVar (ClassP clas inst_tys)
+       ; let class_tc      = classTyCon clas
+             [dict_constr] = tyConDataCons class_tc
+             dict_bind     = mkVarBind self_dict dict_rhs
+             dict_rhs      = foldl mk_app inst_constr $
+                             map HsVar sc_dicts ++ map (wrapId arg_wrapper) meth_ids
+             inst_constr   = L loc $ wrapId (mkWpTyApps inst_tys)
+                                            (dataConWrapId dict_constr)
                      -- We don't produce a binding for the dict_constr; instead we
                      -- rely on the simplifier to unfold this saturated application
                      -- We do this rather than generate an HsCon directly, because
                      -- it means that the special cases (e.g. dictionary with only one
-                     -- member) are dealt with by the common MkId.mkDataConWrapId code rather
-                     -- than needing to be repeated here.
+                     -- member) are dealt with by the common MkId.mkDataConWrapId 
+                    -- code rather than needing to be repeated here.
+
+             mk_app :: LHsExpr Id -> HsExpr Id -> LHsExpr Id
+             mk_app fun arg = L loc (HsApp fun (L loc arg))
 
-            mk_app :: LHsExpr Id -> Id -> LHsExpr Id
-            mk_app fun arg_id = L loc (HsApp fun (L loc (wrapId arg_wrapper arg_id)))
-            arg_wrapper = mkWpEvVarApps dfun_ev_vars <.> mkWpTyApps (mkTyVarTys inst_tyvars')
+             arg_wrapper = mkWpEvVarApps dfun_ev_vars <.> mkWpTyApps (mkTyVarTys inst_tyvars)
 
                -- Do not inline the dfun; instead give it a magic DFunFunfolding
                -- See Note [ClassOp/DFun selection]
                -- See also note [Single-method classes]
-             dfun_id_w_fun = dfun_id  
-                             `setIdUnfolding`  mkDFunUnfolding inst_ty (map Var dict_and_meth_ids)
-                                                       -- Not right for equality superclasses
-                             `setInlinePragma` dfunInlinePragma
-
-             (spec_inst_prags, _) = spec_info
-             main_bind = AbsBinds { abs_tvs = inst_tyvars'
+             dfun_id_w_fun
+                | isNewTyCon class_tc
+                = dfun_id `setInlinePragma` alwaysInlinePragma { inl_sat = Just 0 }
+                | otherwise
+                = dfun_id `setIdUnfolding`  mkDFunUnfolding dfun_ty (sc_args ++ meth_args)
+                          `setInlinePragma` dfunInlinePragma
+             meth_args = map (DFunPolyArg . Var) meth_ids
+
+             main_bind = AbsBinds { abs_tvs = inst_tyvars
                                   , abs_ev_vars = dfun_ev_vars
-                                  , abs_exports = [(inst_tyvars', dfun_id_w_fun, self_dict, 
+                                  , abs_exports = [(inst_tyvars, dfun_id_w_fun, self_dict,
                                                     SpecPrags spec_inst_prags)]
                                   , abs_ev_binds = emptyTcEvBinds
                                   , abs_binds = unitBag dict_bind }
 
-       ; return (unitBag (L loc main_bind) `unionBags` 
-                listToBag meth_binds      `unionBags` 
-                 listToBag sc_binds)
+       ; return (unitBag (L loc main_bind) `unionBags`
+                 listToBag meth_binds)
        }
+ where
+   skol_info = InstSkol         -- See Note [Subtle interaction of recursion and overlap]
+   dfun_ty   = idType dfun_id
+   dfun_id   = instanceDFunId ispec
+   loc       = getSrcSpan dfun_id
+
+------------------------------
+tcSuperClass :: Int -> [EvVar] -> PredType -> TcM (EvVar, DFunArg CoreExpr)
+-- All superclasses should be either
+--   (a) be one of the arguments to the dfun, of
+--   (b) be a constant, soluble at top level
+tcSuperClass n_ty_args ev_vars pred
+  | Just (ev, i) <- find n_ty_args ev_vars
+  = return (ev, DFunLamArg i)
+  | otherwise
+  = ASSERT2( isEmptyVarSet (tyVarsOfPred pred), ppr pred)       -- Constant!
+    do { sc_dict  <- emitWanted ScOrigin pred
+       ; return (sc_dict, DFunConstArg (Var sc_dict)) }
+  where
+    find _ [] = Nothing
+    find i (ev:evs) | pred `tcEqPred` evVarPred ev = Just (ev, i)
+                    | otherwise                    = find (i+1) evs
 
 ------------------------------
-tcSpecInstPrags :: DFunId -> InstBindings Name 
+tcSpecInstPrags :: DFunId -> InstBindings Name
                 -> TcM ([Located TcSpecPrag], PragFun)
 tcSpecInstPrags _ (NewTypeDerived {})
   = return ([], \_ -> [])
@@ -690,52 +737,79 @@ tcSpecInstPrags dfun_id (VanillaInst binds uprags _)
                             filter isSpecInstLSig uprags
             -- The filter removes the pragmas for methods
        ; return (spec_inst_prags, mkPragFun uprags binds) }
-
-------------------------------
-tcSuperClass :: [TyVar] -> [EvVar]
-            -> EvBind
-            -> (Id, PredType) -> TcM (Id, LHsBind Id)
--- Build a top level decl like
---     sc_op = /\a \d. let this = ... in 
---                     let sc = ... in
---                     sc
--- The "this" part is just-in-case (discarded if not used)
--- See Note [Recursive superclasses]
-tcSuperClass tyvars dicts 
-             self_ev_bind@(EvBind self_dict _)
-            (sc_sel, sc_pred)
-  = do { (ev_binds, wanted, sc_dict)
-             <- newImplication InstSkol emptyVarSet tyvars dicts $
-                emitWanted ScOrigin sc_pred
-
-       ; simplifySuperClass self_dict wanted
-         -- We include self_dict in the 'givens'; the simplifier
-         -- is clever enough to stop sc_pred geting bound by just 
-         -- selecting from self_dict!!
-
-       ; uniq <- newUnique
-       ; let sc_op_ty   = mkForAllTys tyvars $ mkPiTypes dicts (varType sc_dict)
-            sc_op_name = mkDerivedInternalName mkClassOpAuxOcc uniq
-                                               (getName sc_sel)
-            sc_op_id   = mkLocalId sc_op_name sc_op_ty
-            sc_op_bind = VarBind { var_id = sc_op_id, var_inline = False
-                                  , var_rhs = L noSrcSpan $ wrapId sc_wrapper sc_dict }
-             sc_wrapper = mkWpTyLams tyvars
-                          <.> mkWpLams dicts
-                          <.> mkWpLet (EvBinds (unitBag self_ev_bind))
-                         <.> mkWpLet ev_binds
-
-       ; return (sc_op_id, noLoc sc_op_bind) }
 \end{code}
 
-Note [Recursive superclasses]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-See Trac #1470 for why we would *like* to add "self_dict" to the 
-available instances here.  But we can't do so because then the superclases
-get satisfied by selection from self_dict, and that leads to an immediate
-loop.  What we need is to add self_dict to Avails without adding its 
-superclasses, and we currently have no way to do that.
-
+Note [Silent Superclass Arguments]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Consider the following (extreme) situation:
+        class C a => D a where ...
+        instance D [a] => D [a] where ...
+Although this looks wrong (assume D [a] to prove D [a]), it is only a
+more extreme case of what happens with recursive dictionaries.
+
+To implement the dfun we must generate code for the superclass C [a],
+which we can get by superclass selection from the supplied argument!
+So we’d generate:
+       dfun :: forall a. D [a] -> D [a]
+       dfun = \d::D [a] -> MkD (scsel d) ..
+
+However this means that if we later encounter a situation where
+we have a [Wanted] dw::D [a] we could solve it thus:
+     dw := dfun dw
+Although recursive, this binding would pass the TcSMonadisGoodRecEv
+check because it appears as guarded.  But in reality, it will make a
+bottom superclass. The trouble is that isGoodRecEv can't "see" the
+superclass-selection inside dfun.
+
+Our solution to this problem is to change the way ‘dfuns’ are created
+for instances, so that we pass as first arguments to the dfun some
+``silent superclass arguments’’, which are the immediate superclasses
+of the dictionary we are trying to construct. In our example:
+       dfun :: forall a. (C [a], D [a] -> D [a]
+       dfun = \(dc::C [a]) (dd::D [a]) -> DOrd dc ...
+
+This gives us:
+
+     -----------------------------------------------------------
+     DFun Superclass Invariant
+     ~~~~~~~~~~~~~~~~~~~~~~~~
+     In the body of a DFun, every superclass argument to the
+     returned dictionary is
+       either   * one of the arguments of the DFun,
+       or       * constant, bound at top level
+     -----------------------------------------------------------
+
+This means that no superclass is hidden inside a dfun application, so
+the counting argument in isGoodRecEv (more dfun calls than superclass
+selections) works correctly.
+
+The extra arguments required to satisfy the DFun Superclass Invariant
+always come first, and are called the "silent" arguments.  DFun types
+are built (only) by MkId.mkDictFunId, so that is where we decide
+what silent arguments are to be added.
+
+This net effect is that it is safe to treat a dfun application as
+wrapping a dictionary constructor around its arguments (in particular,
+a dfun never picks superclasses from the arguments under the dictionary
+constructor).
+
+In our example, if we had  [Wanted] dw :: D [a] we would get via the instance:
+    dw := dfun d1 d2
+    [Wanted] (d1 :: C [a])
+    [Wanted] (d2 :: D [a])
+    [Derived] (d :: D [a])
+    [Derived] (scd :: C [a])   scd  := scsel d
+    [Derived] (scd2 :: C [a])  scd2 := scsel d2
+
+And now, though we *can* solve: 
+     d2 := dw
+we will get an isGoodRecEv failure when we try to solve:
+    d1 := scsel d 
+ or
+    d1 := scsel d2 
+
+Test case SCLoop tests this fix. 
+         
 Note [SPECIALISE instance pragmas]
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 Consider
@@ -783,11 +857,12 @@ tcSpecInst :: Id -> Sig Name -> TcM TcSpecPrag
 tcSpecInst dfun_id prag@(SpecInstSig hs_ty) 
   = addErrCtxt (spec_ctxt prag) $
     do  { let name = idName dfun_id
-        ; (tyvars, theta, tau) <- tcHsInstHead hs_ty   
-        ; let spec_ty = mkSigmaTy tyvars theta tau
-        ; co_fn <- tcSubType (SpecPragOrigin name) (SigSkol SpecInstCtxt) 
-                             (idType dfun_id) spec_ty
-        ; return (SpecPrag co_fn defaultInlinePragma) }
+        ; (tyvars, theta, clas, tys) <- tcHsInstHead hs_ty
+        ; let (_, spec_dfun_ty) = mkDictFunTy tyvars theta clas tys
+
+        ; co_fn <- tcSubType (SpecPragOrigin name) SpecInstCtxt
+                             (idType dfun_id) spec_dfun_ty
+        ; return (SpecPrag dfun_id co_fn defaultInlinePragma) }
   where
     spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
 
@@ -812,15 +887,14 @@ tcInstanceMethod
 tcInstanceMethods :: DFunId -> Class -> [TcTyVar]
                   -> [EvVar]
                  -> [TcType]
-                 -> EvBind               -- "This" and its binding
-                 -> ([Located TcSpecPrag], PragFun)
+                  -> ([Located TcSpecPrag], PragFun)
                  -> [(Id, DefMeth)]
                   -> InstBindings Name 
                  -> TcM ([Id], [LHsBind Id])
        -- The returned inst_meth_ids all have types starting
        --      forall tvs. theta => ...
 tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys 
-                 self_dict_ev (spec_inst_prags, prag_fn)
+                  (spec_inst_prags, prag_fn)
                   op_items (VanillaInst binds _ standalone_deriv)
   = mapAndUnzipM tc_item op_items
   where
@@ -834,27 +908,29 @@ tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys
     ----------------------
     tc_body :: Id -> Bool -> LHsBind Name -> TcM (TcId, LHsBind Id)
     tc_body sel_id generated_code rn_bind 
-      = add_meth_ctxt generated_code rn_bind $
+      = add_meth_ctxt sel_id generated_code rn_bind $
         do { (meth_id, local_meth_id) <- mkMethIds clas tyvars dfun_ev_vars 
                                                    inst_tys sel_id
-           ; (meth_id1, spec_prags) <- tcPrags NonRecursive False True 
-                                               meth_id (prag_fn (idName sel_id))
-
+           ; let prags = prag_fn (idName sel_id)
+           ; meth_id1 <- addInlinePrags meth_id prags
+           ; spec_prags <- tcSpecPrags meth_id1 prags
            ; bind <- tcInstanceMethodBody InstSkol
                           tyvars dfun_ev_vars
-                           mb_dict_ev
-                          meth_id1 local_meth_id
-                           meth_sig_fn 
-                          (SpecPrags (spec_inst_prags ++ spec_prags))
+                          meth_id1 local_meth_id meth_sig_fn 
+                          (mk_meth_spec_prags meth_id1 spec_prags)
                           rn_bind 
            ; return (meth_id1, bind) }
 
     ----------------------
     tc_default :: Id -> DefMeth -> TcM (TcId, LHsBind Id)
+
+    -- JPM: This is probably not that simple...
+    tc_default sel_id (GenDefMeth dm_name) = tc_default sel_id (DefMeth dm_name)
+{-
     tc_default sel_id GenDefMeth    -- Derivable type classes stuff
       = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id
            ; tc_body sel_id False {- Not generated code? -} meth_bind }
-         
+-}
     tc_default sel_id NoDefMeth            -- No default method at all
       = do { warnMissingMethod sel_id
           ; (meth_id, _) <- mkMethIds clas tyvars dfun_ev_vars 
@@ -873,30 +949,33 @@ tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys
       = do {   -- Build the typechecked version directly, 
                 -- without calling typecheck_method; 
                 -- see Note [Default methods in instances]
-                -- Generate   /\as.\ds. let this = df as ds 
-               --                      in $dm inst_tys this
+                 -- Generate   /\as.\ds. let self = df as ds
+                 --                      in $dm inst_tys self
                 -- The 'let' is necessary only because HsSyn doesn't allow
                 -- you to apply a function to a dictionary *expression*.
 
+           ; self_dict <- newEvVar (ClassP clas inst_tys)
+           ; let self_ev_bind = EvBind self_dict $
+                                EvDFunApp dfun_id (mkTyVarTys tyvars) dfun_ev_vars
+
            ; (meth_id, local_meth_id) <- mkMethIds clas tyvars dfun_ev_vars 
                                                    inst_tys sel_id
            ; dm_id <- tcLookupId dm_name
            ; let dm_inline_prag = idInlinePragma dm_id
-                 EvBind self_dict _ = self_dict_ev
                  rhs = HsWrap (mkWpEvVarApps [self_dict] <.> mkWpTyApps inst_tys) $
                         HsVar dm_id 
 
                 meth_bind = L loc $ VarBind { var_id = local_meth_id
                                              , var_rhs = L loc rhs 
-                                              , var_inline = False }
+                                             , var_inline = False }
                  meth_id1 = meth_id `setInlinePragma` dm_inline_prag
                            -- Copy the inline pragma (if any) from the default
                            -- method to this version. Note [INLINE and default methods]
                            
                  bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars =  dfun_ev_vars
                                  , abs_exports = [( tyvars, meth_id1, local_meth_id
-                                                  , SpecPrags spec_inst_prags)]
-                                 , abs_ev_binds = EvBinds (unitBag self_dict_ev)
+                                                  , mk_meth_spec_prags meth_id1 [])]
+                                 , abs_ev_binds = EvBinds (unitBag self_ev_bind)
                                  , abs_binds    = unitBag meth_bind }
             -- Default methods in an instance declaration can't have their own 
             -- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but
@@ -906,6 +985,18 @@ tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys
            ; return (meth_id1, L loc bind) } 
 
     ----------------------
+    mk_meth_spec_prags :: Id -> [LTcSpecPrag] -> TcSpecPrags
+       -- Adapt the SPECIALISE pragmas to work for this method Id
+        -- There are two sources: 
+        --   * spec_inst_prags: {-# SPECIALISE instance :: <blah> #-}
+        --     These ones have the dfun inside, but [perhaps surprisingly] 
+        --     the correct wrapper
+        --   * spec_prags_for_me: {-# SPECIALISE op :: <blah> #-}
+    mk_meth_spec_prags meth_id spec_prags_for_me
+      = SpecPrags (spec_prags_for_me ++ 
+                   [ L loc (SpecPrag meth_id wrap inl)
+                  | L loc (SpecPrag _ wrap inl) <- spec_inst_prags])
+   
     loc = getSrcSpan dfun_id
     meth_sig_fn _ = Just ([],loc)      -- The 'Just' says "yes, there's a type sig"
        -- But there are no scoped type variables from local_method_id
@@ -915,22 +1006,16 @@ tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys
        --      instance C [c] where { op = <rhs> }
        -- In <rhs>, 'c' is scope but 'b' is not!
 
-    mb_dict_ev = if null tyvars then Nothing else Just self_dict_ev
-               -- Only need the self_dict stuff if there are type 
-               -- variables involved; otherwise overlap is not possible
-               -- See Note [Subtle interaction of recursion and overlap]
-               -- in TcInstDcls
-
-       -- For instance decls that come from standalone deriving clauses
+        -- For instance decls that come from standalone deriving clauses
        -- we want to print out the full source code if there's an error
        -- because otherwise the user won't see the code at all
-    add_meth_ctxt generated_code rn_bind thing 
-      | generated_code = addLandmarkErrCtxt (derivBindCtxt clas inst_tys rn_bind) thing
+    add_meth_ctxt sel_id generated_code rn_bind thing 
+      | generated_code = addLandmarkErrCtxt (derivBindCtxt sel_id clas inst_tys rn_bind) thing
       | otherwise      = thing
 
 
 tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys 
-                 _ _ op_items (NewTypeDerived coi _)
+                  _ op_items (NewTypeDerived coi _)
 
 -- Running example:
 --   class Show b => Foo a b where
@@ -958,7 +1043,7 @@ tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys
 -- by the constraint solver, since the <context> may be
 -- user-specified.
 
-  = do { rep_d_stuff <- checkConstraints InstSkol emptyVarSet tyvars dfun_ev_vars $
+  = do { rep_d_stuff <- checkConstraints InstSkol tyvars dfun_ev_vars $
                         emitWanted ScOrigin rep_pred
                          
        ; mapAndUnzipM (tc_item rep_d_stuff) op_items }
@@ -1026,11 +1111,15 @@ mkMethIds clas tyvars dfun_ev_vars inst_tys sel_id
 wrapId :: HsWrapper -> id -> HsExpr id
 wrapId wrapper id = mkHsWrap wrapper (HsVar id)
 
-derivBindCtxt :: Class -> [Type ] -> LHsBind Name -> SDoc
-derivBindCtxt clas tys bind
-   = vcat [ ptext (sLit "When typechecking a standalone-derived method for")
-           <+> quotes (pprClassPred clas tys) <> colon
-         , nest 2 $ pprSetDepth AllTheWay $ ppr bind ]
+derivBindCtxt :: Id -> Class -> [Type ] -> LHsBind Name -> SDoc
+derivBindCtxt sel_id clas tys _bind
+   = vcat [ ptext (sLit "When typechecking the code for ") <+> quotes (ppr sel_id)
+          , nest 2 (ptext (sLit "in a standalone derived instance for")
+                   <+> quotes (pprClassPred clas tys) <> colon)
+          , nest 2 $ ptext (sLit "To see the code I am typechecking, use -ddump-deriv") ]
+
+-- Too voluminous
+--       , nest 2 $ pprSetDepth AllTheWay $ ppr bind ]
 
 warnMissingMethod :: Id -> TcM ()
 warnMissingMethod sel_id
@@ -1161,7 +1250,7 @@ instDeclCtxt2 :: Type -> SDoc
 instDeclCtxt2 dfun_ty
   = inst_decl_ctxt (ppr (mkClassPred cls tys))
   where
-    (_,cls,tys) = tcSplitDFunTy dfun_ty
+    (_,_,cls,tys) = tcSplitDFunTy dfun_ty
 
 inst_decl_ctxt :: SDoc -> SDoc
 inst_decl_ctxt doc = ptext (sLit "In the instance declaration for") <+> quotes doc