[project @ 1998-08-14 12:42:01 by sof]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreLint.lhs
index cff9392..7dada83 100644 (file)
@@ -4,50 +4,55 @@
 \section[CoreLint]{A ``lint'' pass to check for Core correctness}
 
 \begin{code}
-#include "HsVersions.h"
-
 module CoreLint (
        lintCoreBindings,
        lintUnfolding
     ) where
 
-IMP_Ubiq()
+#include "HsVersions.h"
 
+import IO      ( hPutStr, stderr )
+
+import CmdLineOpts      ( opt_D_show_passes, opt_DoCoreLinting )
 import CoreSyn
+import CoreUtils       ( idSpecVars )
 
 import Bag
 import Kind            ( hasMoreBoxityInfo, Kind{-instance-} )
 import Literal         ( literalType, Literal{-instance-} )
-import Id              ( idType, isBottomingId, dataConRepType,
+import Id              ( idType, isBottomingId, dataConRepType, isDataCon, isAlgCon,
                          dataConArgTys, GenId{-instances-},
-                         emptyIdSet, mkIdSet, intersectIdSets,
-                         unionIdSets, elementOfIdSet, SYN_IE(IdSet)
+                         emptyIdSet, mkIdSet, 
+                         unionIdSets, elementOfIdSet, IdSet,
+                         Id
                        )
 import Maybes          ( catMaybes )
-import Name            ( isLocallyDefined, getSrcLoc, Name{-instance NamedThing-} )
-import Outputable      ( Outputable(..){-instance * []-} )
+import Name            ( isLocallyDefined, getSrcLoc, Name{-instance NamedThing-},
+                         NamedThing(..)
+                       )
 import PprCore
-import PprStyle                ( PprStyle(..) )
-import PprType         ( GenType, GenTyVar, TyCon )
-import Pretty
-import PrimOp          ( primOpType, PrimOp(..) )
+import ErrUtils                ( doIfSet, ghcExit )
+import PrimOp          ( primOpType )
 import PrimRep         ( PrimRep(..) )
 import SrcLoc          ( SrcLoc )
-import Type            ( mkFunTy,getFunTy_maybe,mkForAllTy,mkForAllTys,getForAllTy_maybe,
-                         getFunTyExpandingDicts_maybe,
-                         getForAllTyExpandingDicts_maybe,
-                         isPrimType,typeKind,instantiateTy,splitSigmaTy,
-                         mkForAllUsageTy,getForAllUsageTy,instantiateUsage,
-                         maybeAppDataTyConExpandingDicts, eqTy
---                       ,expandTy -- ToDo:rm
+import Type            ( mkFunTy, splitFunTy_maybe, mkForAllTy,
+                         splitForAllTy_maybe, tyVarsOfType,
+                         isUnpointedType, typeKind, instantiateTy,
+                         splitAlgTyConApp_maybe, Type
                        )
-import TyCon           ( isPrimTyCon )
-import TyVar           ( tyVarKind, GenTyVar{-instances-} )
+import TyCon           ( TyCon, isPrimTyCon, isDataTyCon )
+import TyVar           ( TyVar, tyVarKind, mkTyVarEnv, 
+                         TyVarSet,
+                           emptyTyVarSet, mkTyVarSet, isEmptyTyVarSet, 
+                           minusTyVarSet, elementOfTyVarSet, tyVarSetToList,
+                           unionTyVarSets, intersectTyVarSets
+                       )
+import ErrUtils                ( ErrMsg )
 import Unique          ( Unique )
-import Usage           ( GenUsage, SYN_IE(Usage) )
-import Util            ( zipEqual, pprTrace, pprPanic, assertPanic, panic )
+import Util            ( zipEqual )
+import Outputable
 
-infixr 9 `thenL`, `seqL`, `thenMaybeL`, `seqMaybeL`
+infixr 9 `thenL`, `seqL`, `thenMaybeL`
 \end{code}
 
 %************************************************************************
@@ -84,25 +89,33 @@ Outstanding issues:
     --
 
 \begin{code}
-lintCoreBindings
-       :: PprStyle -> String -> Bool -> [CoreBinding] -> [CoreBinding]
+lintCoreBindings :: String -> Bool -> [CoreBinding] -> IO ()
+
+lintCoreBindings whoDunnit spec_done binds
+  | not opt_DoCoreLinting
+  = return ()
 
-lintCoreBindings sty whoDunnit spec_done binds
+lintCoreBindings whoDunnit spec_done binds
   = case (initL (lint_binds binds) spec_done) of
-      Nothing  -> binds
-      Just msg ->
-       pprPanic "" (ppAboves [
-         ppStr ("*** Core Lint Errors: in " ++ whoDunnit ++ " ***"),
-         msg sty,
-         ppPStr SLIT("*** Offending Program ***"),
-         ppAboves (map (pprCoreBinding sty) binds),
-         ppPStr SLIT("*** End of Offense ***")
-       ])
+      Nothing       -> doIfSet opt_D_show_passes
+                       (hPutStr stderr ("*** Core Linted result of " ++ whoDunnit ++ "\n"))
+
+      Just bad_news -> printDump (display bad_news)    >>
+                      ghcExit 1
   where
     lint_binds [] = returnL ()
     lint_binds (bind:binds)
       = lintCoreBinding bind `thenL` \binders ->
        addInScopeVars binders (lint_binds binds)
+
+    display bad_news
+      = vcat [
+               text ("*** Core Lint Errors: in result of " ++ whoDunnit ++ " ***"),
+               bad_news,
+               ptext SLIT("*** Offending Program ***"),
+               pprCoreBindings binds,
+               ptext SLIT("*** End of Offense ***")
+       ]
 \end{code}
 
 %************************************************************************
@@ -125,10 +138,10 @@ lintUnfolding locn expr
       Nothing  -> Just expr
       Just msg ->
         pprTrace "WARNING: Discarded bad unfolding from interface:\n"
-       (ppAboves [msg PprForUser,
-                  ppPStr SLIT("*** Bad unfolding ***"),
-                  ppr PprDebug expr,
-                  ppPStr SLIT("*** End unfolding ***")])
+       (vcat [msg,
+                  ptext SLIT("*** Bad unfolding ***"),
+                  ppr expr,
+                  ptext SLIT("*** End unfolding ***")])
        Nothing
 \end{code}
 
@@ -165,13 +178,19 @@ lintSingleBinding (binder,rhs)
          Just ty -> checkTys (idType binder) ty (mkRhsMsg binder ty))
 
        `seqL`
-       -- Check (not isPrimType)
-       checkIfSpecDoneL (not (isPrimType (idType binder)))
-         (mkRhsPrimMsg binder rhs)
+       -- Check (not isUnpointedType)
+       checkIfSpecDoneL (not (isUnpointedType (idType binder)))
+         (mkRhsPrimMsg binder rhs)  `seqL`
 
+        -- Check whether binder's specialisations contain any out-of-scope variables
+        ifSpecDoneL (mapL (checkSpecIdInScope binder) spec_vars `seqL` returnL ())
+         
        -- We should check the unfolding, if any, but this is tricky because
        -- the unfolding is a SimplifiableCoreExpr. Give up for now.
     )
+    where
+     spec_vars = idSpecVars binder
+
 \end{code}
 
 %************************************************************************
@@ -183,11 +202,31 @@ lintSingleBinding (binder,rhs)
 \begin{code}
 lintCoreExpr :: CoreExpr -> LintM (Maybe Type) -- Nothing if error found
 
-lintCoreExpr (Var var) = checkInScope var `seqL` returnL (Just (idType var))
+lintCoreExpr (Var var) 
+  | isAlgCon var = returnL (Just (idType var))
+       -- Micro-hack here... Class decls generate applications of their
+       -- dictionary constructor, but don't generate a binding for the
+       -- constructor (since it would never be used).  After a single round
+       -- of simplification, these dictionary constructors have been
+       -- inlined (from their UnfoldInfo) to CoCons.  Just between
+       -- desugaring and simplfication, though, they appear as naked, unbound
+       -- variables as the function in an application.
+       -- The hack here simply doesn't check for out-of-scope-ness for
+       -- data constructors (at least, in a function position).
+
+  | otherwise    = checkIdInScope var `seqL` returnL (Just (idType var))
+
 lintCoreExpr (Lit lit) = returnL (Just (literalType lit))
-lintCoreExpr (SCC _ expr) = lintCoreExpr expr
-lintCoreExpr (Coerce _ ty expr)
-  = lintCoreExpr expr `seqL` returnL (Just ty)
+
+lintCoreExpr (Note (Coerce to_ty from_ty) expr)
+  = lintCoreExpr expr  `thenMaybeL` \ expr_ty ->
+    lintTy to_ty       `seqL`
+    lintTy from_ty     `seqL`
+    checkTys from_ty expr_ty (mkCoerceErr from_ty expr_ty)     `seqL`
+    returnL (Just to_ty)
+
+lintCoreExpr (Note other_note expr)
+  = lintCoreExpr expr
 
 lintCoreExpr (Let binds body)
   = lintCoreBinding binds `thenL` \binders ->
@@ -198,7 +237,8 @@ lintCoreExpr (Let binds body)
        (addInScopeVars binders (lintCoreExpr body))
 
 lintCoreExpr e@(Con con args)
-  = lintCoreArgs {-False-} e (dataConRepType con) args
+  = checkL (isDataCon con) (mkConErrMsg e)     `seqL`
+    lintCoreArgs {-False-} e (dataConRepType con) args
     -- Note: we don't check for primitive types in these arguments
 
 lintCoreExpr e@(Prim op args)
@@ -213,16 +253,17 @@ lintCoreExpr e@(App fun arg)
   = lintCoreExpr fun `thenMaybeL` \ty -> lintCoreArg {-True-} e ty arg
     -- Note: we do check for primitive types in this argument
 
-lintCoreExpr (Lam (ValBinder var) expr)
-  = addLoc (LambdaBodyOf var)
+lintCoreExpr (Lam vb@(ValBinder var) expr)
+  = addLoc (LambdaBodyOf vb)
       (addInScopeVars [var]
        (lintCoreExpr expr `thenMaybeL` \ty ->
         returnL (Just (mkFunTy (idType var) ty))))
 
-lintCoreExpr (Lam (TyBinder tyvar) expr)
-  = lintCoreExpr expr `thenMaybeL` \ty ->
-    returnL (Just(mkForAllTy tyvar ty))
-    -- ToDo: Should add in-scope type variable at this point
+lintCoreExpr (Lam tb@(TyBinder tyvar) expr)
+  = addLoc (LambdaBodyOf tb)  $
+     addInScopeTyVars [tyvar] $
+       lintCoreExpr expr                          `thenMaybeL` \ ty ->
+       returnL (Just(mkForAllTy tyvar ty))
 
 lintCoreExpr e@(Case scrut alts)
  = lintCoreExpr scrut `thenMaybeL` \ty ->
@@ -258,25 +299,26 @@ lintCoreArg :: {-Bool ->-} CoreExpr -> Type -> CoreArg -> LintM (Maybe Type)
 
 lintCoreArg e ty (LitArg lit)
   = -- Make sure function type matches argument
-    case (getFunTyExpandingDicts_maybe False{-no peeking in newtypes-} ty) of
-      Just (arg,res) | (lit_ty `eqTy` arg) -> returnL(Just res)
+    case (splitFunTy_maybe ty) of
+      Just (arg,res) | (lit_ty == arg) -> returnL(Just res)
       _ -> addErrL (mkAppMsg ty lit_ty e) `seqL` returnL Nothing
   where
     lit_ty = literalType lit
 
 lintCoreArg e ty (VarArg v)
   = -- Make sure variable is bound
-    checkInScope v `seqL`
+    checkIdInScope v `seqL`
     -- Make sure function type matches argument
-    case (getFunTyExpandingDicts_maybe False{-as above-} ty) of
-      Just (arg,res) | (var_ty `eqTy` arg) -> returnL(Just res)
+    case (splitFunTy_maybe ty) of
+      Just (arg,res) | (var_ty == arg) -> returnL(Just res)
       _ -> addErrL (mkAppMsg ty var_ty e) `seqL` returnL Nothing
   where
     var_ty = idType v
 
 lintCoreArg e ty a@(TyArg arg_ty)
-  = -- ToDo: Check that ty is well-kinded and has no unbound tyvars
-    case (getForAllTyExpandingDicts_maybe ty) of
+  = lintTy arg_ty                           `seqL`
+    checkTyVarsInScope (tyVarsOfType arg_ty) `seqL`
+    case (splitForAllTy_maybe ty) of
       Nothing -> addErrL (mkTyAppMsg SLIT("Illegal") ty arg_ty e) `seqL` returnL Nothing
 
       Just (tyvar,body) ->
@@ -290,18 +332,10 @@ lintCoreArg e ty a@(TyArg arg_ty)
                --      error :: forall a:*. String -> a
                -- and then apply it to both boxed and unboxed types.
         then
-           returnL(Just(instantiateTy [(tyvar,arg_ty)] body))
+           returnL(Just(instantiateTy (mkTyVarEnv [(tyvar,arg_ty)]) body))
        else
-           pprTrace "lintCoreArg:kinds:" (ppCat [ppr PprDebug tyvar_kind, ppr PprDebug argty_kind]) $
-           addErrL (mkTyAppMsg SLIT("Kinds not right in") ty arg_ty e) `seqL` returnL Nothing
-       
-lintCoreArg e ty (UsageArg u)
-  = -- ToDo: Check that usage has no unbound usage variables
-    case (getForAllUsageTy ty) of
-      Just (uvar,bounds,body) ->
-        -- ToDo: Check argument satisfies bounds
-        returnL(Just(panic "lintCoreArg:instantiateUsage uvar u body"))
-      _ -> addErrL (mkUsageAppMsg ty u e) `seqL` returnL Nothing
+           pprTrace "lintCoreArg:kinds:" (hsep [ppr tyvar_kind, ppr argty_kind]) $
+           addErrL (mkKindErrMsg tyvar arg_ty e) `seqL` returnL Nothing
 \end{code}
 
 %************************************************************************
@@ -354,11 +388,9 @@ lintCoreAlts whole_alts@(PrimAlts alts deflt) ty --tycon
        where
          check ty = checkTys first_ty ty (mkCaseAltMsg whole_alts)
 
-lintAlgAlt scrut_ty {-tycon-ToDo: use it!-} (con,args,rhs)
-  = (case maybeAppDataTyConExpandingDicts scrut_ty of
-      Nothing ->
-        addErrL (mkAlgAltMsg1 scrut_ty)
-      Just (tycon, tys_applied, cons) ->
+lintAlgAlt scrut_ty (con,args,rhs)
+  = (case splitAlgTyConApp_maybe scrut_ty of
+      Just (tycon, tys_applied, cons) | isDataTyCon tycon ->
         let
           arg_tys = dataConArgTys con tys_applied
         in
@@ -367,6 +399,8 @@ lintAlgAlt scrut_ty {-tycon-ToDo: use it!-} (con,args,rhs)
                                                                 `seqL`
         mapL check (zipEqual "lintAlgAlt" arg_tys args)         `seqL`
         returnL ()
+
+      other -> addErrL (mkAlgAltMsg1 scrut_ty)
     )                                                           `seqL`
     addInScopeVars args        (
         lintCoreExpr rhs
@@ -392,6 +426,19 @@ lintDeflt deflt@(BindDefault binder rhs) ty
 
 %************************************************************************
 %*                                                                     *
+\subsection[lint-types]{Types}
+%*                                                                     *
+%************************************************************************
+
+\begin{code}
+lintTy :: Type -> LintM ()
+lintTy ty = returnL ()
+-- ToDo: Check that ty is well-kinded and has no unbound tyvars
+\end{code}
+
+    
+%************************************************************************
+%*                                                                     *
 \subsection[lint-monad]{The Lint monad}
 %*                                                                     *
 %************************************************************************
@@ -400,75 +447,72 @@ lintDeflt deflt@(BindDefault binder rhs) ty
 type LintM a = Bool            -- True <=> specialisation has been done
            -> [LintLocInfo]    -- Locations
            -> IdSet            -- Local vars in scope
+           -> TyVarSet         -- Local tyvars in scope
            -> Bag ErrMsg       -- Error messages so far
            -> (a, Bag ErrMsg)  -- Result and error messages (if any)
 
-type ErrMsg = PprStyle -> Pretty
-
 data LintLocInfo
-  = RhsOf Id           -- The variable bound
-  | LambdaBodyOf Id    -- The lambda-binder
-  | BodyOfLetRec [Id]  -- One of the binders
-  | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
+  = RhsOf Id                   -- The variable bound
+  | LambdaBodyOf CoreBinder    -- The lambda-binder
+  | BodyOfLetRec [Id]          -- One of the binders
+  | ImportedUnfolding SrcLoc    -- Some imported unfolding (ToDo: say which)
 
 instance Outputable LintLocInfo where
-    ppr sty (RhsOf v)
-      = ppBesides [ppr sty (getSrcLoc v), ppPStr SLIT(": [RHS of "), pp_binders sty [v], ppChar ']']
+    ppr (RhsOf v)
+      = ppr (getSrcLoc v) <> colon <+> 
+       brackets (ptext SLIT("RHS of") <+> pp_binders [v])
 
-    ppr sty (LambdaBodyOf b)
-      = ppBesides [ppr sty (getSrcLoc b),
-               ppPStr SLIT(": [in body of lambda with binder "), pp_binder sty b, ppChar ']']
+    ppr (LambdaBodyOf (ValBinder b))
+      = ppr (getSrcLoc b) <> colon <+>
+       brackets (ptext SLIT("in body of lambda with binder") <+> pp_binder b)
 
-    ppr sty (BodyOfLetRec bs)
-      = ppBesides [ppr sty (getSrcLoc (head bs)),
-               ppPStr SLIT(": [in body of letrec with binders "), pp_binders sty bs, ppChar ']']
+    ppr (LambdaBodyOf (TyBinder b))
+      = ppr (getSrcLoc b) <> colon <+>
+       brackets (ptext SLIT("in body of lambda with type binder") <+> ppr b)
 
-    ppr sty (ImportedUnfolding locn)
-      = ppBeside (ppr sty locn) (ppPStr SLIT(": [in an imported unfolding]"))
+    ppr (BodyOfLetRec bs)
+      = ppr (getSrcLoc (head bs)) <> colon <+>
+       brackets (ptext SLIT("in body of letrec with binders") <+> pp_binders bs)
 
-pp_binders :: PprStyle -> [Id] -> Pretty
-pp_binders sty bs = ppInterleave ppComma (map (pp_binder sty) bs)
+    ppr (ImportedUnfolding locn)
+      = ppr locn <> colon <+>
+       brackets (ptext SLIT("in an imported unfolding"))
 
-pp_binder :: PprStyle -> Id -> Pretty
-pp_binder sty b = ppCat [ppr sty b, ppStr "::", ppr sty (idType b)]
+pp_binders :: [Id] -> SDoc
+pp_binders bs = sep (punctuate comma (map pp_binder bs))
+
+pp_binder :: Id -> SDoc
+pp_binder b = hsep [ppr b, text "::", ppr (idType b)]
 \end{code}
 
 \begin{code}
 initL :: LintM a -> Bool -> Maybe ErrMsg
 initL m spec_done
-  = case (m spec_done [] emptyIdSet emptyBag) of { (_, errs) ->
+  = case (m spec_done [] emptyIdSet emptyTyVarSet emptyBag) of { (_, errs) ->
     if isEmptyBag errs then
        Nothing
     else
-       Just ( \ sty ->
-         ppAboves [ msg sty | msg <- bagToList errs ]
-       )
+       Just (vcat (bagToList errs))
     }
 
 returnL :: a -> LintM a
-returnL r spec loc scope errs = (r, errs)
+returnL r spec loc scope tyscope errs = (r, errs)
 
 thenL :: LintM a -> (a -> LintM b) -> LintM b
-thenL m k spec loc scope errs
-  = case m spec loc scope errs of
-      (r, errs') -> k r spec loc scope errs'
+thenL m k spec loc scope tyscope errs
+  = case m spec loc scope tyscope errs of
+      (r, errs') -> k r spec loc scope tyscope errs'
 
 seqL :: LintM a -> LintM b -> LintM b
-seqL m k spec loc scope errs
-  = case m spec loc scope errs of
-      (_, errs') -> k spec loc scope errs'
+seqL m k spec loc scope tyscope errs
+  = case m spec loc scope tyscope errs of
+      (_, errs') -> k spec loc scope tyscope errs'
 
 thenMaybeL :: LintM (Maybe a) -> (a -> LintM (Maybe b)) -> LintM (Maybe b)
-thenMaybeL m k spec loc scope errs
-  = case m spec loc scope errs of
-      (Nothing, errs2) -> (Nothing, errs2)
-      (Just r,  errs2) -> k r spec loc scope errs2
-
-seqMaybeL :: LintM (Maybe a) -> LintM (Maybe b) -> LintM (Maybe b)
-seqMaybeL m k spec loc scope errs
-  = case m spec loc scope errs of
+thenMaybeL m k spec loc scope tyscope errs
+  = case m spec loc scope tyscope errs of
       (Nothing, errs2) -> (Nothing, errs2)
-      (Just _,  errs2) -> k spec loc scope errs2
+      (Just r,  errs2) -> k r spec loc scope tyscope errs2
 
 mapL :: (a -> LintM b) -> [a] -> LintM [b]
 mapL f [] = returnL []
@@ -488,34 +532,33 @@ mapMaybeL f (x:xs)
 
 \begin{code}
 checkL :: Bool -> ErrMsg -> LintM ()
-checkL True  msg spec loc scope errs = ((), errs)
-checkL False msg spec loc scope errs = ((), addErr errs msg loc)
+checkL True  msg spec loc scope tyscope errs = ((), errs)
+checkL False msg spec loc scope tyscope errs = ((), addErr errs msg loc)
 
 checkIfSpecDoneL :: Bool -> ErrMsg -> LintM ()
-checkIfSpecDoneL True  msg spec  loc scope errs = ((), errs)
-checkIfSpecDoneL False msg True  loc scope errs = ((), addErr errs msg loc)
-checkIfSpecDoneL False msg False loc scope errs = ((), errs)
+checkIfSpecDoneL True  msg spec  loc scope tyscope errs = ((), errs)
+checkIfSpecDoneL False msg True  loc scope tyscope errs = ((), addErr errs msg loc)
+checkIfSpecDoneL False msg False loc scope tyscope errs = ((), errs)
 
-addErrIfL pred spec
-  = if pred then addErrL spec else returnL ()
+ifSpecDoneL :: LintM () -> LintM ()
+ifSpecDoneL m False loc scope tyscope errs = ((), errs)
+ifSpecDoneL m True  loc scope tyscope errs = m True loc scope tyscope errs
 
 addErrL :: ErrMsg -> LintM ()
-addErrL msg spec loc scope errs = ((), addErr errs msg loc)
+addErrL msg spec loc scope tyscope errs = ((), addErr errs msg loc)
 
 addErr :: Bag ErrMsg -> ErrMsg -> [LintLocInfo] -> Bag ErrMsg
 
 addErr errs_so_far msg locs
   = ASSERT (not (null locs))
-    errs_so_far `snocBag` ( \ sty ->
-    ppHang (ppr sty (head locs)) 4 (msg sty)
-    )
+    errs_so_far `snocBag` (hang (ppr (head locs)) 4 msg)
 
 addLoc :: LintLocInfo -> LintM a -> LintM a
-addLoc extra_loc m spec loc scope errs
-  = m spec (extra_loc:loc) scope errs
+addLoc extra_loc m spec loc scope tyscope errs
+  = m spec (extra_loc:loc) scope tyscope errs
 
 addInScopeVars :: [Id] -> LintM a -> LintM a
-addInScopeVars ids m spec loc scope errs
+addInScopeVars ids m spec loc scope tyscope errs
   = -- We check if these "new" ids are already
     -- in scope, i.e., we have *shadowing* going on.
     -- For now, it's just a "trace"; we may make
@@ -529,137 +572,155 @@ addInScopeVars ids m spec loc scope errs
 --  names after all.  WDP 94/07
 --  (if isEmptyUniqSet shadowed
 --  then id
---  else pprTrace "Shadowed vars:" (ppr PprDebug (uniqSetToList shadowed))) (
-    m spec loc (scope `unionIdSets` new_set) errs
+--  else pprTrace "Shadowed vars:" (ppr (uniqSetToList shadowed))) (
+    m spec loc (scope `unionIdSets` new_set) tyscope errs
 --  )
+
+addInScopeTyVars :: [TyVar] -> LintM a -> LintM a
+addInScopeTyVars tyvars m spec loc scope tyscope errs
+  = m spec loc scope (tyscope `unionTyVarSets` new_set) errs
+    where
+     new_set   = mkTyVarSet tyvars
+    
 \end{code}
 
 \begin{code}
-checkInScope :: Id -> LintM ()
-checkInScope id spec loc scope errs
+checkIdInScope :: Id -> LintM ()
+checkIdInScope id 
+  = checkInScope (ptext SLIT("is out of scope")) id
+
+checkSpecIdInScope :: Id -> Id -> LintM ()
+checkSpecIdInScope binder id 
+  = checkInScope msg id
+    where
+     msg = ptext SLIT("is out of scope inside specialisation info for") <+> 
+          ppr binder
+
+checkInScope :: SDoc -> Id -> LintM ()
+checkInScope loc_msg id spec loc scope tyscope errs
   = let
        id_name = getName id
     in
     if isLocallyDefined id_name && not (id `elementOfIdSet` scope) then
-      ((),addErr errs (\sty -> ppCat [ppr sty id, ppPStr SLIT("is out of scope")]) loc)
+      ((), addErr errs (hsep [ppr id, loc_msg]) loc)
     else
       ((),errs)
 
+checkTyVarsInScope :: TyVarSet -> LintM ()
+checkTyVarsInScope tyvars spec loc scope tyscope errs
+-- | not (isEmptyTyVarSet out_of_scope) = ((), errs')
+ | otherwise                   = ((), errs)
+   where
+    out_of_scope = tyvars `minusTyVarSet` tyscope
+    errs'        = 
+       foldr (\ tv errs -> addErr errs (hsep [ppr tv, ptext SLIT("is out of scope")]) loc)
+            errs
+            (tyVarSetToList out_of_scope)
+
 checkTys :: Type -> Type -> ErrMsg -> LintM ()
-checkTys ty1 ty2 msg spec loc scope errs
-  = if ty1 `eqTy` ty2 then ((), errs) else ((), addErr errs msg loc)
+checkTys ty1 ty2 msg spec loc scope tyscope errs
+  = if ty1 == ty2 then ((), errs) else ((), addErr errs msg loc)
 \end{code}
 
 \begin{code}
-mkCaseAltMsg :: CoreCaseAlts -> ErrMsg
-mkCaseAltMsg alts sty
-  = ppAbove (ppPStr SLIT("Type of case alternatives not the same:"))
-           (ppr sty alts)
+mkConErrMsg e
+  = ($$) (ptext SLIT("Application of newtype constructor:"))
+           (ppr e)
 
-mkCaseDataConMsg :: CoreExpr -> ErrMsg
-mkCaseDataConMsg expr sty
-  = ppAbove (ppPStr SLIT("A case scrutinee not of data constructor type:"))
-           (pp_expr sty expr)
 
-mkCaseNotPrimMsg :: TyCon -> ErrMsg
-mkCaseNotPrimMsg tycon sty
-  = ppAbove (ppPStr SLIT("A primitive case on a non-primitive type:"))
-           (ppr sty tycon)
-
-mkCasePrimMsg :: TyCon -> ErrMsg
-mkCasePrimMsg tycon sty
-  = ppAbove (ppPStr SLIT("An algebraic case on a primitive type:"))
-           (ppr sty tycon)
+mkCaseAltMsg :: CoreCaseAlts -> ErrMsg
+mkCaseAltMsg alts
+  = ($$) (ptext SLIT("Type of case alternatives not the same:"))
+           (ppr alts)
 
 mkCaseAbstractMsg :: TyCon -> ErrMsg
-mkCaseAbstractMsg tycon sty
-  = ppAbove (ppPStr SLIT("An algebraic case on some weird type:"))
-           (ppr sty tycon)
+mkCaseAbstractMsg tycon
+  = ($$) (ptext SLIT("An algebraic case on some weird type:"))
+           (ppr tycon)
 
 mkDefltMsg :: CoreCaseDefault -> ErrMsg
-mkDefltMsg deflt sty
-  = ppAbove (ppPStr SLIT("Binder in case default doesn't match type of scrutinee:"))
-           (ppr sty deflt)
+mkDefltMsg deflt
+  = ($$) (ptext SLIT("Binder in case default doesn't match type of scrutinee:"))
+           (ppr deflt)
 
 mkAppMsg :: Type -> Type -> CoreExpr -> ErrMsg
-mkAppMsg fun arg expr sty
-  = ppAboves [ppPStr SLIT("Argument value doesn't match argument type:"),
-             ppHang (ppPStr SLIT("Fun type:")) 4 (ppr sty fun),
-             ppHang (ppPStr SLIT("Arg type:")) 4 (ppr sty arg),
-             ppHang (ppPStr SLIT("Expression:")) 4 (pp_expr sty expr)]
+mkAppMsg fun arg expr
+  = vcat [ptext SLIT("Argument value doesn't match argument type:"),
+             hang (ptext SLIT("Fun type:")) 4 (ppr fun),
+             hang (ptext SLIT("Arg type:")) 4 (ppr arg),
+             hang (ptext SLIT("Expression:")) 4 (pprCoreExpr expr)]
+
+mkKindErrMsg :: TyVar -> Type -> CoreExpr -> ErrMsg
+mkKindErrMsg tyvar arg_ty expr
+  = vcat [ptext SLIT("Kinds don't match in type application:"),
+         hang (ptext SLIT("Type variable:"))
+                4 (ppr tyvar <+> ptext SLIT("::") <+> ppr (tyVarKind tyvar)),
+         hang (ptext SLIT("Arg type:"))   
+                4 (ppr arg_ty <+> ptext SLIT("::") <+> ppr (typeKind arg_ty)),
+         hang (ptext SLIT("Expression:")) 4 (pprCoreExpr expr)]
 
 mkTyAppMsg :: FAST_STRING -> Type -> Type -> CoreExpr -> ErrMsg
-mkTyAppMsg msg ty arg expr sty
-  = ppAboves [ppCat [ppPStr msg, ppPStr SLIT("type application:")],
-             ppHang (ppPStr SLIT("Exp type:"))   4 (ppr sty ty),
-             ppHang (ppPStr SLIT("Arg type:"))   4 (ppr sty arg),
-             ppHang (ppPStr SLIT("Expression:")) 4 (pp_expr sty expr)]
-
-mkUsageAppMsg :: Type -> Usage -> CoreExpr -> ErrMsg
-mkUsageAppMsg ty u expr sty
-  = ppAboves [ppPStr SLIT("Illegal usage application:"),
-             ppHang (ppPStr SLIT("Exp type:")) 4 (ppr sty ty),
-             ppHang (ppPStr SLIT("Usage exp:")) 4 (ppr sty u),
-             ppHang (ppPStr SLIT("Expression:")) 4 (pp_expr sty expr)]
+mkTyAppMsg msg ty arg expr
+  = vcat [hsep [ptext msg, ptext SLIT("type application:")],
+             hang (ptext SLIT("Exp type:"))
+                4 (ppr ty <+> ptext SLIT("::") <+> ppr (typeKind ty)),
+             hang (ptext SLIT("Arg type:"))   
+                4 (ppr arg <+> ptext SLIT("::") <+> ppr (typeKind arg)),
+             hang (ptext SLIT("Expression:")) 4 (pprCoreExpr expr)]
 
 mkAlgAltMsg1 :: Type -> ErrMsg
-mkAlgAltMsg1 ty sty
-  = ppAbove (ppStr "In some case statement, type of scrutinee is not a data type:")
-           (ppr sty ty)
---         (ppAbove (ppr sty ty) (ppr sty (expandTy ty))) -- ToDo: rm
+mkAlgAltMsg1 ty
+  = ($$) (text "In some case statement, type of scrutinee is not a data type:")
+           (ppr ty)
 
 mkAlgAltMsg2 :: Type -> Id -> ErrMsg
-mkAlgAltMsg2 ty con sty
-  = ppAboves [
-       ppStr "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
-       ppr sty ty,
-       ppr sty con
+mkAlgAltMsg2 ty con
+  = vcat [
+       text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
+       ppr ty,
+       ppr con
     ]
 
 mkAlgAltMsg3 :: Id -> [Id] -> ErrMsg
-mkAlgAltMsg3 con alts sty
-  = ppAboves [
-       ppStr "In some algebraic case alternative, number of arguments doesn't match constructor:",
-       ppr sty con,
-       ppr sty alts
+mkAlgAltMsg3 con alts
+  = vcat [
+       text "In some algebraic case alternative, number of arguments doesn't match constructor:",
+       ppr con,
+       ppr alts
     ]
 
 mkAlgAltMsg4 :: Type -> Id -> ErrMsg
-mkAlgAltMsg4 ty arg sty
-  = ppAboves [
-       ppStr "In some algebraic case alternative, type of argument doesn't match data constructor:",
-       ppr sty ty,
-       ppr sty arg
+mkAlgAltMsg4 ty arg
+  = vcat [
+       text "In some algebraic case alternative, type of argument doesn't match data constructor:",
+       ppr ty,
+       ppr arg
     ]
 
 mkPrimAltMsg :: (Literal, CoreExpr) -> ErrMsg
-mkPrimAltMsg alt sty
-  = ppAbove
-    (ppStr "In a primitive case alternative, type of literal doesn't match type of scrutinee:")
-           (ppr sty alt)
+mkPrimAltMsg alt
+  = ($$)
+    (text "In a primitive case alternative, type of literal doesn't match type of scrutinee:")
+           (ppr alt)
 
 mkRhsMsg :: Id -> Type -> ErrMsg
-mkRhsMsg binder ty sty
-  = ppAboves
-    [ppCat [ppPStr SLIT("The type of this binder doesn't match the type of its RHS:"),
-           ppr sty binder],
-     ppCat [ppPStr SLIT("Binder's type:"), ppr sty (idType binder)],
-     ppCat [ppPStr SLIT("Rhs type:"), ppr sty ty]]
+mkRhsMsg binder ty
+  = vcat
+    [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
+           ppr binder],
+     hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
+     hsep [ptext SLIT("Rhs type:"), ppr ty]]
 
 mkRhsPrimMsg :: Id -> CoreExpr -> ErrMsg
-mkRhsPrimMsg binder rhs sty
-  = ppAboves [ppCat [ppPStr SLIT("The type of this binder is primitive:"),
-                    ppr sty binder],
-             ppCat [ppPStr SLIT("Binder's type:"), ppr sty (idType binder)]
+mkRhsPrimMsg binder rhs
+  = vcat [hsep [ptext SLIT("The type of this binder is primitive:"),
+                    ppr binder],
+             hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]
             ]
 
-mkSpecTyAppMsg :: CoreArg -> ErrMsg
-mkSpecTyAppMsg arg sty
-  = ppAbove
-      (ppPStr SLIT("Unboxed types in a type application (after specialisation):"))
-      (ppr sty arg)
-
-pp_expr :: PprStyle -> CoreExpr -> Pretty
-pp_expr sty expr
-  = pprCoreExpr sty (pprBigCoreBinder sty) (pprTypedCoreBinder sty) (pprTypedCoreBinder sty) expr
+mkCoerceErr from_ty expr_ty
+  = vcat [ptext SLIT("From-type of Coerce differs from type of enclosed expression"),
+         ptext SLIT("From-type:") <+> ppr from_ty,
+         ptext SLIT("Type of enclosed expr:") <+> ppr expr_ty
+    ]
 \end{code}