[project @ 2000-07-15 15:09:45 by panne]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcMonoType.lhs
index 1d6087c..fbf9a71 100644 (file)
 \section[TcMonoType]{Typechecking user-specified @MonoTypes@}
 
 \begin{code}
-module TcMonoType ( tcHsType, tcHsTypeKind, tcHsTopType, tcHsTopBoxedType, tcHsTopTypeKind,
-                   tcContext, tcHsTyVar, kcHsTyVar,
-                   tcExtendTyVarScope, tcExtendTopTyVarScope,
+module TcMonoType ( tcHsType, tcHsSigType, tcHsBoxedSigType, 
+                   tcContext, tcClassContext,
+
+                       -- Kind checking
+                   kcHsTyVar, kcHsTyVars, mkTyClTyVars,
+                   kcHsType, kcHsSigType, kcHsBoxedSigType, kcHsContext,
+                   kcTyVarScope, newSigTyVars, mkImmutTyVars,
+
                    TcSigInfo(..), tcTySig, mkTcSig, maybeSig,
                    checkSigTyVars, sigCtxt, sigPatCtxt
                  ) where
 
 #include "HsVersions.h"
 
-import HsSyn           ( HsType(..), HsTyVar(..), MonoUsageAnn(..),
-                          Sig(..), HsPred(..), pprHsPred, pprParendHsType )
-import RnHsSyn         ( RenamedHsType, RenamedContext, RenamedSig )
+import HsSyn           ( HsType(..), HsTyVarBndr(..), HsUsageAnn(..),
+                          Sig(..), HsPred(..), pprParendHsType, HsTupCon(..), hsTyVarNames )
+import RnHsSyn         ( RenamedHsType, RenamedHsPred, RenamedContext, RenamedSig )
 import TcHsSyn         ( TcId )
 
 import TcMonad
 import TcEnv           ( tcExtendTyVarEnv, tcLookupTy, tcGetValueEnv, tcGetInScopeTyVars,
                           tcExtendUVarEnv, tcLookupUVar,
-                         tcGetGlobalTyVars, valueEnvIds, TcTyThing(..)
+                         tcGetGlobalTyVars, valueEnvIds, 
+                         TyThing(..), tyThingKind, tcExtendKindEnv
                        )
 import TcType          ( TcType, TcKind, TcTyVar, TcThetaType, TcTauType,
-                         typeToTcType, kindToTcKind,
                          newKindVar, tcInstSigVar,
-                         zonkTcKindToKind, zonkTcTypeToType, zonkTcTyVars, zonkTcType
+                         zonkKindEnv, zonkTcType, zonkTcTyVars, zonkTcTyVar
                        )
-import Inst            ( Inst, InstOrigin(..), newMethodWithGivenTy, instToIdBndr )
-import TcUnify         ( unifyKind, unifyKinds, unifyTypeKind )
-import Type            ( Type, PredType(..), ThetaType, UsageAnn(..),
+import Inst            ( Inst, InstOrigin(..), newMethodWithGivenTy, instToIdBndr,
+                         instFunDeps, instFunDepsOfTheta )
+import FunDeps         ( tyVarFunDep, oclose )
+import TcUnify         ( unifyKind, unifyKinds, unifyOpenTypeKind )
+import Type            ( Type, Kind, PredType(..), ThetaType, UsageAnn(..),
                          mkTyVarTy, mkTyVarTys, mkFunTy, mkSynTy, mkUsgTy,
-                          mkUsForAllTy, zipFunTys,
+                          mkUsForAllTy, zipFunTys, hoistForAllTys,
                          mkSigmaTy, mkDictTy, mkPredTy, mkTyConApp,
-                         mkAppTys, splitForAllTys, splitRhoTy,
-                         boxedTypeKind, unboxedTypeKind, tyVarsOfType,
-                         mkArrowKinds, getTyVar_maybe, getTyVar,
-                         tidyOpenType, tidyOpenTypes, tidyTyVar,
-                         tyVarsOfType, tyVarsOfTypes
+                         mkAppTys, splitForAllTys, splitRhoTy, mkRhoTy,
+                         boxedTypeKind, unboxedTypeKind, mkArrowKind,
+                         mkArrowKinds, getTyVar_maybe, getTyVar, splitFunTy_maybe,
+                         tidyOpenType, tidyOpenTypes, tidyTyVar, tidyTyVars,
+                         tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, mkForAllTys,
+                         classesOfPreds
                        )
-import PprType         ( pprConstraint )
+import PprType         ( pprConstraint, pprType, pprPred )
 import Subst           ( mkTopTyVarSubst, substTy )
 import Id              ( mkVanillaId, idName, idType, idFreeTyVars )
-import Var             ( TyVar, mkTyVar, mkNamedUVar, varName )
+import Var             ( TyVar, mkTyVar, tyVarKind, mkNamedUVar, varName )
 import VarEnv
 import VarSet
-import Bag             ( bagToList )
 import ErrUtils                ( Message )
-import PrelInfo                ( cCallishClassKeys )
-import TyCon           ( TyCon )
+import TyCon           ( TyCon, isSynTyCon, tyConArity, tyConKind )
+import Class           ( ClassContext, classArity, classTyCon )
 import Name            ( Name, OccName, isLocallyDefined )
-import TysWiredIn      ( mkListTy, mkTupleTy, mkUnboxedTupleTy )
+import TysWiredIn      ( mkListTy, mkTupleTy )
 import UniqFM          ( elemUFM, foldUFM )
+import BasicTypes      ( Boxity(..) )
 import SrcLoc          ( SrcLoc )
-import Unique          ( Unique, Uniquable(..) )
-import Util            ( zipWithEqual, zipLazy, mapAccumL )
+import Util            ( mapAccumL, isSingleton, removeDups )
 import Outputable
 \end{code}
 
 
 %************************************************************************
 %*                                                                     *
+\subsection{Kind checking}
+%*                                                                     *
+%************************************************************************
+
+Kind checking
+~~~~~~~~~~~~~
+When we come across the binding site for some type variables, we
+proceed in two stages
+
+1. Figure out what kind each tyvar has
+
+2. Create suitably-kinded tyvars, 
+   extend the envt, 
+   and typecheck the body
+
+To do step 1, we proceed thus:
+
+1a. Bind each type variable to a kind variable
+1b. Apply the kind checker
+1c. Zonk the resulting kinds
+
+The kind checker is passed to kcTyVarScope as an argument.  
+
+For example, when we find
+       (forall a m. m a -> m a)
+we bind a,m to kind varibles and kind-check (m a -> m a).  This
+makes a get kind *, and m get kind *->*.  Now we typecheck (m a -> m a)
+in an environment that binds a and m suitably.
+
+The kind checker passed to kcTyVarScope needs to look at enough to
+establish the kind of the tyvar:
+  * For a group of type and class decls, it's just the group, not
+       the rest of the program
+  * For a tyvar bound in a pattern type signature, its the types
+       mentioned in the other type signatures in that bunch of patterns
+  * For a tyvar bound in a RULE, it's the type signatures on other
+       universally quantified variables in the rule
+
+Note that this may occasionally give surprising results.  For example:
+
+       data T a b = MkT (a b)
+
+Here we deduce                 a::*->*, b::*.
+But equally valid would be
+                               a::(*->*)-> *, b::*->*
+
+\begin{code}
+kcTyVarScope :: [HsTyVarBndr Name] 
+            -> TcM s a                         -- The kind checker
+            -> TcM s [(Name,Kind)]
+       -- Do a kind check to find out the kinds of the type variables
+       -- Then return a bunch of name-kind pairs, from which to 
+       -- construct the type variables.  We don't return the tyvars
+       -- themselves because sometimes we want mutable ones and 
+       -- sometimes we want immutable ones.
+
+kcTyVarScope [] kind_check = returnTc []
+       -- A useful short cut for a common case!
+  
+kcTyVarScope tv_names kind_check 
+  = kcHsTyVars tv_names                                `thenNF_Tc` \ tv_names_w_kinds ->
+    tcExtendKindEnv tv_names_w_kinds kind_check                `thenTc_`
+    zonkKindEnv tv_names_w_kinds
+\end{code}
+    
+
+\begin{code}
+kcHsTyVar  :: HsTyVarBndr name   -> NF_TcM s (name, TcKind)
+kcHsTyVars :: [HsTyVarBndr name] -> NF_TcM s [(name, TcKind)]
+
+kcHsTyVar (UserTyVar name)       = newKindVar  `thenNF_Tc` \ kind ->
+                                  returnNF_Tc (name, kind)
+kcHsTyVar (IfaceTyVar name kind) = returnNF_Tc (name, kind)
+
+kcHsTyVars tvs = mapNF_Tc kcHsTyVar tvs
+
+---------------------------
+kcBoxedType :: RenamedHsType -> TcM s ()
+       -- The type ty must be a *boxed* *type*
+kcBoxedType ty
+  = kcHsType ty                                `thenTc` \ kind ->
+    tcAddErrCtxt (typeKindCtxt ty)     $
+    unifyKind boxedTypeKind kind
+    
+---------------------------
+kcTypeType :: RenamedHsType -> TcM s ()
+       -- The type ty must be a *type*, but it can be boxed or unboxed.
+kcTypeType ty
+  = kcHsType ty                                `thenTc` \ kind ->
+    tcAddErrCtxt (typeKindCtxt ty)     $
+    unifyOpenTypeKind kind
+
+---------------------------
+kcHsSigType, kcHsBoxedSigType :: RenamedHsType -> TcM s ()
+       -- Used for type signatures
+kcHsSigType     = kcTypeType
+kcHsBoxedSigType = kcBoxedType
+
+---------------------------
+kcHsType :: RenamedHsType -> TcM s TcKind
+kcHsType (HsTyVar name)              
+  = tcLookupTy name    `thenTc` \ thing ->
+    case thing of
+       ATyVar tv -> returnTc (tyVarKind tv)
+       ATyCon tc -> returnTc (tyConKind tc)
+       AThing k  -> returnTc k
+       other     -> failWithTc (wrongThingErr "type" thing name)
+
+kcHsType (HsUsgTy _ ty)       = kcHsType ty
+kcHsType (HsUsgForAllTy _ ty) = kcHsType ty
+
+kcHsType (HsListTy ty)
+  = kcBoxedType ty             `thenTc` \ tau_ty ->
+    returnTc boxedTypeKind
+
+kcHsType (HsTupleTy (HsTupCon _ Boxed) tys)
+  = mapTc kcBoxedType tys      `thenTc_` 
+    returnTc boxedTypeKind
+
+kcHsType (HsTupleTy (HsTupCon _ Unboxed) tys)
+  = mapTc kcTypeType tys       `thenTc_` 
+    returnTc unboxedTypeKind
+
+kcHsType (HsFunTy ty1 ty2)
+  = kcTypeType ty1     `thenTc_`
+    kcTypeType ty2     `thenTc_`
+    returnTc boxedTypeKind
+
+kcHsType (HsPredTy pred)
+  = kcHsPred pred              `thenTc_`
+    returnTc boxedTypeKind
+
+kcHsType ty@(HsAppTy ty1 ty2)
+  = kcHsType ty1               `thenTc` \ tc_kind ->
+    kcHsType ty2               `thenTc` \ arg_kind ->
+
+    tcAddErrCtxt (appKindCtxt (ppr ty))        $
+    case splitFunTy_maybe tc_kind of 
+       Just (arg_kind', res_kind)
+               -> unifyKind arg_kind arg_kind' `thenTc_`
+                  returnTc res_kind
+
+       Nothing -> newKindVar                                           `thenNF_Tc` \ res_kind ->
+                  unifyKind tc_kind (mkArrowKind arg_kind res_kind)    `thenTc_`
+                  returnTc res_kind
+
+kcHsType (HsForAllTy (Just tv_names) context ty)
+  = kcHsTyVars tv_names                        `thenNF_Tc` \ kind_env ->
+    tcExtendKindEnv kind_env           $
+    kcHsContext context                `thenTc_`
+    kcHsType ty                        `thenTc` \ kind ->
+               -- Context behaves like a function type
+               -- This matters.  Return-unboxed-tuple analysis can
+               -- give overloaded functions like
+               --      f :: forall a. Num a => (# a->a, a->a #)
+               -- And we want these to get through the type checker
+    returnTc (if null context then
+                kind
+             else
+                 boxedTypeKind)
+
+---------------------------
+kcHsContext ctxt = mapTc_ kcHsPred ctxt
+
+kcHsPred :: RenamedHsPred -> TcM s ()
+kcHsPred pred@(HsPIParam name ty)
+  = tcAddErrCtxt (appKindCtxt (ppr pred))      $
+    kcBoxedType ty
+
+kcHsPred pred@(HsPClass cls tys)
+  = tcAddErrCtxt (appKindCtxt (ppr pred))      $
+    tcLookupTy cls                             `thenNF_Tc` \ thing -> 
+    (case thing of
+       AClass cls  -> returnTc (tyConKind (classTyCon cls))
+       AThing kind -> returnTc kind
+       other -> failWithTc (wrongThingErr "class" thing cls))  `thenTc` \ kind ->
+    mapTc kcHsType tys                                         `thenTc` \ arg_kinds ->
+    unifyKind kind (mkArrowKinds arg_kinds boxedTypeKind)
+\end{code}
+
+%************************************************************************
+%*                                                                     *
 \subsection{Checking types}
 %*                                                                     *
 %************************************************************************
 
-tcHsType and tcHsTypeKind
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+tcHsSigType and tcHsBoxedSigType
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+tcHsSigType and tcHsBoxedSigType are used for type signatures written by the programmer
 
-tcHsType checks that the type really is of kind Type!
+  * We hoist any inner for-alls to the top
+
+  * Notice that we kind-check first, because the type-check assumes
+       that the kinds are already checked.
+  * They are only called when there are no kind vars in the environment
+       so the kind returned is indeed a Kind not a TcKind
 
 \begin{code}
-tcHsType :: RenamedHsType -> TcM s TcType
-tcHsType ty
-  = -- tcAddErrCtxt (typeCtxt ty)              $
-    tc_type ty
-
-tcHsTypeKind    :: RenamedHsType -> TcM s (TcKind, TcType)
-tcHsTypeKind ty 
-  = -- tcAddErrCtxt (typeCtxt ty)              $
-    tc_type_kind ty
-
--- Type-check a type, *and* then lazily zonk it.  The important
--- point is that this zonks all the uncommitted *kind* variables
--- in kinds of any any nested for-all tyvars.
--- There won't be any mutable *type* variables at all.
---
--- NOTE the forkNF_Tc.  This makes the zonking lazy, which is
--- absolutely necessary.  During the type-checking of a recursive
--- group of tycons/classes (TcTyClsDecls.tcGroup) we use an
--- environment in which we aren't allowed to look at the actual
--- tycons/classes returned from a lookup. Because tc_app does
--- look at the tycon to build the type, we can't look at the type
--- either, until we get out of the loop.   The fork delays the
--- zonking till we've completed the loop.  Sigh.
-
-tcHsTopType :: RenamedHsType -> TcM s Type
-tcHsTopType ty
-  = -- tcAddErrCtxt (typeCtxt ty)              $
-    tc_type ty                         `thenTc` \ ty' ->
-    forkNF_Tc (zonkTcTypeToType ty')
-
-tcHsTopTypeKind :: RenamedHsType -> TcM s (TcKind, Type)
-tcHsTopTypeKind ty
-  = -- tcAddErrCtxt (typeCtxt ty)              $
-    tc_type_kind ty                            `thenTc` \ (kind, ty') ->
-    forkNF_Tc (zonkTcTypeToType ty')           `thenTc` \ zonked_ty ->
-    returnNF_Tc (kind, zonked_ty)
-
-tcHsTopBoxedType :: RenamedHsType -> TcM s Type
-tcHsTopBoxedType ty
-  = -- tcAddErrCtxt (typeCtxt ty)              $
-    tc_boxed_type ty                   `thenTc` \ ty' ->
-    forkNF_Tc (zonkTcTypeToType ty')
+tcHsSigType :: RenamedHsType -> TcM s TcType
+tcHsSigType ty
+  = kcTypeType ty      `thenTc_`
+    tcHsType ty                `thenTc` \ ty' ->
+    returnTc (hoistForAllTys ty')
+
+tcHsBoxedSigType :: RenamedHsType -> TcM s Type
+tcHsBoxedSigType ty
+  = kcBoxedType ty     `thenTc_`
+    tcHsType ty                `thenTc` \ ty' ->
+    returnTc (hoistForAllTys ty')
 \end{code}
 
 
-The main work horse
-~~~~~~~~~~~~~~~~~~~
+tcHsType, the main work horse
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
 \begin{code}
-tc_boxed_type :: RenamedHsType -> TcM s Type
-tc_boxed_type ty
-  = tc_type_kind ty                                    `thenTc` \ (actual_kind, tc_ty) ->
-    tcAddErrCtxt (typeKindCtxt ty)
-                (unifyKind boxedTypeKind actual_kind)  `thenTc_`
-    returnTc tc_ty
-
-tc_type :: RenamedHsType -> TcM s Type
-tc_type ty
-       -- The type ty must be a *type*, but it can be boxed
-       -- or unboxed.  So we check that is is of form (Type bv)
-       -- using unifyTypeKind
-  = tc_type_kind ty                            `thenTc` \ (actual_kind, tc_ty) ->
-    tcAddErrCtxt (typeKindCtxt ty)
-                (unifyTypeKind actual_kind)    `thenTc_`
-    returnTc tc_ty
-
-tc_type_kind :: RenamedHsType -> TcM s (TcKind, Type)
-tc_type_kind ty@(MonoTyVar name)
+tcHsType :: RenamedHsType -> TcM s Type
+tcHsType ty@(HsTyVar name)
   = tc_app ty []
 
-tc_type_kind (MonoListTy ty)
-  = tc_boxed_type ty           `thenTc` \ tau_ty ->
-    returnTc (boxedTypeKind, mkListTy tau_ty)
+tcHsType (HsListTy ty)
+  = tcHsType ty                `thenTc` \ tau_ty ->
+    returnTc (mkListTy tau_ty)
 
-tc_type_kind (MonoTupleTy tys True {-boxed-})
-  = mapTc tc_boxed_type tys    `thenTc` \ tau_tys ->
-    returnTc (boxedTypeKind, mkTupleTy (length tys) tau_tys)
+tcHsType (HsTupleTy (HsTupCon _ boxity) tys)
+  = mapTc tcHsType tys `thenTc` \ tau_tys ->
+    returnTc (mkTupleTy boxity (length tys) tau_tys)
 
-tc_type_kind (MonoTupleTy tys False {-unboxed-})
-  = mapTc tc_type tys                  `thenTc` \ tau_tys ->
-    returnTc (unboxedTypeKind, mkUnboxedTupleTy (length tys) tau_tys)
+tcHsType (HsFunTy ty1 ty2)
+  = tcHsType ty1       `thenTc` \ tau_ty1 ->
+    tcHsType ty2       `thenTc` \ tau_ty2 ->
+    returnTc (mkFunTy tau_ty1 tau_ty2)
 
-tc_type_kind (MonoFunTy ty1 ty2)
-  = tc_type ty1        `thenTc` \ tau_ty1 ->
-    tc_type ty2        `thenTc` \ tau_ty2 ->
-    returnTc (boxedTypeKind, mkFunTy tau_ty1 tau_ty2)
-
-tc_type_kind (MonoTyApp ty1 ty2)
+tcHsType (HsAppTy ty1 ty2)
   = tc_app ty1 [ty2]
 
-tc_type_kind (MonoIParamTy n ty)
-  = tc_type ty `thenTc` \ tau ->
-    returnTc (boxedTypeKind, mkPredTy (IParam n tau))
-
-tc_type_kind (MonoDictTy class_name tys)
-  = tcClassAssertion (HsPClass class_name tys) `thenTc` \ (Class clas arg_tys) ->
-    returnTc (boxedTypeKind, mkDictTy clas arg_tys)
+tcHsType (HsPredTy pred)
+  = tcClassAssertion True pred `thenTc` \ pred' ->
+    returnTc (mkPredTy pred')
 
-tc_type_kind (MonoUsgTy usg ty)
-  = newUsg usg                          `thenTc` \ usg' ->
-    tc_type_kind ty                     `thenTc` \ (kind, tc_ty) ->
-    returnTc (kind, mkUsgTy usg' tc_ty)
+tcHsType (HsUsgTy usg ty)
+  = newUsg usg                 `thenTc` \ usg' ->
+    tcHsType ty                        `thenTc` \ tc_ty ->
+    returnTc (mkUsgTy usg' tc_ty)
   where
     newUsg usg = case usg of
-                   MonoUsOnce        -> returnTc UsOnce
-                   MonoUsMany        -> returnTc UsMany
-                   MonoUsVar uv_name -> tcLookupUVar uv_name `thenTc` \ uv ->
-                                        returnTc (UsVar uv)
+                   HsUsOnce        -> returnTc UsOnce
+                   HsUsMany        -> returnTc UsMany
+                   HsUsVar uv_name -> tcLookupUVar uv_name `thenTc` \ uv ->
+                                      returnTc (UsVar uv)
 
-tc_type_kind (MonoUsgForAllTy uv_name ty)
+tcHsType (HsUsgForAllTy uv_name ty)
   = let
         uv = mkNamedUVar uv_name
     in
     tcExtendUVarEnv uv_name uv $
-      tc_type_kind ty                     `thenTc` \ (kind, tc_ty) ->
-      returnTc (kind, mkUsForAllTy uv tc_ty)
-
-tc_type_kind (HsForAllTy (Just tv_names) context ty)
-  = tcExtendTyVarScope tv_names                $ \ tyvars ->
-    tcContext context                  `thenTc` \ theta ->
-    tc_type_kind ty                    `thenTc` \ (kind, tau) ->
-    tcGetInScopeTyVars                 `thenTc` \ in_scope_vars ->
+    tcHsType ty                     `thenTc` \ tc_ty ->
+    returnTc (mkUsForAllTy uv tc_ty)
+
+tcHsType full_ty@(HsForAllTy (Just tv_names) ctxt ty)
+  = kcTyVarScope tv_names 
+                (kcHsContext ctxt `thenTc_` kcHsType ty)  `thenTc` \ tv_kinds ->
     let
-       body_kind | null theta = kind
-                 | otherwise  = boxedTypeKind
-               -- Context behaves like a function type
-               -- This matters.  Return-unboxed-tuple analysis can
-               -- give overloaded functions like
-               --      f :: forall a. Num a => (# a->a, a->a #)
-               -- And we want these to get through the type checker
-        check ct@(Class c tys) | ambiguous = failWithTc (ambigErr (c,tys) tau)
-         where ct_vars = tyVarsOfTypes tys
-               forall_tyvars = map varName in_scope_vars
-               tau_vars = tyVarsOfType tau
-               ambig ct_var = (varName ct_var `elem` forall_tyvars) &&
-                              not (ct_var `elemUFM` tau_vars)
-               ambiguous = foldUFM ((||) . ambig) False ct_vars
-       check _ = returnTc ()
+       forall_tyvars = mkImmutTyVars tv_kinds
     in
-    mapTc check theta                  `thenTc_`
-    returnTc (body_kind, mkSigmaTy tyvars theta tau)
+    tcExtendTyVarEnv forall_tyvars     $
+    tcContext ctxt                     `thenTc` \ theta ->
+    tcHsType ty                                `thenTc` \ tau ->
+    let
+       -- Check for ambiguity
+       --   forall V. P => tau
+       -- is ambiguous if P contains generic variables
+       -- (i.e. one of the Vs) that are not mentioned in tau
+       --
+       -- However, we need to take account of functional dependencies
+       -- when we speak of 'mentioned in tau'.  Example:
+       --      class C a b | a -> b where ...
+       -- Then the type
+       --      forall x y. (C x y) => x
+       -- is not ambiguous because x is mentioned and x determines y
+       --
+       -- NOTE: In addition, GHC insists that at least one type variable
+       -- in each constraint is in V.  So we disallow a type like
+       --      forall a. Eq b => b -> b
+       -- even in a scope where b is in scope.
+       -- This is the is_free test below.
+
+       tau_vars            = tyVarsOfType tau
+       fds                 = instFunDepsOfTheta theta
+       tvFundep            = tyVarFunDep fds
+       extended_tau_vars   = oclose tvFundep tau_vars
+       is_ambig ct_var     = (ct_var `elem` forall_tyvars) &&
+                             not (ct_var `elemUFM` extended_tau_vars)
+       is_free ct_var      = not (ct_var `elem` forall_tyvars)
+
+       check_pred pred = checkTc (not any_ambig) (ambigErr pred full_ty) `thenTc_`
+                         checkTc (not all_free)  (freeErr  pred full_ty)
+             where 
+               ct_vars   = varSetElems (tyVarsOfPred pred)
+               any_ambig = is_source_polytype && any is_ambig ct_vars
+               all_free  = all is_free  ct_vars
+
+       -- Check ambiguity only for source-program types, not
+       -- for types coming from inteface files.  The latter can
+       -- legitimately have ambiguous types. Example
+       --    class S a where s :: a -> (Int,Int)
+       --    instance S Char where s _ = (1,1)
+       --    f:: S a => [a] -> Int -> (Int,Int)
+       --    f (_::[a]) x = (a*x,b)
+       --      where (a,b) = s (undefined::a)
+       -- Here the worker for f gets the type
+       --      fw :: forall a. S a => Int -> (# Int, Int #)
+       --
+       -- If the list of tv_names is empty, we have a monotype,
+       -- and then we don't need to check for ambiguity either,
+       -- because the test can't fail (see is_ambig).
+       is_source_polytype = case tv_names of
+                               (UserTyVar _ : _) -> True
+                               other             -> False
+    in
+    mapTc check_pred theta             `thenTc_`
+    returnTc (mkSigmaTy forall_tyvars theta tau)
 \end{code}
 
 Help functions for type applications
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
 \begin{code}
-tc_app (MonoTyApp ty1 ty2) tys
+tc_app (HsAppTy ty1 ty2) tys
   = tc_app ty1 (ty2:tys)
 
 tc_app ty tys
-  | null tys
-  = tc_fun_type ty []
-
-  | otherwise
   = tcAddErrCtxt (appKindCtxt pp_app)  $
-    mapAndUnzipTc tc_type_kind tys     `thenTc` \ (arg_kinds, arg_tys) ->
-    tc_fun_type ty arg_tys             `thenTc` \ (fun_kind, result_ty) ->
-
-       -- Check argument compatibility
-    newKindVar                                 `thenNF_Tc` \ result_kind ->
-    unifyKind fun_kind (mkArrowKinds arg_kinds result_kind)
-                                       `thenTc_`
-    returnTc (result_kind, result_ty)
+    mapTc tcHsType tys                 `thenTc` \ arg_tys ->
+    tc_fun_type ty arg_tys
   where
     pp_app = ppr ty <+> sep (map pprParendHsType tys)
 
--- (tc_fun_type ty arg_tys) returns (kind-of ty, mkAppTys ty arg_tys)
+-- (tc_fun_type ty arg_tys) returns (mkAppTys ty arg_tys)
 -- But not quite; for synonyms it checks the correct arity, and builds a SynTy
 --     hence the rather strange functionality.
 
-tc_fun_type (MonoTyVar name) arg_tys
-  = tcLookupTy name                    `thenTc` \ (tycon_kind, maybe_arity, thing) ->
+tc_fun_type (HsTyVar name) arg_tys
+  = tcLookupTy name                    `thenTc` \ thing ->
     case thing of
-       ATyVar tv   -> returnTc (tycon_kind, mkAppTys (mkTyVarTy tv) arg_tys)
-       AClass clas -> failWithTc (classAsTyConErr name)
-       ATyCon tc   -> case maybe_arity of
-                        Nothing ->     -- Data or newtype
-                                       returnTc (tycon_kind, mkTyConApp tc arg_tys)
-
-                        Just arity ->  -- Type synonym
-                                 checkTc (arity <= n_args) err_msg     `thenTc_`
-                                 returnTc (tycon_kind, result_ty)
-                          where
-                               -- It's OK to have an *over-applied* type synonym
-                               --      data Tree a b = ...
-                               --      type Foo a = Tree [a]
-                               --      f :: Foo a b -> ...
-                             result_ty = mkAppTys (mkSynTy tc (take arity arg_tys))
-                                                  (drop arity arg_tys)
-                             err_msg = arityErr "type synonym" name arity n_args
-                             n_args  = length arg_tys
+       ATyVar tv -> returnTc (mkAppTys (mkTyVarTy tv) arg_tys)
+
+       ATyCon tc | isSynTyCon tc ->  checkTc arity_ok err_msg  `thenTc_`
+                                     returnTc (mkAppTys (mkSynTy tc (take arity arg_tys))
+                                                        (drop arity arg_tys))
+
+                 | otherwise     ->  returnTc (mkTyConApp tc arg_tys)
+                 where
+
+                   arity_ok = arity <= n_args 
+                   arity = tyConArity tc
+                       -- It's OK to have an *over-applied* type synonym
+                       --      data Tree a b = ...
+                       --      type Foo a = Tree [a]
+                       --      f :: Foo a b -> ...
+                   err_msg = arityErr "Type synonym" name arity n_args
+                   n_args  = length arg_tys
+
+       other -> failWithTc (wrongThingErr "type constructor" thing name)
 
 tc_fun_type ty arg_tys
-  = tc_type_kind ty            `thenTc` \ (fun_kind, fun_ty) ->
-    returnTc (fun_kind, mkAppTys fun_ty arg_tys)
+  = tcHsType ty                `thenTc` \ fun_ty ->
+    returnNF_Tc (mkAppTys fun_ty arg_tys)
 \end{code}
 
 
 Contexts
 ~~~~~~~~
 \begin{code}
+tcClassContext :: RenamedContext -> TcM s ClassContext
+       -- Used when we are expecting a ClassContext (i.e. no implicit params)
+tcClassContext context
+  = tcContext context  `thenTc` \ theta ->
+    returnTc (classesOfPreds theta)
 
 tcContext :: RenamedContext -> TcM s ThetaType
-tcContext context
-  =    --Someone discovered that @CCallable@ and @CReturnable@
-       -- could be used in contexts such as:
-       --      foo :: CCallable a => a -> PrimIO Int
-       -- Doing this utterly wrecks the whole point of introducing these
-       -- classes so we specifically check that this isn't being done.
-       --
-       -- We *don't* do this check in tcClassAssertion, because that's
-       -- called when checking a HsDictTy, and we don't want to reject
-       --      instance CCallable Int 
-       -- etc. Ugh!
-    mapTc check_naughty context `thenTc_`
-
-    mapTc tcClassAssertion context
-
- where
-   check_naughty (HsPClass class_name _) 
-     = checkTc (not (getUnique class_name `elem` cCallishClassKeys))
-              (naughtyCCallContextErr class_name)
-   check_naughty (HsPIParam _ _) = returnTc ()
-
-tcClassAssertion assn@(HsPClass class_name tys)
-  = tcAddErrCtxt (appKindCtxt (pprHsPred assn))        $
-    mapAndUnzipTc tc_type_kind tys     `thenTc` \ (arg_kinds, arg_tys) ->
-    tcLookupTy class_name              `thenTc` \ (kind, ~(Just arity), thing) ->
+tcContext context = mapTc (tcClassAssertion False) context
+
+tcClassAssertion ccall_ok assn@(HsPClass class_name tys)
+  = tcAddErrCtxt (appKindCtxt (ppr assn))      $
+    mapTc tcHsType tys                         `thenTc` \ arg_tys ->
+    tcLookupTy class_name                      `thenTc` \ thing ->
     case thing of
-       ATyVar  _   -> failWithTc (tyVarAsClassErr class_name)
-       ATyCon  _   -> failWithTc (tyConAsClassErr class_name)
-       AClass clas ->
-                       -- Check with kind mis-match
-               checkTc (arity == n_tys) err                            `thenTc_`
-               unifyKind kind (mkArrowKinds arg_kinds boxedTypeKind)   `thenTc_`
-               returnTc (Class clas arg_tys)
+       AClass clas -> checkTc (arity == n_tys) err                             `thenTc_`
+                      returnTc (Class clas arg_tys)
            where
+               arity = classArity clas
                n_tys = length tys
                err   = arityErr "Class" class_name arity n_tys
-tcClassAssertion assn@(HsPIParam name ty)
-  = tcAddErrCtxt (appKindCtxt (pprHsPred assn))        $
-    tc_type_kind ty    `thenTc` \ (arg_kind, arg_ty) ->
+
+       other -> failWithTc (wrongThingErr "class" thing class_name)
+
+tcClassAssertion ccall_ok assn@(HsPIParam name ty)
+  = tcAddErrCtxt (appKindCtxt (ppr assn))      $
+    tcHsType ty                                        `thenTc` \ arg_ty ->
     returnTc (IParam name arg_ty)
 \end{code}
 
@@ -326,38 +482,19 @@ tcClassAssertion assn@(HsPIParam name ty)
 %************************************************************************
 
 \begin{code}
-tcExtendTopTyVarScope :: TcKind -> [HsTyVar Name]
-                     -> ([TcTyVar] -> TcKind -> TcM s a)
-                     -> TcM s a
-tcExtendTopTyVarScope kind tyvar_names thing_inside
-  = let
-       (tyvars_w_kinds, result_kind) = zipFunTys tyvar_names kind
-       tyvars                        = map mk_tv tyvars_w_kinds
-    in
-    tcExtendTyVarEnv tyvars (thing_inside tyvars result_kind)  
-  where
-    mk_tv (UserTyVar name,    kind) = mkTyVar name kind
-    mk_tv (IfaceTyVar name _, kind) = mkTyVar name kind
-       -- NB: immutable tyvars, but perhaps with mutable kinds
-
-tcExtendTyVarScope :: [HsTyVar Name] 
-                  -> ([TcTyVar] -> TcM s a) -> TcM s a
-tcExtendTyVarScope tv_names thing_inside
-  = mapNF_Tc tcHsTyVar tv_names        `thenNF_Tc` \ tyvars ->
-    tcExtendTyVarEnv tyvars            $
-    thing_inside tyvars
-    
-tcHsTyVar :: HsTyVar Name -> NF_TcM s TcTyVar
-tcHsTyVar (UserTyVar name)       = newKindVar          `thenNF_Tc` \ kind ->
-                                  tcNewMutTyVar name kind
-       -- NB: mutable kind => mutable tyvar, so that zonking can bind
-       -- the tyvar to its immutable form
+mkImmutTyVars :: [(Name,Kind)] -> [TyVar]
+newSigTyVars  :: [(Name,Kind)] -> NF_TcM s [TcTyVar]
 
-tcHsTyVar (IfaceTyVar name kind) = returnNF_Tc (mkTyVar name (kindToTcKind kind))
+mkImmutTyVars pairs = [mkTyVar name kind | (name, kind) <- pairs]
+newSigTyVars  pairs = listNF_Tc [tcNewSigTyVar name kind | (name,kind) <- pairs]
 
-kcHsTyVar :: HsTyVar name -> NF_TcM s TcKind
-kcHsTyVar (UserTyVar name)       = newKindVar
-kcHsTyVar (IfaceTyVar name kind) = returnNF_Tc (kindToTcKind kind)
+mkTyClTyVars :: Kind                   -- Kind of the tycon or class
+            -> [HsTyVarBndr Name]
+            -> [TyVar]
+mkTyClTyVars kind tyvar_names
+  = mkImmutTyVars tyvars_w_kinds
+  where
+    (tyvars_w_kinds, _) = zipFunTys (hsTyVarNames tyvar_names) kind
 \end{code}
 
 
@@ -392,7 +529,7 @@ data TcSigInfo
                                -- Does *not* have name = N
                                -- Has type tau
 
-       Inst                    -- Empty if theta is null, or 
+       [Inst]                  -- Empty if theta is null, or
                                -- (method mono_id) otherwise
 
        SrcLoc                  -- Of the signature
@@ -414,8 +551,9 @@ maybeSig (sig@(TySigInfo sig_name _ _ _ _ _ _ _) : sigs) name
 tcTySig :: RenamedSig -> TcM s TcSigInfo
 
 tcTySig (Sig v ty src_loc)
- = tcAddSrcLoc src_loc $
-   tcHsType ty                                 `thenTc` \ sigma_tc_ty ->
+ = tcAddSrcLoc src_loc                         $ 
+   tcAddErrCtxt (tcsigCtxt v)                  $
+   tcHsSigType ty                              `thenTc` \ sigma_tc_ty ->
    mkTcSig (mkVanillaId v sigma_tc_ty) src_loc `thenNF_Tc` \ sig -> 
    returnTc sig
 
@@ -447,8 +585,9 @@ mkTcSig poly_id src_loc
                tyvar_tys'
                theta' tau'                     `thenNF_Tc` \ inst ->
        -- We make a Method even if it's not overloaded; no harm
+   instFunDeps SignatureOrigin theta'          `thenNF_Tc` \ fds ->
        
-   returnNF_Tc (TySigInfo name poly_id tyvars' theta' tau' (instToIdBndr inst) inst src_loc)
+   returnNF_Tc (TySigInfo name poly_id tyvars' theta' tau' (instToIdBndr inst) (inst : fds) src_loc)
   where
     name = idName poly_id
 \end{code}
@@ -518,12 +657,15 @@ So we revert to ordinary type variables for signatures, and try to
 give a helpful message in checkSigTyVars.
 
 \begin{code}
-checkSigTyVars :: [TcTyVar]            -- The original signature type variables
+checkSigTyVars :: [TcTyVar]            -- Universally-quantified type variables in the signature
+              -> TcTyVarSet            -- Tyvars that are free in the type signature
+                                       -- These should *already* be in the global-var set, and are
+                                       -- used here only to improve the error message
               -> TcM s [TcTyVar]       -- Zonked signature type variables
 
-checkSigTyVars [] = returnTc []
+checkSigTyVars [] free = returnTc []
 
-checkSigTyVars sig_tyvars
+checkSigTyVars sig_tyvars free_tyvars
   = zonkTcTyVars sig_tyvars            `thenNF_Tc` \ sig_tys ->
     tcGetGlobalTyVars                  `thenNF_Tc` \ globals ->
 
@@ -586,9 +728,10 @@ checkSigTyVars sig_tyvars
 
            if tv `elemVarSet` globals  -- Error (c)! Type variable escapes
                                        -- The least comprehensible, so put it last
-           then   tcGetValueEnv                        `thenNF_Tc` \ ve ->
-                  find_globals tv env (valueEnvIds ve) `thenNF_Tc` \ (env1, globs) ->
-                  returnNF_Tc (env1, acc, escape_msg sig_tyvar tv globs : msgs)
+           then   tcGetValueEnv                                        `thenNF_Tc` \ ve ->
+                  find_globals tv env  [] (valueEnvIds ve)             `thenNF_Tc` \ (env1, globs) ->
+                  find_frees   tv env1 [] (varSetElems free_tyvars)    `thenNF_Tc` \ (env2, frees) ->
+                  returnNF_Tc (env2, acc, escape_msg sig_tyvar tv globs frees : msgs)
 
            else        -- All OK
            returnNF_Tc (env, extendVarEnv acc tv sig_tyvar, msgs)
@@ -598,37 +741,57 @@ checkSigTyVars sig_tyvars
 -- whose types mention the offending type variable.  It has to be 
 -- careful to zonk the Id's type first, so it has to be in the monad.
 -- We must be careful to pass it a zonked type variable, too.
-find_globals tv tidy_env ids
-  | null ids
-  = returnNF_Tc (tidy_env, [])
+find_globals tv tidy_env acc []
+  = returnNF_Tc (tidy_env, acc)
 
-find_globals tv tidy_env (id:ids) 
+find_globals tv tidy_env acc (id:ids) 
   | not (isLocallyDefined id) ||
     isEmptyVarSet (idFreeTyVars id)
-  = find_globals tv tidy_env ids
+  = find_globals tv tidy_env acc ids
 
   | otherwise
   = zonkTcType (idType id)     `thenNF_Tc` \ id_ty ->
     if tv `elemVarSet` tyVarsOfType id_ty then
        let 
           (tidy_env', id_ty') = tidyOpenType tidy_env id_ty
+          acc'                = (idName id, id_ty') : acc
        in
-       find_globals tv tidy_env' ids   `thenNF_Tc` \ (tidy_env'', globs) ->
-       returnNF_Tc (tidy_env'', (idName id, id_ty') : globs)
+       find_globals tv tidy_env' acc' ids
     else
-       find_globals tv tidy_env ids
+       find_globals tv tidy_env  acc  ids
 
-escape_msg sig_tv tv globs
-  = vcat [mk_msg sig_tv <+> ptext SLIT("escapes"),
-         pp_escape,
-         ptext SLIT("The following variables in the environment mention") <+> quotes (ppr tv),
-         nest 4 (vcat_first 10 [ppr name <+> dcolon <+> ppr ty | (name,ty) <- globs])
-    ]
+find_frees tv tidy_env acc []
+  = returnNF_Tc (tidy_env, acc)
+find_frees tv tidy_env acc (ftv:ftvs)
+  = zonkTcTyVar ftv    `thenNF_Tc` \ ty ->
+    if tv `elemVarSet` tyVarsOfType ty then
+       let
+           (tidy_env', ftv') = tidyTyVar tidy_env ftv
+       in
+       find_frees tv tidy_env' (ftv':acc) ftvs
+    else
+       find_frees tv tidy_env  acc        ftvs
+
+
+escape_msg sig_tv tv globs frees
+  = mk_msg sig_tv <+> ptext SLIT("escapes") $$
+    if not (null globs) then
+       vcat [pp_it <+> ptext SLIT("is mentioned in the environment"),
+             ptext SLIT("The following variables in the environment mention") <+> quotes (ppr tv),
+             nest 2 (vcat_first 10 [ppr name <+> dcolon <+> ppr ty | (name,ty) <- globs])
+       ]
+     else if not (null frees) then
+       vcat [ptext SLIT("It is reachable from the type variable(s)") <+> pprQuotedList frees,
+             nest 2 (ptext SLIT("which") <+> is_are <+> ptext SLIT("free in the signature"))
+       ]
+     else
+       empty   -- Sigh.  It's really hard to give a good error message
+               -- all the time.   One bad case is an existential pattern match
   where
-    pp_escape | sig_tv /= tv = ptext SLIT("It unifies with") <+>
-                              quotes (ppr tv) <> comma <+>
-                              ptext SLIT("which is mentioned in the environment")
-             | otherwise    = ptext SLIT("It is mentioned in the environment")
+    is_are | isSingleton frees = ptext SLIT("is")
+          | otherwise         = ptext SLIT("are")
+    pp_it | sig_tv /= tv = ptext SLIT("It unifies with") <+> quotes (ppr tv) <> comma <+> ptext SLIT("which")
+         | otherwise    = ptext SLIT("It")
 
     vcat_first :: Int -> [SDoc] -> SDoc
     vcat_first n []     = empty
@@ -642,13 +805,20 @@ mk_msg tv          = ptext SLIT("Quantified type variable") <+> quotes (ppr tv)
 These two context are used with checkSigTyVars
     
 \begin{code}
-sigCtxt :: (Type -> Message) -> Type
+sigCtxt :: Message -> [TcTyVar] -> TcThetaType -> TcTauType
        -> TidyEnv -> NF_TcM s (TidyEnv, Message)
-sigCtxt mk_msg sig_ty tidy_env
-  = let
-       (env1, tidy_sig_ty) = tidyOpenType tidy_env sig_ty
+sigCtxt when sig_tyvars sig_theta sig_tau tidy_env
+  = zonkTcType sig_tau         `thenNF_Tc` \ actual_tau ->
+    let
+       (env1, tidy_sig_tyvars)  = tidyTyVars tidy_env sig_tyvars
+       (env2, tidy_sig_rho)     = tidyOpenType env1 (mkRhoTy sig_theta sig_tau)
+       (env3, tidy_actual_tau)  = tidyOpenType env2 actual_tau
+       msg = vcat [ptext SLIT("Signature type:    ") <+> pprType (mkForAllTys tidy_sig_tyvars tidy_sig_rho),
+                   ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau,
+                   when
+                  ]
     in
-    returnNF_Tc (env1, mk_msg tidy_sig_ty)
+    returnNF_Tc (env3, msg)
 
 sigPatCtxt bound_tvs bound_ids tidy_env
   = returnNF_Tc (env1,
@@ -671,9 +841,7 @@ sigPatCtxt bound_tvs bound_ids tidy_env
 %************************************************************************
 
 \begin{code}
-naughtyCCallContextErr clas_name
-  = sep [ptext SLIT("Can't use class") <+> quotes (ppr clas_name), 
-        ptext SLIT("in a context")]
+tcsigCtxt v   = ptext SLIT("In a type signature for") <+> quotes (ppr v)
 
 typeCtxt ty = ptext SLIT("In the type") <+> quotes (ppr ty)
 
@@ -685,17 +853,22 @@ typeKindCtxt ty = sep [ptext SLIT("When checking that"),
 appKindCtxt :: SDoc -> Message
 appKindCtxt pp = ptext SLIT("When checking kinds in") <+> quotes pp
 
-classAsTyConErr name
-  = ptext SLIT("Class used as a type constructor:") <+> ppr name
-
-tyConAsClassErr name
-  = ptext SLIT("Type constructor used as a class:") <+> ppr name
-
-tyVarAsClassErr name
-  = ptext SLIT("Type variable used as a class:") <+> ppr name
+wrongThingErr expected actual name
+  = pp_actual actual <+> quotes (ppr name) <+> ptext SLIT("used as a") <+> text expected
+  where
+    pp_actual (ATyCon _) = ptext SLIT("Type constructor")
+    pp_actual (AClass _) = ptext SLIT("Class")
+    pp_actual (ATyVar _) = ptext SLIT("Type variable")
+    pp_actual (AThing _) = ptext SLIT("Utterly bogus")
 
-ambigErr (c, ts) ty
-  = sep [ptext SLIT("Ambiguous constraint") <+> quotes (pprConstraint c ts),
+ambigErr pred ty
+  = sep [ptext SLIT("Ambiguous constraint") <+> quotes (pprPred pred),
         nest 4 (ptext SLIT("for the type:") <+> ppr ty),
-        nest 4 (ptext SLIT("Each forall'd type variable mentioned by the constraint must appear after the =>."))]
+        nest 4 (ptext SLIT("Each forall'd type variable mentioned by the constraint must appear after the =>"))]
+
+freeErr pred ty
+  = sep [ptext SLIT("The constraint") <+> quotes (pprPred pred) <+>
+                  ptext SLIT("does not mention any of the universally quantified type variables"),
+        nest 4 (ptext SLIT("in the type") <+> quotes (ppr ty))
+    ]
 \end{code}