Super-monster patch implementing the new typechecker -- at last
[ghc-hetmet.git] / compiler / coreSyn / CoreLint.lhs
1
2 %
3 % (c) The University of Glasgow 2006
4 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
5 %
6
7 A ``lint'' pass to check for Core correctness
8
9 \begin{code}
10 module CoreLint ( lintCoreBindings, lintUnfolding ) where
11
12 #include "HsVersions.h"
13
14 import Demand
15 import CoreSyn
16 import CoreFVs
17 import CoreUtils
18 import Bag
19 import Literal
20 import DataCon
21 import TysWiredIn
22 import Var
23 import VarEnv
24 import VarSet
25 import Name
26 import Id
27 import PprCore
28 import ErrUtils
29 import SrcLoc
30 import Type
31 import TypeRep
32 import Coercion
33 import TyCon
34 import Class
35 import BasicTypes
36 import StaticFlags
37 import ListSetOps
38 import PrelNames
39 import Outputable
40 import FastString
41 import Util
42 import Control.Monad
43 import Data.Maybe
44 \end{code}
45
46 %************************************************************************
47 %*                                                                      *
48 \subsection[lintCoreBindings]{@lintCoreBindings@: Top-level interface}
49 %*                                                                      *
50 %************************************************************************
51
52 Checks that a set of core bindings is well-formed.  The PprStyle and String
53 just control what we print in the event of an error.  The Bool value
54 indicates whether we have done any specialisation yet (in which case we do
55 some extra checks).
56
57 We check for
58         (a) type errors
59         (b) Out-of-scope type variables
60         (c) Out-of-scope local variables
61         (d) Ill-kinded types
62
63 If we have done specialisation the we check that there are
64         (a) No top-level bindings of primitive (unboxed type)
65
66 Outstanding issues:
67
68     --
69     -- Things are *not* OK if:
70     --
71     --  * Unsaturated type app before specialisation has been done;
72     --
73     --  * Oversaturated type app after specialisation (eta reduction
74     --   may well be happening...);
75
76
77 Note [Linting type lets]
78 ~~~~~~~~~~~~~~~~~~~~~~~~
79 In the desugarer, it's very very convenient to be able to say (in effect)
80         let a = Type Int in <body>
81 That is, use a type let.   See Note [Type let] in CoreSyn.
82
83 However, when linting <body> we need to remember that a=Int, else we might
84 reject a correct program.  So we carry a type substitution (in this example 
85 [a -> Int]) and apply this substitution before comparing types.  The functin
86         lintInTy :: Type -> LintM Type
87 returns a substituted type; that's the only reason it returns anything.
88
89 When we encounter a binder (like x::a) we must apply the substitution
90 to the type of the binding variable.  lintBinders does this.
91
92 For Ids, the type-substituted Id is added to the in_scope set (which 
93 itself is part of the TvSubst we are carrying down), and when we
94 find an occurence of an Id, we fetch it from the in-scope set.
95
96
97 \begin{code}
98 lintCoreBindings :: [CoreBind] -> (Bag Message, Bag Message)
99 --   Returns (warnings, errors)
100 lintCoreBindings binds
101   = initL (lint_binds binds)
102   where
103         -- Put all the top-level binders in scope at the start
104         -- This is because transformation rules can bring something
105         -- into use 'unexpectedly'
106     lint_binds binds = addLoc TopLevelBindings $
107                        addInScopeVars (bindersOfBinds binds) $
108                        mapM lint_bind binds 
109
110     lint_bind (Rec prs)         = mapM_ (lintSingleBinding TopLevel Recursive) prs
111     lint_bind (NonRec bndr rhs) = lintSingleBinding TopLevel NonRecursive (bndr,rhs)
112 \end{code}
113
114 %************************************************************************
115 %*                                                                      *
116 \subsection[lintUnfolding]{lintUnfolding}
117 %*                                                                      *
118 %************************************************************************
119
120 We use this to check all unfoldings that come in from interfaces
121 (it is very painful to catch errors otherwise):
122
123 \begin{code}
124 lintUnfolding :: SrcLoc
125               -> [Var]          -- Treat these as in scope
126               -> CoreExpr
127               -> Maybe Message  -- Nothing => OK
128
129 lintUnfolding locn vars expr
130   | isEmptyBag errs = Nothing
131   | otherwise       = Just (pprMessageBag errs)
132   where
133     (_warns, errs) = initL (addLoc (ImportedUnfolding locn) $
134                             addInScopeVars vars            $
135                             lintCoreExpr expr)
136 \end{code}
137
138 %************************************************************************
139 %*                                                                      *
140 \subsection[lintCoreBinding]{lintCoreBinding}
141 %*                                                                      *
142 %************************************************************************
143
144 Check a core binding, returning the list of variables bound.
145
146 \begin{code}
147 lintSingleBinding :: TopLevelFlag -> RecFlag -> (Id, CoreExpr) -> LintM ()
148 lintSingleBinding top_lvl_flag rec_flag (binder,rhs)
149   = addLoc (RhsOf binder) $
150          -- Check the rhs 
151     do { ty <- lintCoreExpr rhs 
152        ; lintBinder binder -- Check match to RHS type
153        ; binder_ty <- applySubst binder_ty
154        ; checkTys binder_ty ty (mkRhsMsg binder ty)
155         -- Check (not isUnLiftedType) (also checks for bogus unboxed tuples)
156        ; checkL (not (isUnLiftedType binder_ty)
157             || (isNonRec rec_flag && exprOkForSpeculation rhs))
158            (mkRhsPrimMsg binder rhs)
159         -- Check that if the binder is top-level or recursive, it's not demanded
160        ; checkL (not (isStrictId binder)
161             || (isNonRec rec_flag && not (isTopLevel top_lvl_flag)))
162            (mkStrictMsg binder)
163         -- Check whether binder's specialisations contain any out-of-scope variables
164        ; mapM_ (checkBndrIdInScope binder) bndr_vars 
165
166        ; when (isNonRuleLoopBreaker (idOccInfo binder) && isInlinePragma (idInlinePragma binder))
167               (addWarnL (ptext (sLit "INLINE binder is (non-rule) loop breaker:") <+> ppr binder))
168               -- Only non-rule loop breakers inhibit inlining
169
170       -- Check whether arity and demand type are consistent (only if demand analysis
171       -- already happened)
172        ; checkL (case maybeDmdTy of
173                   Just (StrictSig dmd_ty) -> idArity binder >= dmdTypeDepth dmd_ty || exprIsTrivial rhs
174                   Nothing -> True)
175            (mkArityMsg binder) }
176           
177         -- We should check the unfolding, if any, but this is tricky because
178         -- the unfolding is a SimplifiableCoreExpr. Give up for now.
179    where
180     binder_ty                  = idType binder
181     maybeDmdTy                 = idStrictness_maybe binder
182     bndr_vars                  = varSetElems (idFreeVars binder)
183     lintBinder var | isId var  = lintIdBndr var $ \_ -> (return ())
184                    | otherwise = return ()
185 \end{code}
186
187 %************************************************************************
188 %*                                                                      *
189 \subsection[lintCoreExpr]{lintCoreExpr}
190 %*                                                                      *
191 %************************************************************************
192
193 \begin{code}
194 type InType  = Type     -- Substitution not yet applied
195 type InVar   = Var
196 type InTyVar = TyVar
197
198 type OutType  = Type    -- Substitution has been applied to this
199 type OutVar   = Var
200 type OutTyVar = TyVar
201 type OutCoVar = CoVar
202
203 lintCoreExpr :: CoreExpr -> LintM OutType
204 -- The returned type has the substitution from the monad 
205 -- already applied to it:
206 --      lintCoreExpr e subst = exprType (subst e)
207 --
208 -- The returned "type" can be a kind, if the expression is (Type ty)
209
210 lintCoreExpr (Var var)
211   = do  { checkL (not (var == oneTupleDataConId))
212                  (ptext (sLit "Illegal one-tuple"))
213
214         ; checkDeadIdOcc var
215         ; var' <- lookupIdInScope var
216         ; return (idType var') }
217
218 lintCoreExpr (Lit lit)
219   = return (literalType lit)
220
221 lintCoreExpr (Cast expr co)
222   = do { expr_ty <- lintCoreExpr expr
223        ; co' <- applySubst co
224        ; (from_ty, to_ty) <- lintCoercion co'
225        ; checkTys from_ty expr_ty (mkCastErr from_ty expr_ty)
226        ; return to_ty }
227
228 lintCoreExpr (Note _ expr)
229   = lintCoreExpr expr
230
231 lintCoreExpr (Let (NonRec tv (Type ty)) body)
232   | isTyVar tv
233   =     -- See Note [Linting type lets]
234     do  { ty' <- addLoc (RhsOf tv) $ lintInTy ty
235         ; lintTyBndr tv              $ \ tv' -> 
236           addLoc (BodyOfLetRec [tv]) $ 
237           extendSubstL tv' ty'       $ do
238         { checkKinds tv' ty'              
239                 -- Now extend the substitution so we 
240                 -- take advantage of it in the body
241         ; lintCoreExpr body } }
242
243   | isCoVar tv
244   = do { co <- applySubst ty
245        ; (s1,s2) <- addLoc (RhsOf tv) $ lintCoercion co
246        ; lintTyBndr tv  $ \ tv' -> 
247          addLoc (BodyOfLetRec [tv]) $ do
248        { let (t1,t2) = coVarKind tv'
249        ; checkTys s1 t1 (mkTyVarLetErr tv ty)
250        ; checkTys s2 t2 (mkTyVarLetErr tv ty)
251        ; lintCoreExpr body } }
252
253   | otherwise
254   = failWithL (mkTyVarLetErr tv ty)     -- Not quite accurate
255
256 lintCoreExpr (Let (NonRec bndr rhs) body)
257   = do  { lintSingleBinding NotTopLevel NonRecursive (bndr,rhs)
258         ; addLoc (BodyOfLetRec [bndr])
259                  (lintAndScopeId bndr $ \_ -> (lintCoreExpr body)) }
260
261 lintCoreExpr (Let (Rec pairs) body) 
262   = lintAndScopeIds bndrs       $ \_ ->
263     do  { mapM_ (lintSingleBinding NotTopLevel Recursive) pairs 
264         ; addLoc (BodyOfLetRec bndrs) (lintCoreExpr body) }
265   where
266     bndrs = map fst pairs
267
268 lintCoreExpr e@(App fun arg)
269   = do  { fun_ty <- lintCoreExpr fun
270         ; addLoc (AnExpr e) $
271           lintCoreArg fun_ty arg }
272
273 lintCoreExpr (Lam var expr)
274   = addLoc (LambdaBodyOf var) $
275     lintBinders [var] $ \[var'] -> 
276     do { body_ty <- lintCoreExpr expr
277        ; if isId var' then 
278              return (mkFunTy (idType var') body_ty) 
279          else
280              return (mkForAllTy var' body_ty)
281        }
282         -- The applySubst is needed to apply the subst to var
283
284 lintCoreExpr e@(Case scrut var alt_ty alts) =
285        -- Check the scrutinee
286   do { scrut_ty <- lintCoreExpr scrut
287      ; alt_ty   <- lintInTy alt_ty  
288      ; var_ty   <- lintInTy (idType var)        
289
290      ; let mb_tc_app = splitTyConApp_maybe (idType var)
291      ; case mb_tc_app of 
292          Just (tycon, _)
293               | debugIsOn &&
294                 isAlgTyCon tycon && 
295                 not (isFamilyTyCon tycon || isAbstractTyCon tycon) &&
296                 null (tyConDataCons tycon) -> 
297                   pprTrace "Lint warning: case binder's type has no constructors" (ppr var <+> ppr (idType var))
298                         -- This can legitimately happen for type families
299                       $ return ()
300          _otherwise -> return ()
301
302         -- Don't use lintIdBndr on var, because unboxed tuple is legitimate
303
304      ; subst <- getTvSubst 
305      ; checkTys var_ty scrut_ty (mkScrutMsg var var_ty scrut_ty subst)
306
307      -- If the binder is an unboxed tuple type, don't put it in scope
308      ; let scope = if (isUnboxedTupleType (idType var)) then 
309                        pass_var 
310                    else lintAndScopeId var
311      ; scope $ \_ ->
312        do { -- Check the alternatives
313             mapM_ (lintCoreAlt scrut_ty alt_ty) alts
314           ; checkCaseAlts e scrut_ty alts
315           ; return alt_ty } }
316   where
317     pass_var f = f var
318
319 lintCoreExpr (Type ty)
320   = do { ty' <- lintInTy ty
321        ; return (typeKind ty') }
322 \end{code}
323
324 %************************************************************************
325 %*                                                                      *
326 \subsection[lintCoreArgs]{lintCoreArgs}
327 %*                                                                      *
328 %************************************************************************
329
330 The basic version of these functions checks that the argument is a
331 subtype of the required type, as one would expect.
332
333 \begin{code}
334 lintCoreArg  :: OutType -> CoreArg -> LintM OutType
335 lintCoreArg fun_ty (Type arg_ty)
336   = do  { arg_ty' <- applySubst arg_ty
337         ; lintTyApp fun_ty arg_ty' }
338
339 lintCoreArg fun_ty arg
340  = do { arg_ty <- lintCoreExpr arg
341       ; lintValApp arg fun_ty arg_ty }
342
343 -----------------
344 lintAltBinders :: OutType     -- Scrutinee type
345                -> OutType     -- Constructor type
346                -> [OutVar]    -- Binders
347                -> LintM ()
348 lintAltBinders scrut_ty con_ty [] 
349   = checkTys con_ty scrut_ty (mkBadPatMsg con_ty scrut_ty) 
350 lintAltBinders scrut_ty con_ty (bndr:bndrs)
351   | isTyCoVar bndr
352   = do { con_ty' <- lintTyApp con_ty (mkTyVarTy bndr)
353        ; lintAltBinders scrut_ty con_ty' bndrs }
354   | otherwise
355   = do { con_ty' <- lintValApp (Var bndr) con_ty (idType bndr)
356        ; lintAltBinders scrut_ty con_ty' bndrs } 
357
358 -----------------
359 lintTyApp :: OutType -> OutType -> LintM OutType
360 lintTyApp fun_ty arg_ty
361   | Just (tyvar,body_ty) <- splitForAllTy_maybe fun_ty
362   = do  { checkKinds tyvar arg_ty
363         ; if isCoVar tyvar then 
364              return body_ty   -- Co-vars don't appear in body_ty!
365           else 
366              return (substTyWith [tyvar] [arg_ty] body_ty) }
367   | otherwise
368   = failWithL (mkTyAppMsg fun_ty arg_ty)
369    
370 -----------------
371 lintValApp :: CoreExpr -> OutType -> OutType -> LintM OutType
372 lintValApp arg fun_ty arg_ty
373   | Just (arg,res) <- splitFunTy_maybe fun_ty
374   = do { checkTys arg arg_ty err1
375        ; return res }
376   | otherwise
377   = failWithL err2
378   where
379     err1 = mkAppMsg       fun_ty arg_ty arg
380     err2 = mkNonFunAppMsg fun_ty arg_ty arg
381 \end{code}
382
383 \begin{code}
384 checkKinds :: Var -> OutType -> LintM ()
385 -- Both args have had substitution applied
386 checkKinds tyvar arg_ty
387         -- Arg type might be boxed for a function with an uncommitted
388         -- tyvar; notably this is used so that we can give
389         --      error :: forall a:*. String -> a
390         -- and then apply it to both boxed and unboxed types.
391   | isCoVar tyvar = do { (s2,t2) <- lintCoercion arg_ty
392                        ; unless (s1 `coreEqType` s2 && t1 `coreEqType` t2)
393                                 (addErrL (mkCoAppErrMsg tyvar arg_ty)) }
394   | otherwise     = do { arg_kind <- lintType arg_ty
395                        ; unless (arg_kind `isSubKind` tyvar_kind)
396                                 (addErrL (mkKindErrMsg tyvar arg_ty)) }
397   where
398     tyvar_kind = tyVarKind tyvar
399     (s1,t1)    = coVarKind tyvar
400
401 checkDeadIdOcc :: Id -> LintM ()
402 -- Occurrences of an Id should never be dead....
403 -- except when we are checking a case pattern
404 checkDeadIdOcc id
405   | isDeadOcc (idOccInfo id)
406   = do { in_case <- inCasePat
407        ; checkL in_case
408                 (ptext (sLit "Occurrence of a dead Id") <+> ppr id) }
409   | otherwise
410   = return ()
411 \end{code}
412
413
414 %************************************************************************
415 %*                                                                      *
416 \subsection[lintCoreAlts]{lintCoreAlts}
417 %*                                                                      *
418 %************************************************************************
419
420 \begin{code}
421 checkCaseAlts :: CoreExpr -> OutType -> [CoreAlt] -> LintM ()
422 -- a) Check that the alts are non-empty
423 -- b1) Check that the DEFAULT comes first, if it exists
424 -- b2) Check that the others are in increasing order
425 -- c) Check that there's a default for infinite types
426 -- NB: Algebraic cases are not necessarily exhaustive, because
427 --     the simplifer correctly eliminates case that can't 
428 --     possibly match.
429
430 checkCaseAlts e _ []
431   = addErrL (mkNullAltsMsg e)
432
433 checkCaseAlts e ty alts = 
434   do { checkL (all non_deflt con_alts) (mkNonDefltMsg e)
435      ; checkL (increasing_tag con_alts) (mkNonIncreasingAltsMsg e)
436      ; checkL (isJust maybe_deflt || not is_infinite_ty)
437            (nonExhaustiveAltsMsg e) }
438   where
439     (con_alts, maybe_deflt) = findDefault alts
440
441         -- Check that successive alternatives have increasing tags 
442     increasing_tag (alt1 : rest@( alt2 : _)) = alt1 `ltAlt` alt2 && increasing_tag rest
443     increasing_tag _                         = True
444
445     non_deflt (DEFAULT, _, _) = False
446     non_deflt _               = True
447
448     is_infinite_ty = case splitTyConApp_maybe ty of
449                         Nothing         -> False
450                         Just (tycon, _) -> isPrimTyCon tycon
451 \end{code}
452
453 \begin{code}
454 checkAltExpr :: CoreExpr -> OutType -> LintM ()
455 checkAltExpr expr ann_ty
456   = do { actual_ty <- lintCoreExpr expr 
457        ; checkTys actual_ty ann_ty (mkCaseAltMsg expr actual_ty ann_ty) }
458
459 lintCoreAlt :: OutType          -- Type of scrutinee
460             -> OutType          -- Type of the alternative
461             -> CoreAlt
462             -> LintM ()
463
464 lintCoreAlt _ alt_ty (DEFAULT, args, rhs) =
465   do { checkL (null args) (mkDefaultArgsMsg args)
466      ; checkAltExpr rhs alt_ty }
467
468 lintCoreAlt scrut_ty alt_ty (LitAlt lit, args, rhs) = 
469   do { checkL (null args) (mkDefaultArgsMsg args)
470      ; checkTys lit_ty scrut_ty (mkBadPatMsg lit_ty scrut_ty)   
471      ; checkAltExpr rhs alt_ty } 
472   where
473     lit_ty = literalType lit
474
475 lintCoreAlt scrut_ty alt_ty alt@(DataAlt con, args, rhs)
476   | isNewTyCon (dataConTyCon con) 
477   = addErrL (mkNewTyDataConAltMsg scrut_ty alt)
478   | Just (tycon, tycon_arg_tys) <- splitTyConApp_maybe scrut_ty
479   = addLoc (CaseAlt alt) $  do
480     {   -- First instantiate the universally quantified 
481         -- type variables of the data constructor
482         -- We've already check
483       checkL (tycon == dataConTyCon con) (mkBadConMsg tycon con)
484     ; let con_payload_ty = applyTys (dataConRepType con) tycon_arg_tys
485
486         -- And now bring the new binders into scope
487     ; lintBinders args $ \ args' -> do
488     { addLoc (CasePat alt) (lintAltBinders scrut_ty con_payload_ty args')
489     ; checkAltExpr rhs alt_ty } }
490
491   | otherwise   -- Scrut-ty is wrong shape
492   = addErrL (mkBadAltMsg scrut_ty alt)
493 \end{code}
494
495 %************************************************************************
496 %*                                                                      *
497 \subsection[lint-types]{Types}
498 %*                                                                      *
499 %************************************************************************
500
501 \begin{code}
502 -- When we lint binders, we (one at a time and in order):
503 --  1. Lint var types or kinds (possibly substituting)
504 --  2. Add the binder to the in scope set, and if its a coercion var,
505 --     we may extend the substitution to reflect its (possibly) new kind
506 lintBinders :: [Var] -> ([Var] -> LintM a) -> LintM a
507 lintBinders [] linterF = linterF []
508 lintBinders (var:vars) linterF = lintBinder var $ \var' ->
509                                  lintBinders vars $ \ vars' ->
510                                  linterF (var':vars')
511
512 lintBinder :: Var -> (Var -> LintM a) -> LintM a
513 lintBinder var linterF
514   | isId var  = lintIdBndr var linterF
515   | otherwise = lintTyBndr var linterF
516
517 lintTyBndr :: InTyVar -> (OutTyVar -> LintM a) -> LintM a
518 lintTyBndr tv thing_inside
519   = do { subst <- getTvSubst
520        ; let (subst', tv') = substTyVarBndr subst tv
521        ; lintTyBndrKind tv'
522        ; updateTvSubst subst' (thing_inside tv') }
523
524 lintIdBndr :: Id -> (Id -> LintM a) -> LintM a
525 -- Do substitution on the type of a binder and add the var with this 
526 -- new type to the in-scope set of the second argument
527 -- ToDo: lint its rules
528
529 lintIdBndr id linterF 
530   = do  { checkL (not (isUnboxedTupleType (idType id))) 
531                  (mkUnboxedTupleMsg id)
532                 -- No variable can be bound to an unboxed tuple.
533         ; lintAndScopeId id $ \id' -> linterF id' }
534
535 lintAndScopeIds :: [Var] -> ([Var] -> LintM a) -> LintM a
536 lintAndScopeIds ids linterF 
537   = go ids
538   where
539     go []       = linterF []
540     go (id:ids) = lintAndScopeId id $ \id ->
541                   lintAndScopeIds ids $ \ids ->
542                   linterF (id:ids)
543
544 lintAndScopeId :: InVar -> (OutVar -> LintM a) -> LintM a
545 lintAndScopeId id linterF 
546   = do { ty <- lintInTy (idType id)
547        ; let id' = setIdType id ty
548        ; addInScopeVar id' $ (linterF id') }
549 \end{code}
550
551
552 %************************************************************************
553 %*                                                                      *
554 \subsection[lint-monad]{The Lint monad}
555 %*                                                                      *
556 %************************************************************************
557
558 \begin{code}
559 lintInTy :: InType -> LintM OutType
560 -- Check the type, and apply the substitution to it
561 -- See Note [Linting type lets]
562 -- ToDo: check the kind structure of the type
563 lintInTy ty 
564   = addLoc (InType ty) $
565     do  { ty' <- applySubst ty
566         ; _ <- lintType ty'
567         ; return ty' }
568
569 -------------------
570 lintKind :: Kind -> LintM ()
571 -- Check well-formedness of kinds: *, *->*, etc
572 lintKind (TyConApp tc []) 
573   | getUnique tc `elem` kindKeys
574   = return ()
575 lintKind (FunTy k1 k2)
576   = lintKind k1 >> lintKind k2
577 lintKind kind 
578   = addErrL (hang (ptext (sLit "Malformed kind:")) 2 (quotes (ppr kind)))
579
580 -------------------
581 lintTyBndrKind :: OutTyVar -> LintM ()
582 lintTyBndrKind tv 
583   | isCoVar tv = lintCoVarKind tv
584   | otherwise  = lintKind (tyVarKind tv)
585
586 -------------------
587 lintCoVarKind :: OutCoVar -> LintM ()
588 -- Check the kind of a coercion binder
589 lintCoVarKind tv
590   = do { (ty1,ty2) <- lintSplitCoVar tv
591        ; k1 <- lintType ty1
592        ; k2 <- lintType ty2
593        ; unless (k1 `eqKind` k2) 
594                 (addErrL (sep [ ptext (sLit "Kind mis-match in coercion kind of:")
595                               , nest 2 (quotes (ppr tv))
596                               , ppr [k1,k2] ])) }
597
598 -------------------
599 lintSplitCoVar :: CoVar -> LintM (Type,Type)
600 lintSplitCoVar cv
601   = case coVarKind_maybe cv of
602       Just ts -> return ts
603       Nothing -> failWithL (sep [ ptext (sLit "Coercion variable with non-equality kind:")
604                                 , nest 2 (ppr cv <+> dcolon <+> ppr (tyVarKind cv))])
605
606 -------------------
607 lintCoercion :: OutType -> LintM (OutType, OutType)
608 -- Check the kind of a coercion term, returning the kind
609 lintCoercion ty@(TyVarTy tv)
610   = do { checkTyVarInScope tv
611        ; if isCoVar tv then return (coVarKind tv) 
612                        else return (ty, ty) }
613
614 lintCoercion ty@(AppTy ty1 ty2) 
615   = do { (s1,t1) <- lintCoercion ty1
616        ; (s2,t2) <- lintCoercion ty2
617        ; check_co_app ty (typeKind s1) [s2]
618        ; return (AppTy s1 s2, AppTy t1 t2) }
619
620 lintCoercion ty@(FunTy ty1 ty2) 
621   = do { (s1,t1) <- lintCoercion ty1
622        ; (s2,t2) <- lintCoercion ty2
623        ; check_co_app ty (tyConKind funTyCon) [s1, s2]
624        ; return (FunTy s1 s2, FunTy t1 t2) }
625
626 lintCoercion ty@(TyConApp tc tys) 
627   | Just (ar, desc) <- isCoercionTyCon_maybe tc
628   = do { unless (tys `lengthAtLeast` ar) (badCo ty)
629        ; (s,t) <- lintCoTyConApp ty desc (take ar tys)
630        ; (ss,ts) <- mapAndUnzipM lintCoercion (drop ar tys)
631        ; check_co_app ty (typeKind s) ss
632        ; return (mkAppTys s ss, mkAppTys t ts) }
633
634   | not (tyConHasKind tc)       -- Just something bizarre like SuperKindTyCon
635   = badCo ty
636
637   | otherwise
638   = do { (ss,ts) <- mapAndUnzipM lintCoercion tys
639        ; check_co_app ty (tyConKind tc) ss
640        ; return (TyConApp tc ss, TyConApp tc ts) }
641
642 lintCoercion ty@(PredTy (ClassP cls tys))
643   = do { (ss,ts) <- mapAndUnzipM lintCoercion tys
644        ; check_co_app ty (tyConKind (classTyCon cls)) ss
645        ; return (PredTy (ClassP cls ss), PredTy (ClassP cls ts)) }
646
647 lintCoercion (PredTy (IParam n p_ty))
648   = do { (s,t) <- lintCoercion p_ty
649        ; return (PredTy (IParam n s), PredTy (IParam n t)) }
650
651 lintCoercion ty@(PredTy (EqPred {}))
652   = failWithL (badEq ty)
653
654 lintCoercion (ForAllTy tv ty)
655   | isCoVar tv
656   = do { (co1, co2) <- lintSplitCoVar tv
657        ; (s1,t1)    <- lintCoercion co1
658        ; (s2,t2)    <- lintCoercion co2
659        ; (sr,tr)    <- lintCoercion ty
660        ; return (mkCoPredTy s1 s2 sr, mkCoPredTy t1 t2 tr) }
661
662   | otherwise
663   = do { lintKind (tyVarKind tv)
664        ; (s,t) <- addInScopeVar tv (lintCoercion ty)
665        ; return (ForAllTy tv s, ForAllTy tv t) }
666
667 badCo :: Coercion -> LintM a
668 badCo co = failWithL (hang (ptext (sLit "Ill-kinded coercion term:")) 2 (ppr co))
669
670 ---------------
671 lintCoTyConApp :: Coercion -> CoTyConDesc -> [Coercion] -> LintM (Type,Type)
672 -- Always called with correct number of coercion arguments
673 -- First arg is just for error message
674 lintCoTyConApp _ CoLeft  (co:_) = lintLR   fst      co 
675 lintCoTyConApp _ CoRight (co:_) = lintLR   snd      co   
676 lintCoTyConApp _ CoCsel1 (co:_) = lintCsel fstOf3   co 
677 lintCoTyConApp _ CoCsel2 (co:_) = lintCsel sndOf3   co 
678 lintCoTyConApp _ CoCselR (co:_) = lintCsel thirdOf3 co 
679
680 lintCoTyConApp _ CoSym (co:_) 
681   = do { (ty1,ty2) <- lintCoercion co
682        ; return (ty2,ty1) }
683
684 lintCoTyConApp co CoTrans (co1:co2:_) 
685   = do { (ty1a, ty1b) <- lintCoercion co1
686        ; (ty2a, ty2b) <- lintCoercion co2
687        ; checkL (ty1b `coreEqType` ty2a)
688                 (hang (ptext (sLit "Trans coercion mis-match:") <+> ppr co)
689                     2 (vcat [ppr ty1a, ppr ty1b, ppr ty2a, ppr ty2b]))
690        ; return (ty1a, ty2b) }
691
692 lintCoTyConApp _ CoInst (co:arg_ty:_) 
693   = do { co_tys <- lintCoercion co
694        ; arg_kind  <- lintType arg_ty
695        ; case decompInst_maybe co_tys of
696           Just ((tv1,tv2), (ty1,ty2)) 
697             | arg_kind `isSubKind` tyVarKind tv1
698             -> return (substTyWith [tv1] [arg_ty] ty1, 
699                        substTyWith [tv2] [arg_ty] ty2) 
700             | otherwise
701             -> failWithL (ptext (sLit "Kind mis-match in inst coercion"))
702           Nothing -> failWithL (ptext (sLit "Bad argument of inst")) }
703
704 lintCoTyConApp _ (CoAxiom { co_ax_tvs = tvs 
705                           , co_ax_lhs = lhs_ty, co_ax_rhs = rhs_ty }) cos
706   = do { (tys1, tys2) <- mapAndUnzipM lintCoercion cos
707        ; sequence_ (zipWith checkKinds tvs tys1)
708        ; return (substTyWith tvs tys1 lhs_ty,
709                  substTyWith tvs tys2 rhs_ty) }
710
711 lintCoTyConApp _ CoUnsafe (ty1:ty2:_) 
712   = do { _ <- lintType ty1
713        ; _ <- lintType ty2      -- Ignore kinds; it's unsafe!
714        ; return (ty1,ty2) } 
715
716 lintCoTyConApp _ _ _ = panic "lintCoTyConApp"  -- Called with wrong number of coercion args
717
718 ----------
719 lintLR :: (forall a. (a,a)->a) -> Coercion -> LintM (Type,Type)
720 lintLR sel co
721   = do { (ty1,ty2) <- lintCoercion co
722        ; case decompLR_maybe (ty1,ty2) of
723            Just res -> return (sel res)
724            Nothing  -> failWithL (ptext (sLit "Bad argument of left/right")) }
725
726 ----------
727 lintCsel :: (forall a. (a,a,a)->a) -> Coercion -> LintM (Type,Type)
728 lintCsel sel co
729   = do { (ty1,ty2) <- lintCoercion co
730        ; case decompCsel_maybe (ty1,ty2) of
731            Just res -> return (sel res)
732            Nothing  -> failWithL (ptext (sLit "Bad argument of csel")) }
733
734 -------------------
735 lintType :: OutType -> LintM Kind
736 lintType (TyVarTy tv)
737   = do { checkTyVarInScope tv
738        ; return (tyVarKind tv) }
739
740 lintType ty@(AppTy t1 t2) 
741   = do { k1 <- lintType t1
742        ; lint_ty_app ty k1 [t2] }
743
744 lintType ty@(FunTy t1 t2)
745   = lint_ty_app ty (tyConKind funTyCon) [t1,t2]
746
747 lintType ty@(TyConApp tc tys)
748   | tyConHasKind tc
749   = lint_ty_app ty (tyConKind tc) tys
750   | otherwise
751   = failWithL (hang (ptext (sLit "Malformed type:")) 2 (ppr ty))
752
753 lintType (ForAllTy tv ty)
754   = do { lintTyBndrKind tv
755        ; addInScopeVar tv (lintType ty) }
756
757 lintType ty@(PredTy (ClassP cls tys))
758   = lint_ty_app ty (tyConKind (classTyCon cls)) tys
759
760 lintType (PredTy (IParam _ p_ty))
761   = lintType p_ty
762
763 lintType ty@(PredTy (EqPred {}))
764   = failWithL (badEq ty)
765
766 ----------------
767 lint_ty_app :: Type -> Kind -> [OutType] -> LintM Kind
768 lint_ty_app ty k tys 
769   = do { ks <- mapM lintType tys
770        ; lint_kind_app (ptext (sLit "type") <+> quotes (ppr ty)) k ks }
771                       
772 ----------------
773 check_co_app :: Coercion -> Kind -> [OutType] -> LintM ()
774 check_co_app ty k tys 
775   = do { _ <- lint_kind_app (ptext (sLit "coercion") <+> quotes (ppr ty))  
776                             k (map typeKind tys)
777        ; return () }
778                       
779 ----------------
780 lint_kind_app :: SDoc -> Kind -> [Kind] -> LintM Kind
781 lint_kind_app doc kfn ks = go kfn ks
782   where
783     fail_msg = vcat [hang (ptext (sLit "Kind application error in")) 2 doc,
784                      nest 2 (ptext (sLit "Function kind =") <+> ppr kfn),
785                      nest 2 (ptext (sLit "Arg kinds =") <+> ppr ks)]
786
787     go kfn []     = return kfn
788     go kfn (k:ks) = case splitKindFunTy_maybe kfn of
789                       Nothing         -> failWithL fail_msg
790                       Just (kfa, kfb) -> do { unless (k `isSubKind` kfa)
791                                                      (addErrL fail_msg)
792                                             ; go kfb ks } 
793 --------------
794 badEq :: Type -> SDoc
795 badEq ty = hang (ptext (sLit "Unexpected equality predicate:"))
796               1 (quotes (ppr ty))
797 \end{code}
798     
799 %************************************************************************
800 %*                                                                      *
801 \subsection[lint-monad]{The Lint monad}
802 %*                                                                      *
803 %************************************************************************
804
805 \begin{code}
806 newtype LintM a = 
807    LintM { unLintM :: 
808             [LintLocInfo] ->         -- Locations
809             TvSubst ->               -- Current type substitution; we also use this
810                                      -- to keep track of all the variables in scope,
811                                      -- both Ids and TyVars
812             WarnsAndErrs ->           -- Error and warning messages so far
813             (Maybe a, WarnsAndErrs) } -- Result and messages (if any)
814
815 type WarnsAndErrs = (Bag Message, Bag Message)
816
817 {-      Note [Type substitution]
818         ~~~~~~~~~~~~~~~~~~~~~~~~
819 Why do we need a type substitution?  Consider
820         /\(a:*). \(x:a). /\(a:*). id a x
821 This is ill typed, because (renaming variables) it is really
822         /\(a:*). \(x:a). /\(b:*). id b x
823 Hence, when checking an application, we can't naively compare x's type
824 (at its binding site) with its expected type (at a use site).  So we
825 rename type binders as we go, maintaining a substitution.
826
827 The same substitution also supports let-type, current expressed as
828         (/\(a:*). body) ty
829 Here we substitute 'ty' for 'a' in 'body', on the fly.
830 -}
831
832 instance Monad LintM where
833   return x = LintM (\ _   _     errs -> (Just x, errs))
834   fail err = failWithL (text err)
835   m >>= k  = LintM (\ loc subst errs -> 
836                        let (res, errs') = unLintM m loc subst errs in
837                          case res of
838                            Just r -> unLintM (k r) loc subst errs'
839                            Nothing -> (Nothing, errs'))
840
841 data LintLocInfo
842   = RhsOf Id            -- The variable bound
843   | LambdaBodyOf Id     -- The lambda-binder
844   | BodyOfLetRec [Id]   -- One of the binders
845   | CaseAlt CoreAlt     -- Case alternative
846   | CasePat CoreAlt     -- The *pattern* of the case alternative
847   | AnExpr CoreExpr     -- Some expression
848   | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
849   | TopLevelBindings
850   | InType Type         -- Inside a type
851 \end{code}
852
853                  
854 \begin{code}
855 initL :: LintM a -> WarnsAndErrs    -- Errors and warnings
856 initL m
857   = case unLintM m [] emptyTvSubst (emptyBag, emptyBag) of
858       (_, errs) -> errs
859 \end{code}
860
861 \begin{code}
862 checkL :: Bool -> Message -> LintM ()
863 checkL True  _   = return ()
864 checkL False msg = failWithL msg
865
866 failWithL :: Message -> LintM a
867 failWithL msg = LintM $ \ loc subst (warns,errs) ->
868                 (Nothing, (warns, addMsg subst errs msg loc))
869
870 addErrL :: Message -> LintM ()
871 addErrL msg = LintM $ \ loc subst (warns,errs) -> 
872               (Just (), (warns, addMsg subst errs msg loc))
873
874 addWarnL :: Message -> LintM ()
875 addWarnL msg = LintM $ \ loc subst (warns,errs) -> 
876               (Just (), (addMsg subst warns msg loc, errs))
877
878 addMsg :: TvSubst ->  Bag Message -> Message -> [LintLocInfo] -> Bag Message
879 addMsg subst msgs msg locs
880   = ASSERT( notNull locs )
881     msgs `snocBag` mk_msg msg
882   where
883    (loc, cxt1) = dumpLoc (head locs)
884    cxts        = [snd (dumpLoc loc) | loc <- locs]   
885    context     | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1 $$
886                                       ptext (sLit "Substitution:") <+> ppr subst
887                | otherwise          = cxt1
888  
889    mk_msg msg = mkLocMessage (mkSrcSpan loc loc) (context $$ msg)
890
891 addLoc :: LintLocInfo -> LintM a -> LintM a
892 addLoc extra_loc m =
893   LintM (\ loc subst errs -> unLintM m (extra_loc:loc) subst errs)
894
895 inCasePat :: LintM Bool         -- A slight hack; see the unique call site
896 inCasePat = LintM $ \ loc _ errs -> (Just (is_case_pat loc), errs)
897   where
898     is_case_pat (CasePat {} : _) = True
899     is_case_pat _other           = False
900
901 addInScopeVars :: [Var] -> LintM a -> LintM a
902 addInScopeVars vars m
903   | null dups
904   = LintM (\ loc subst errs -> unLintM m loc (extendTvInScopeList subst vars) errs)
905   | otherwise
906   = failWithL (dupVars dups)
907   where
908     (_, dups) = removeDups compare vars 
909
910 addInScopeVar :: Var -> LintM a -> LintM a
911 addInScopeVar var m
912   = LintM (\ loc subst errs -> unLintM m loc (extendTvInScope subst var) errs)
913
914 updateTvSubst :: TvSubst -> LintM a -> LintM a
915 updateTvSubst subst' m = 
916   LintM (\ loc _ errs -> unLintM m loc subst' errs)
917
918 getTvSubst :: LintM TvSubst
919 getTvSubst = LintM (\ _ subst errs -> (Just subst, errs))
920
921 applySubst :: Type -> LintM Type
922 applySubst ty = do { subst <- getTvSubst; return (substTy subst ty) }
923
924 extendSubstL :: TyVar -> Type -> LintM a -> LintM a
925 extendSubstL tv ty m
926   = LintM (\ loc subst errs -> unLintM m loc (extendTvSubst subst tv ty) errs)
927 \end{code}
928
929 \begin{code}
930 lookupIdInScope :: Id -> LintM Id
931 lookupIdInScope id 
932   | not (mustHaveLocalBinding id)
933   = return id   -- An imported Id
934   | otherwise   
935   = do  { subst <- getTvSubst
936         ; case lookupInScope (getTvInScope subst) id of
937                 Just v  -> return v
938                 Nothing -> do { addErrL out_of_scope
939                               ; return id } }
940   where
941     out_of_scope = ppr id <+> ptext (sLit "is out of scope")
942
943
944 oneTupleDataConId :: Id -- Should not happen
945 oneTupleDataConId = dataConWorkId (tupleCon Boxed 1)
946
947 checkBndrIdInScope :: Var -> Var -> LintM ()
948 checkBndrIdInScope binder id 
949   = checkInScope msg id
950     where
951      msg = ptext (sLit "is out of scope inside info for") <+> 
952            ppr binder
953
954 checkTyVarInScope :: TyVar -> LintM ()
955 checkTyVarInScope tv = checkInScope (ptext (sLit "is out of scope")) tv
956
957 checkInScope :: SDoc -> Var -> LintM ()
958 checkInScope loc_msg var =
959  do { subst <- getTvSubst
960     ; checkL (not (mustHaveLocalBinding var) || (var `isInScope` subst))
961              (hsep [ppr var, loc_msg]) }
962
963 checkTys :: OutType -> OutType -> Message -> LintM ()
964 -- check ty2 is subtype of ty1 (ie, has same structure but usage
965 -- annotations need only be consistent, not equal)
966 -- Assumes ty1,ty2 are have alrady had the substitution applied
967 checkTys ty1 ty2 msg = checkL (ty1 `coreEqType` ty2) msg
968 \end{code}
969
970 %************************************************************************
971 %*                                                                      *
972 \subsection{Error messages}
973 %*                                                                      *
974 %************************************************************************
975
976 \begin{code}
977 dumpLoc :: LintLocInfo -> (SrcLoc, SDoc)
978
979 dumpLoc (RhsOf v)
980   = (getSrcLoc v, brackets (ptext (sLit "RHS of") <+> pp_binders [v]))
981
982 dumpLoc (LambdaBodyOf b)
983   = (getSrcLoc b, brackets (ptext (sLit "in body of lambda with binder") <+> pp_binder b))
984
985 dumpLoc (BodyOfLetRec [])
986   = (noSrcLoc, brackets (ptext (sLit "In body of a letrec with no binders")))
987
988 dumpLoc (BodyOfLetRec bs@(_:_))
989   = ( getSrcLoc (head bs), brackets (ptext (sLit "in body of letrec with binders") <+> pp_binders bs))
990
991 dumpLoc (AnExpr e)
992   = (noSrcLoc, text "In the expression:" <+> ppr e)
993
994 dumpLoc (CaseAlt (con, args, _))
995   = (noSrcLoc, text "In a case alternative:" <+> parens (ppr con <+> pp_binders args))
996
997 dumpLoc (CasePat (con, args, _))
998   = (noSrcLoc, text "In the pattern of a case alternative:" <+> parens (ppr con <+> pp_binders args))
999
1000 dumpLoc (ImportedUnfolding locn)
1001   = (locn, brackets (ptext (sLit "in an imported unfolding")))
1002 dumpLoc TopLevelBindings
1003   = (noSrcLoc, empty)
1004 dumpLoc (InType ty)
1005   = (noSrcLoc, text "In the type" <+> quotes (ppr ty))
1006
1007 pp_binders :: [Var] -> SDoc
1008 pp_binders bs = sep (punctuate comma (map pp_binder bs))
1009
1010 pp_binder :: Var -> SDoc
1011 pp_binder b | isId b    = hsep [ppr b, dcolon, ppr (idType b)]
1012             | otherwise = hsep [ppr b, dcolon, ppr (tyVarKind b)]
1013 \end{code}
1014
1015 \begin{code}
1016 ------------------------------------------------------
1017 --      Messages for case expressions
1018
1019 mkNullAltsMsg :: CoreExpr -> Message
1020 mkNullAltsMsg e 
1021   = hang (text "Case expression with no alternatives:")
1022          4 (ppr e)
1023
1024 mkDefaultArgsMsg :: [Var] -> Message
1025 mkDefaultArgsMsg args 
1026   = hang (text "DEFAULT case with binders")
1027          4 (ppr args)
1028
1029 mkCaseAltMsg :: CoreExpr -> Type -> Type -> Message
1030 mkCaseAltMsg e ty1 ty2
1031   = hang (text "Type of case alternatives not the same as the annotation on case:")
1032          4 (vcat [ppr ty1, ppr ty2, ppr e])
1033
1034 mkScrutMsg :: Id -> Type -> Type -> TvSubst -> Message
1035 mkScrutMsg var var_ty scrut_ty subst
1036   = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
1037           text "Result binder type:" <+> ppr var_ty,--(idType var),
1038           text "Scrutinee type:" <+> ppr scrut_ty,
1039      hsep [ptext (sLit "Current TV subst"), ppr subst]]
1040
1041 mkNonDefltMsg, mkNonIncreasingAltsMsg :: CoreExpr -> Message
1042 mkNonDefltMsg e
1043   = hang (text "Case expression with DEFAULT not at the beginnning") 4 (ppr e)
1044 mkNonIncreasingAltsMsg e
1045   = hang (text "Case expression with badly-ordered alternatives") 4 (ppr e)
1046
1047 nonExhaustiveAltsMsg :: CoreExpr -> Message
1048 nonExhaustiveAltsMsg e
1049   = hang (text "Case expression with non-exhaustive alternatives") 4 (ppr e)
1050
1051 mkBadConMsg :: TyCon -> DataCon -> Message
1052 mkBadConMsg tycon datacon
1053   = vcat [
1054         text "In a case alternative, data constructor isn't in scrutinee type:",
1055         text "Scrutinee type constructor:" <+> ppr tycon,
1056         text "Data con:" <+> ppr datacon
1057     ]
1058
1059 mkBadPatMsg :: Type -> Type -> Message
1060 mkBadPatMsg con_result_ty scrut_ty
1061   = vcat [
1062         text "In a case alternative, pattern result type doesn't match scrutinee type:",
1063         text "Pattern result type:" <+> ppr con_result_ty,
1064         text "Scrutinee type:" <+> ppr scrut_ty
1065     ]
1066
1067 mkBadAltMsg :: Type -> CoreAlt -> Message
1068 mkBadAltMsg scrut_ty alt
1069   = vcat [ text "Data alternative when scrutinee is not a tycon application",
1070            text "Scrutinee type:" <+> ppr scrut_ty,
1071            text "Alternative:" <+> pprCoreAlt alt ]
1072
1073 mkNewTyDataConAltMsg :: Type -> CoreAlt -> Message
1074 mkNewTyDataConAltMsg scrut_ty alt
1075   = vcat [ text "Data alternative for newtype datacon",
1076            text "Scrutinee type:" <+> ppr scrut_ty,
1077            text "Alternative:" <+> pprCoreAlt alt ]
1078
1079
1080 ------------------------------------------------------
1081 --      Other error messages
1082
1083 mkAppMsg :: Type -> Type -> CoreExpr -> Message
1084 mkAppMsg fun_ty arg_ty arg
1085   = vcat [ptext (sLit "Argument value doesn't match argument type:"),
1086               hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
1087               hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
1088               hang (ptext (sLit "Arg:")) 4 (ppr arg)]
1089
1090 mkNonFunAppMsg :: Type -> Type -> CoreExpr -> Message
1091 mkNonFunAppMsg fun_ty arg_ty arg
1092   = vcat [ptext (sLit "Non-function type in function position"),
1093               hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
1094               hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
1095               hang (ptext (sLit "Arg:")) 4 (ppr arg)]
1096
1097 mkTyVarLetErr :: TyVar -> Type -> Message
1098 mkTyVarLetErr tyvar ty
1099   = vcat [ptext (sLit "Bad `let' binding for type or coercion variable:"),
1100           hang (ptext (sLit "Type/coercion variable:"))
1101                  4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
1102           hang (ptext (sLit "Arg type/coercion:"))   
1103                  4 (ppr ty)]
1104
1105 mkKindErrMsg :: TyVar -> Type -> Message
1106 mkKindErrMsg tyvar arg_ty
1107   = vcat [ptext (sLit "Kinds don't match in type application:"),
1108           hang (ptext (sLit "Type variable:"))
1109                  4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
1110           hang (ptext (sLit "Arg type:"))   
1111                  4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
1112
1113 mkCoAppErrMsg :: TyVar -> Type -> Message
1114 mkCoAppErrMsg tyvar arg_ty
1115   = vcat [ptext (sLit "Kinds don't match in coercion application:"),
1116           hang (ptext (sLit "Coercion variable:"))
1117                  4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
1118           hang (ptext (sLit "Arg coercion:"))   
1119                  4 (ppr arg_ty <+> dcolon <+> pprEqPred (coercionKind arg_ty))]
1120
1121 mkTyAppMsg :: Type -> Type -> Message
1122 mkTyAppMsg ty arg_ty
1123   = vcat [text "Illegal type application:",
1124               hang (ptext (sLit "Exp type:"))
1125                  4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
1126               hang (ptext (sLit "Arg type:"))   
1127                  4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
1128
1129 mkRhsMsg :: Id -> Type -> Message
1130 mkRhsMsg binder ty
1131   = vcat
1132     [hsep [ptext (sLit "The type of this binder doesn't match the type of its RHS:"),
1133             ppr binder],
1134      hsep [ptext (sLit "Binder's type:"), ppr (idType binder)],
1135      hsep [ptext (sLit "Rhs type:"), ppr ty]]
1136
1137 mkRhsPrimMsg :: Id -> CoreExpr -> Message
1138 mkRhsPrimMsg binder _rhs
1139   = vcat [hsep [ptext (sLit "The type of this binder is primitive:"),
1140                      ppr binder],
1141               hsep [ptext (sLit "Binder's type:"), ppr (idType binder)]
1142              ]
1143
1144 mkStrictMsg :: Id -> Message
1145 mkStrictMsg binder
1146   = vcat [hsep [ptext (sLit "Recursive or top-level binder has strict demand info:"),
1147                      ppr binder],
1148               hsep [ptext (sLit "Binder's demand info:"), ppr (idDemandInfo binder)]
1149              ]
1150
1151 mkArityMsg :: Id -> Message
1152 mkArityMsg binder
1153   = vcat [hsep [ptext (sLit "Demand type has "),
1154                      ppr (dmdTypeDepth dmd_ty),
1155                      ptext (sLit " arguments, rhs has "),
1156                      ppr (idArity binder),
1157                      ptext (sLit "arguments, "),
1158                      ppr binder],
1159               hsep [ptext (sLit "Binder's strictness signature:"), ppr dmd_ty]
1160
1161          ]
1162            where (StrictSig dmd_ty) = idStrictness binder
1163
1164 mkUnboxedTupleMsg :: Id -> Message
1165 mkUnboxedTupleMsg binder
1166   = vcat [hsep [ptext (sLit "A variable has unboxed tuple type:"), ppr binder],
1167           hsep [ptext (sLit "Binder's type:"), ppr (idType binder)]]
1168
1169 mkCastErr :: Type -> Type -> Message
1170 mkCastErr from_ty expr_ty
1171   = vcat [ptext (sLit "From-type of Cast differs from type of enclosed expression"),
1172           ptext (sLit "From-type:") <+> ppr from_ty,
1173           ptext (sLit "Type of enclosed expr:") <+> ppr expr_ty
1174     ]
1175
1176 dupVars :: [[Var]] -> Message
1177 dupVars vars
1178   = hang (ptext (sLit "Duplicate variables brought into scope"))
1179        2 (ppr vars)
1180 \end{code}