[project @ 2004-03-17 13:59:06 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcTyClsDecls.lhs
index 33c9cbd..311d2b1 100644 (file)
@@ -11,40 +11,46 @@ module TcTyClsDecls (
 #include "HsVersions.h"
 
 import HsSyn           ( TyClDecl(..),  HsConDetails(..), HsTyVarBndr(..),
-                         ConDecl(..),   Sig(..), BangType(..), HsBang(..),
-                         tyClDeclTyVars, getBangType, getBangStrictness
+                         ConDecl(..),   Sig(..), BangType(..), HsBang(..), NewOrData(..), 
+                         tyClDeclTyVars, getBangType, getBangStrictness, isSynDecl,
+                         LTyClDecl, tcdName, LHsTyVarBndr
                        )
-import RnHsSyn         ( RenamedTyClDecl, RenamedConDecl )
-import BasicTypes      ( RecFlag(..), NewOrData(..), StrictnessMark(..) )
+import BasicTypes      ( RecFlag(..), StrictnessMark(..) )
 import HscTypes                ( implicitTyThings )
-import BuildTyCl       ( buildClass, buildAlgTyCon, buildSynTyCon, buildDataCon )
+import BuildTyCl       ( buildClass, buildAlgTyCon, buildSynTyCon, buildDataCon,
+                         mkDataTyConRhs, mkNewTyConRhs )
 import TcRnMonad
 import TcEnv           ( TcTyThing(..), TyThing(..), 
-                         tcLookup, tcLookupGlobal, tcExtendGlobalEnv,
+                         tcLookupLocated, tcLookupLocatedGlobal, 
+                         tcExtendGlobalEnv, tcExtendKindEnv,
                          tcExtendRecEnv, tcLookupTyVar )
-import TcTyDecls       ( calcTyConArgVrcs, calcRecFlags, calcCycleErrs )
+import TcTyDecls       ( calcTyConArgVrcs, calcRecFlags, calcClassCycles, calcSynCycles )
 import TcClassDcl      ( tcClassSigs, tcAddDeclCtxt )
-import TcHsType                ( kcHsTyVars, kcHsLiftedSigType, kcHsSigType, kcCheckHsType, 
+import TcHsType                ( kcHsTyVars, kcHsLiftedSigType, kcHsSigType, kcHsType,
                          kcHsContext, tcTyVarBndrs, tcHsKindedType, tcHsKindedContext )
 import TcMType         ( newKindVar, checkValidTheta, checkValidType, checkFreeness, 
                          UserTypeCtxt(..), SourceTyCtxt(..) ) 
 import TcUnify         ( unifyKind )
-import TcType          ( TcKind, ThetaType, TcType,
+import TcType          ( TcKind, ThetaType, TcType, tyVarsOfType,
                          mkArrowKind, liftedTypeKind, 
                          tcSplitSigmaTy, tcEqType )
 import Type            ( splitTyConApp_maybe, pprThetaArrow, pprParendType )
 import FieldLabel      ( fieldLabelName, fieldLabelType )
 import Generics                ( validGenericMethodType, canDoGenerics )
-import Class           ( Class, className, classTyCon, DefMeth(..), classBigSig )
-import TyCon           ( TyCon, ArgVrcs, DataConDetails(..), 
+import Class           ( Class, className, classTyCon, DefMeth(..), classBigSig, classTyVars )
+import TyCon           ( TyCon, ArgVrcs, 
                          tyConDataCons, mkForeignTyCon, isProductTyCon, isRecursiveTyCon,
                          tyConTheta, getSynTyConDefn, tyConDataCons, isSynTyCon, tyConName )
 import DataCon         ( DataCon, dataConWrapId, dataConName, dataConSig, dataConFieldLabels )
 import Var             ( TyVar, idType, idName )
-import Name            ( Name, getSrcLoc )
+import VarSet          ( elemVarSet )
+import Name            ( Name )
 import Outputable
 import Util            ( zipLazy, isSingleton, notNull )
+import List            ( partition )
+import SrcLoc          ( Located(..), unLoc, getLoc )
 import ListSetOps      ( equivClasses )
+import Digraph         ( SCC(..) )
 import CmdLineOpts     ( DynFlag( Opt_GlasgowExts, Opt_Generics, Opt_UnboxStrictFields ) )
 \end{code}
 
@@ -99,7 +105,7 @@ The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
 @TyThing@s.  @rec_vrcs@ is a finite map from @Name@s to @ArgVrcs@s.
 
 \begin{code}
-tcTyAndClassDecls :: [RenamedTyClDecl]
+tcTyAndClassDecls :: [LTyClDecl Name]
                   -> TcM TcGblEnv      -- Input env extended by types and classes 
                                        -- and their implicit Ids,DataCons
 tcTyAndClassDecls decls
@@ -107,50 +113,51 @@ tcTyAndClassDecls decls
                -- See notes with checkCycleErrs
          checkCycleErrs decls
 
-       ; tyclss <- fixM (\ rec_tyclss ->
-         do    { lcl_things <- mappM getInitialKind decls
-                       -- Extend the local env with kinds, and
-                       -- the global env with the knot-tied results
-               ; let { gbl_things = mkGlobalThings decls rec_tyclss }
-               ; tcExtendRecEnv gbl_things lcl_things $ do     
-
-               -- The local type environment is populated with 
-               --              {"T" -> ARecTyCon k, ...}
-               -- and the global type envt with
-               --              {"T" -> ATyCon T, ...}
-               -- where k is T's (unzonked) kind
-               --       T is the loop-tied TyCon itself
-               -- We must populate the environment with the loop-tied T's right
-               -- away, because the kind checker may "fault in" some type 
-               -- constructors that recursively mention T
-
-               -- Kind-check the declarations, returning kind-annotated decls
-               { kc_decls <- mappM kcTyClDecl decls
-
-               -- Calculate variances and rec-flag
-               ; let { calc_vrcs = calcTyConArgVrcs rec_tyclss
-                     ; calc_rec  = calcRecFlags     rec_tyclss }
-                   
-               ; mappM (tcTyClDecl calc_vrcs calc_rec) kc_decls
-           }})
+       ; (syn_tycons, alg_tyclss) <- fixM (\ ~(rec_syn_tycons, rec_alg_tyclss) ->
+         do    { let { -- Calculate variances and rec-flag
+                     ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc) decls }
+
+                       -- Extend the global env with the knot-tied results
+                       -- for data types and classes
+                       -- 
+                       -- We must populate the environment with the loop-tied T's right
+                       -- away, because the kind checker may "fault in" some type 
+                       -- constructors that recursively mention T
+               ; let { gbl_things = mkGlobalThings alg_decls rec_alg_tyclss }
+               ; tcExtendRecEnv gbl_things $ do
+
+                       -- Kind-check the declarations
+               { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
+
+               ; let { calc_vrcs = calcTyConArgVrcs (rec_syn_tycons ++ rec_alg_tyclss)
+                     ; calc_rec  = calcRecFlags     rec_alg_tyclss
+                     ; tc_decl   = addLocM (tcTyClDecl calc_vrcs calc_rec) }
+                       -- Type-check the type synonyms, and extend the envt
+               ; syn_tycons <- tcSynDecls calc_vrcs kc_syn_decls
+               ; tcExtendGlobalEnv syn_tycons $ do
+
+                       -- Type-check the data types and classes
+               { alg_tyclss <- mappM tc_decl kc_alg_decls
+               ; return (syn_tycons, alg_tyclss)
+           }}})
        -- Finished with knot-tying now
        -- Extend the environment with the finished things
-       ; tcExtendGlobalEnv tyclss $ do
+       ; tcExtendGlobalEnv (syn_tycons ++ alg_tyclss) $ do
 
        -- Perform the validity check
        { traceTc (text "ready for validity check")
-       ; mappM_ checkValidTyCl decls
+       ; mappM_ (addLocM checkValidTyCl) decls
        ; traceTc (text "done")
    
        -- Add the implicit things;
        -- we want them in the environment because 
        -- they may be mentioned in interface files
-       ; let { implicit_things = concatMap implicitTyThings tyclss }
-       ; traceTc ((text "Adding" <+> ppr tyclss) $$ (text "and" <+> ppr implicit_things))
+       ; let { implicit_things = concatMap implicitTyThings alg_tyclss }
+       ; traceTc ((text "Adding" <+> ppr alg_tyclss) $$ (text "and" <+> ppr implicit_things))
        ; tcExtendGlobalEnv implicit_things getGblEnv
     }}
 
-mkGlobalThings :: [RenamedTyClDecl]    -- The decls
+mkGlobalThings :: [LTyClDecl Name]     -- The decls
               -> [TyThing]             -- Knot-tied, in 1-1 correspondence with the decls
               -> [(Name,TyThing)]
 -- Driven by the Decls, and treating the TyThings lazily
@@ -158,8 +165,10 @@ mkGlobalThings :: [RenamedTyClDecl]        -- The decls
 mkGlobalThings decls things
   = map mk_thing (decls `zipLazy` things)
   where
-    mk_thing (ClassDecl {tcdName = name}, ~(AClass cl)) = (name,         AClass cl)
-    mk_thing (decl,                      ~(ATyCon tc)) = (tcdName decl, ATyCon tc)
+    mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
+        = (name, AClass cl)
+    mk_thing (L _ decl, ~(ATyCon tc))
+         = (tcdName decl, ATyCon tc)
 \end{code}
 
 
@@ -182,55 +191,100 @@ Here, the kind of the locally-polymorphic type variable "b"
 depends on *all the uses of class D*.  For example, the use of
 Monad c in bop's type signature means that D must have kind Type->Type.
 
-\begin{code}
-------------------------------------------------------------------------
-getInitialKind :: TyClDecl Name -> TcM (Name, TcTyThing)
-
--- Note the lazy pattern match on the ATyCon etc
--- Exactly the same reason as the zipLay above
-
-getInitialKind (TyData {tcdName = name})
- = newKindVar                          `thenM` \ kind  ->
-   returnM (name, ARecTyCon kind)
-
-getInitialKind (TySynonym {tcdName = name})
- = newKindVar                          `thenM` \ kind  ->
-   returnM (name, ARecTyCon kind)
-
-getInitialKind (ClassDecl {tcdName = name})
- = newKindVar                          `thenM` \ kind  ->
-   returnM (name, ARecClass kind)
+However type synonyms work differently.  They can have kinds which don't
+just involve (->) and *:
+       type R = Int#           -- Kind #
+       type S a = Array# a     -- Kind * -> #
+       type T a b = (# a,b #)  -- Kind * -> * -> (# a,b #)
+So we must infer their kinds from their right-hand sides *first* and then
+use them, whereas for the mutually recursive data types D we bring into
+scope kind bindings D -> k, where k is a kind variable, and do inference.
 
+\begin{code}
+kcTyClDecls syn_decls alg_decls
+  = do {       -- First extend the kind env with each data 
+               -- type and class, mapping them to a type variable
+         alg_kinds <- mappM getInitialKind alg_decls
+       ; tcExtendKindEnv alg_kinds $ do
+
+               -- Now kind-check the type synonyms, in dependency order
+               -- We do these differently to data type and classes,
+               -- because a type synonym can be an unboxed type
+               --      type Foo = Int#
+               -- and a kind variable can't unify with UnboxedTypeKind
+               -- So we infer their kinds in dependency order
+       { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
+       ; tcExtendKindEnv syn_kinds $  do
+
+               -- Now kind-check the data type and class declarations, 
+               -- returning kind-annotated decls
+       { kc_alg_decls <- mappM (wrapLocM kcTyClDecl) alg_decls
+
+       ; return (kc_syn_decls, kc_alg_decls) }}}
 
 ------------------------------------------------------------------------
-kcTyClDecl :: RenamedTyClDecl -> TcM RenamedTyClDecl
+getInitialKind :: LTyClDecl Name -> TcM (Name, TcKind)
+
+getInitialKind decl
+ = newKindVar                  `thenM` \ kind  ->
+   returnM (unLoc (tcdLName (unLoc decl)), kind)
+
+----------------
+kcSynDecls :: [SCC (LTyClDecl Name)] 
+          -> TcM ([LTyClDecl Name],    -- Kind-annotated decls
+                  [(Name,TcKind)])     -- Kind bindings
+kcSynDecls []
+  = return ([], [])
+kcSynDecls (group : groups)
+  = do { (decl,  nk)  <- kcSynDecl group
+       ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
+       ; return (decl:decls, nk:nks) }
+                       
+----------------
+kcSynDecl :: SCC (LTyClDecl Name) 
+          -> TcM (LTyClDecl Name,      -- Kind-annotated decls
+                  (Name,TcKind))       -- Kind bindings
+kcSynDecl (AcyclicSCC ldecl@(L loc decl))
+  = tcAddDeclCtxt decl $
+    kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
+    do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl)) 
+                       <+> brackets (ppr k_tvs))
+       ; (k_rhs, rhs_kind) <- kcHsType (tcdSynRhs decl)
+       ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
+       ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
+       ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
+                (unLoc (tcdLName decl), tc_kind)) })
+
+kcSynDecl (CyclicSCC decls)
+  = do { recSynErr decls; failM }      -- Fail here to avoid error cascade
+                                       -- of out-of-scope tycons
 
-kcTyClDecl decl@(TySynonym {tcdSynRhs = rhs})
-  = do         { res_kind <- newKindVar
-       ; kcTyClDeclBody decl res_kind          $ \ tvs' ->
-         do { rhs' <- kcCheckHsType rhs res_kind
-            ; return (decl {tcdTyVars = tvs', tcdSynRhs = rhs'}) } }
+------------------------------------------------------------------------
+kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
+       -- Not used for type synonyms (see kcSynDecl)
 
 kcTyClDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
-  = kcTyClDeclBody decl liftedTypeKind $ \ tvs' ->
+  = kcTyClDeclBody decl        $ \ tvs' ->
     do { ctxt' <- kcHsContext ctxt     
-       ; cons' <- mappM kc_con_decl cons
+       ; cons' <- mappM (wrapLocM kc_con_decl) cons
        ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdCons = cons'}) }
   where
-    kc_con_decl (ConDecl name ex_tvs ex_ctxt details loc)
+    kc_con_decl (ConDecl name ex_tvs ex_ctxt details)
       = kcHsTyVars ex_tvs              $ \ ex_tvs' ->
        do { ex_ctxt' <- kcHsContext ex_ctxt
           ; details' <- kc_con_details details 
-          ; return (ConDecl name ex_tvs' ex_ctxt' details' loc)}
+          ; return (ConDecl name ex_tvs' ex_ctxt' details')}
 
     kc_con_details (PrefixCon btys) 
-       = do { btys' <- mappM kc_arg_ty btys ; return (PrefixCon btys') }
+       = do { btys' <- mappM kc_larg_ty btys ; return (PrefixCon btys') }
     kc_con_details (InfixCon bty1 bty2) 
-       = do { bty1' <- kc_arg_ty bty1; bty2' <- kc_arg_ty bty2; return (InfixCon bty1' bty2') }
+       = do { bty1' <- kc_larg_ty bty1; bty2' <- kc_larg_ty bty2; return (InfixCon bty1' bty2') }
     kc_con_details (RecCon fields) 
        = do { fields' <- mappM kc_field fields; return (RecCon fields') }
 
-    kc_field (fld, bty) = do { bty' <- kc_arg_ty bty ; return (fld, bty') }
+    kc_field (fld, bty) = do { bty' <- kc_larg_ty bty ; return (fld, bty') }
+
+    kc_larg_ty = wrapLocM kc_arg_ty
 
     kc_arg_ty (BangType str ty) = do { ty' <- kc_arg_ty_body ty; return (BangType str ty') }
     kc_arg_ty_body = case new_or_data of
@@ -240,37 +294,34 @@ kcTyClDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
            -- going to remove the constructor while coercing it to a lifted type.
 
 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt,  tcdSigs = sigs})
-  = kcTyClDeclBody decl liftedTypeKind $ \ tvs' ->
+  = kcTyClDeclBody decl        $ \ tvs' ->
     do { ctxt' <- kcHsContext ctxt     
-       ; sigs' <- mappM kc_sig sigs
+       ; sigs' <- mappM (wrapLocM kc_sig) sigs
        ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs'}) }
   where
-    kc_sig (Sig nm op_ty loc) = do { op_ty' <- kcHsLiftedSigType op_ty
-                                  ; return (Sig nm op_ty' loc) }
+    kc_sig (Sig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
+                               ; return (Sig nm op_ty') }
     kc_sig other_sig         = return other_sig
 
-kcTyClDecl decl@(ForeignType {}) 
+kcTyClDecl decl@(ForeignType {})
   = return decl
 
-kcTyClDeclBody :: RenamedTyClDecl -> TcKind
-              -> ([HsTyVarBndr Name] -> TcM a)
+kcTyClDeclBody :: TyClDecl Name
+              -> ([LHsTyVarBndr Name] -> TcM a)
               -> TcM a
   -- Extend the env with bindings for the tyvars, taken from
   -- the kind of the tycon/class.  Give it to the thing inside, and 
   -- check the result kind matches
-kcTyClDeclBody decl res_kind thing_inside
+kcTyClDeclBody decl thing_inside
   = tcAddDeclCtxt decl         $
     kcHsTyVars (tyClDeclTyVars decl)   $ \ kinded_tvs ->
-    do         { tc_ty_thing <- tcLookup (tcdName decl)
-       ; let { tc_kind = case tc_ty_thing of
-                           ARecClass k -> k
-                           ARecTyCon k -> k
-         }
+    do         { tc_ty_thing <- tcLookupLocated (tcdLName decl)
+       ; let tc_kind = case tc_ty_thing of { AThing k -> k }
        ; unifyKind tc_kind (foldr (mkArrowKind . kindedTyVarKind) 
-                                  res_kind kinded_tvs)
+                                  liftedTypeKind kinded_tvs)
        ; thing_inside kinded_tvs }
 
-kindedTyVarKind (KindedTyVar _ k) = k
+kindedTyVarKind (L _ (KindedTyVar _ k)) = k
 \end{code}
 
 
@@ -281,31 +332,42 @@ kindedTyVarKind (KindedTyVar _ k) = k
 %************************************************************************
 
 \begin{code}
+tcSynDecls :: (Name -> ArgVrcs) -> [LTyClDecl Name] -> TcM [TyThing]
+tcSynDecls calc_vrcs [] = return []
+tcSynDecls calc_vrcs (decl : decls) 
+  = do { syn_tc <- addLocM (tcSynDecl calc_vrcs) decl
+       ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls calc_vrcs decls)
+       ; return (syn_tc : syn_tcs) }
+
+tcSynDecl calc_vrcs 
+  (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
+  = tcTyVarBndrs tvs           $ \ tvs' -> do 
+    { traceTc (text "tcd1" <+> ppr tc_name) 
+    ; rhs_ty' <- tcHsKindedType rhs_ty
+    ; return (ATyCon (buildSynTyCon tc_name tvs' rhs_ty' (calc_vrcs tc_name))) }
+
+--------------------
 tcTyClDecl :: (Name -> ArgVrcs) -> (Name -> RecFlag) 
-          -> RenamedTyClDecl -> TcM TyThing
+          -> TyClDecl Name -> TcM TyThing
 
 tcTyClDecl calc_vrcs calc_isrec decl
   = tcAddDeclCtxt decl (tcTyClDecl1 calc_vrcs calc_isrec decl)
 
 tcTyClDecl1 calc_vrcs calc_isrec 
-  (TySynonym {tcdName = tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
-  =   tcTyVarBndrs tvs         $ \ tvs' -> do 
-    { rhs_ty' <- tcHsKindedType rhs_ty
-    ; return (ATyCon (buildSynTyCon tc_name tvs' rhs_ty' arg_vrcs)) }
-  where
-    arg_vrcs = calc_vrcs tc_name
-
-tcTyClDecl1 calc_vrcs calc_isrec 
   (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
-          tcdName = tc_name, tcdCons = cons})
+          tcdLName = L _ tc_name, tcdCons = cons})
   = tcTyVarBndrs tvs           $ \ tvs' -> do 
   { ctxt'       <- tcHsKindedContext ctxt
   ; want_generic <- doptM Opt_Generics
   ; tycon <- fixM (\ tycon -> do 
-       { cons' <- mappM (tcConDecl new_or_data tycon tvs' ctxt') cons
-       ; buildAlgTyCon new_or_data tc_name tvs' ctxt' 
-                       (DataCons cons') arg_vrcs is_rec
-                       (want_generic && canDoGenerics cons')
+       { data_cons <- mappM (addLocM (tcConDecl new_or_data tycon tvs' ctxt')) cons
+       ; let tc_rhs = case new_or_data of
+                       DataType -> mkDataTyConRhs data_cons
+                       NewType  -> ASSERT( isSingleton data_cons )
+                                   mkNewTyConRhs (head data_cons)
+       ; buildAlgTyCon tc_name tvs' ctxt' 
+                       tc_rhs arg_vrcs is_rec
+                       (want_generic && canDoGenerics data_cons)
        })
   ; return (ATyCon tycon)
   }
@@ -314,12 +376,12 @@ tcTyClDecl1 calc_vrcs calc_isrec
     is_rec   = calc_isrec tc_name
 
 tcTyClDecl1 calc_vrcs calc_isrec 
-  (ClassDecl {tcdName = class_name, tcdTyVars = tvs, 
+  (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs, 
              tcdCtxt = ctxt, tcdMeths = meths,
              tcdFDs = fundeps, tcdSigs = sigs} )
   = tcTyVarBndrs tvs           $ \ tvs' -> do 
   { ctxt' <- tcHsKindedContext ctxt
-  ; fds' <- mappM tc_fundep fundeps
+  ; fds' <- mappM (addLocM tc_fundep) fundeps
   ; sig_stuff <- tcClassSigs class_name sigs meths
   ; clas <- fixM (\ clas ->
                let     -- This little knot is just so we can get
@@ -339,25 +401,25 @@ tcTyClDecl1 calc_vrcs calc_isrec
 
 
 tcTyClDecl1 calc_vrcs calc_isrec 
-  (ForeignType {tcdName = tc_name, tcdExtName = tc_ext_name})
+  (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
   = returnM (ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0 []))
 
 -----------------------------------
 tcConDecl :: NewOrData -> TyCon -> [TyVar] -> ThetaType 
-         -> RenamedConDecl -> TcM DataCon
+         -> ConDecl Name -> TcM DataCon
 
 tcConDecl new_or_data tycon tyvars ctxt 
-          (ConDecl name ex_tvs ex_ctxt details src_loc)
-  = addSrcLoc src_loc          $
-    tcTyVarBndrs ex_tvs                $ \ ex_tvs' -> do 
+          (ConDecl name ex_tvs ex_ctxt details)
+  = tcTyVarBndrs ex_tvs                $ \ ex_tvs' -> do 
     { ex_ctxt' <- tcHsKindedContext ex_ctxt
     ; unbox_strict <- doptM Opt_UnboxStrictFields
     ; let 
        tc_datacon field_lbls btys
-         = do { arg_tys <- mappM (tcHsKindedType . getBangType) btys
-              ; buildDataCon name 
-                   (argStrictness unbox_strict tycon btys arg_tys)
-                   field_lbls
+         = do { let { ubtys = map unLoc btys }
+              ; arg_tys <- mappM (tcHsKindedType . getBangType) ubtys
+              ; buildDataCon (unLoc name)
+                   (argStrictness unbox_strict tycon ubtys arg_tys)
+                   (map unLoc field_lbls)
                    tyvars ctxt ex_tvs' ex_ctxt'
                    arg_tys tycon }
     ; case details of
@@ -403,24 +465,23 @@ Validity checking is done once the mutually-recursive knot has been
 tied, so we can look at things freely.
 
 \begin{code}
-checkCycleErrs :: [TyClDecl Name] -> TcM ()
+checkCycleErrs :: [LTyClDecl Name] -> TcM ()
 checkCycleErrs tyclss
-  | null syn_cycles && null cls_cycles
+  | null cls_cycles
   = return ()
   | otherwise
-  = do { mappM_ recSynErr syn_cycles
-       ; mappM_ recClsErr cls_cycles
+  = do { mappM_ recClsErr cls_cycles
        ; failM }       -- Give up now, because later checkValidTyCl
                        -- will loop if the synonym is recursive
   where
-    (syn_cycles, cls_cycles) = calcCycleErrs tyclss
+    cls_cycles = calcClassCycles tyclss
 
-checkValidTyCl :: RenamedTyClDecl -> TcM ()
+checkValidTyCl :: TyClDecl Name -> TcM ()
 -- We do the validity check over declarations, rather than TyThings
 -- only so that we can add a nice context with tcAddDeclCtxt
 checkValidTyCl decl
   = tcAddDeclCtxt decl $
-    do { thing <- tcLookupGlobal (tcdName decl)
+    do { thing <- tcLookupLocatedGlobal (tcdLName decl)
        ; traceTc (text "Validity of" <+> ppr thing)    
        ; case thing of
            ATyCon tc -> checkValidTyCon tc
@@ -505,18 +566,23 @@ checkValidClass cls
     no_generics = null [() | (_, GenDefMeth) <- op_stuff]
 
     check_op (sel_id, dm) 
-       = addErrCtxt (classOpCtxt sel_id) (
-         checkValidTheta SigmaCtxt (tail theta)        `thenM_`
+      = addErrCtxt (classOpCtxt sel_id tau) $ do
+       { checkValidTheta SigmaCtxt (tail theta)
                -- The 'tail' removes the initial (C a) from the
                -- class itself, leaving just the method type
 
-         checkValidType (FunSigCtxt op_name) tau       `thenM_`
+       ; checkValidType (FunSigCtxt op_name) tau
+
+               -- Check that the type mentions at least one of
+               -- the class type variables
+       ; checkTc (any (`elemVarSet` tyVarsOfType tau) tyvars)
+                 (noClassTyVarErr cls sel_id)
 
                -- Check that for a generic method, the type of 
                -- the method is sufficiently simple
-         checkTc (dm /= GenDefMeth || validGenericMethodType op_ty)
+       ; checkTc (dm /= GenDefMeth || validGenericMethodType op_ty)
                  (badGenericMethodType op_name op_ty)
-       )
+       }
        where
          op_name = idName sel_id
          op_ty   = idType sel_id
@@ -544,8 +610,8 @@ dataConCtxt con = sep [ptext SLIT("When checking the data constructor:"),
                             [ ppr n <+> dcolon <+> ppr ty 
                             | (n,ty) <- fields `zip` arg_tys]))
 
-classOpCtxt sel_id = sep [ptext SLIT("When checking the class method:"),
-                         nest 2 (ppr sel_id <+> dcolon <+> ppr (idType sel_id))]
+classOpCtxt sel_id tau = sep [ptext SLIT("When checking the class method:"),
+                             nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
 
 nullaryClassErr cls
   = ptext SLIT("No parameters for class")  <+> quotes (ppr cls)
@@ -554,6 +620,11 @@ classArityErr cls
   = vcat [ptext SLIT("Too many parameters for class") <+> quotes (ppr cls),
          parens (ptext SLIT("Use -fglasgow-exts to allow multi-parameter classes"))]
 
+noClassTyVarErr clas op
+  = sep [ptext SLIT("The class method") <+> quotes (ppr op),
+        ptext SLIT("mentions none of the type variables of the class") <+> 
+               ppr clas <+> hsep (map ppr (classTyVars clas))]
+
 genericMultiParamErr clas
   = ptext SLIT("The multi-parameter class") <+> quotes (ppr clas) <+> 
     ptext SLIT("cannot have generic methods")
@@ -563,19 +634,19 @@ badGenericMethodType op op_ty
        4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
                ptext SLIT("You can only use type variables, arrows, and tuples")])
 
-recSynErr tcs
-  = addSrcLoc (getSrcLoc (head tcs)) $
+recSynErr syn_decls
+  = addSrcSpan (getLoc (head syn_decls)) $
     addErr (sep [ptext SLIT("Cycle in type synonym declarations:"),
-                nest 2 (vcat (map ppr_thing tcs))])
+                nest 2 (vcat (map ppr_decl syn_decls))])
+  where
+    ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
 
-recClsErr clss
-  = addSrcLoc (getSrcLoc (head clss)) $
+recClsErr cls_decls
+  = addSrcSpan (getLoc (head cls_decls)) $
     addErr (sep [ptext SLIT("Cycle in class declarations (via superclasses):"),
-                nest 2 (vcat (map ppr_thing clss))])
-
-ppr_thing :: Name -> SDoc
-ppr_thing n = ppr n <+> parens (ppr (getSrcLoc n))
-
+                nest 2 (vcat (map ppr_decl cls_decls))])
+  where
+    ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
 
 exRecConErr name
   = ptext SLIT("Can't combine named fields with locally-quantified type variables")