[project @ 2004-11-30 14:28:02 by simonpj]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreLint.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[CoreLint]{A ``lint'' pass to check for Core correctness}
5
6 \begin{code}
7 module CoreLint (
8         lintCoreBindings,
9         lintUnfolding, 
10         showPass, endPass
11     ) where
12
13 #include "HsVersions.h"
14
15 import CoreSyn
16 import CoreFVs          ( idFreeVars )
17 import CoreUtils        ( findDefault, exprOkForSpeculation, coreBindsSize, mkPiType )
18 import Unify            ( coreRefineTys )
19 import Bag
20 import Literal          ( literalType )
21 import DataCon          ( dataConRepType, isVanillaDataCon, dataConTyCon, dataConResTy )
22 import Var              ( Var, Id, TyVar, idType, tyVarKind, mustHaveLocalBinding )
23 import VarSet
24 import Name             ( getSrcLoc )
25 import PprCore
26 import ErrUtils         ( dumpIfSet_core, ghcExit, Message, showPass,
27                           mkLocMessage, debugTraceMsg )
28 import SrcLoc           ( SrcLoc, noSrcLoc, mkSrcSpan )
29 import Type             ( Type, tyVarsOfType, eqType,
30                           splitFunTy_maybe, mkTyVarTys,
31                           splitForAllTy_maybe, splitTyConApp_maybe,
32                           isUnLiftedType, typeKind, 
33                           isUnboxedTupleType, isSubKind,
34                           substTyWith, emptyTvSubst, extendTvInScope, 
35                           TvSubst, TvSubstEnv, setTvSubstEnv, substTy,
36                           extendTvSubst, isInScope )
37 import TyCon            ( isPrimTyCon )
38 import BasicTypes       ( RecFlag(..), isNonRec )
39 import CmdLineOpts
40 import Outputable
41
42 #ifdef DEBUG
43 import Util             ( notNull )
44 #endif
45
46 import Maybe
47
48 \end{code}
49
50 %************************************************************************
51 %*                                                                      *
52 \subsection{End pass}
53 %*                                                                      *
54 %************************************************************************
55
56 @showPass@ and @endPass@ don't really belong here, but it makes a convenient
57 place for them.  They print out stuff before and after core passes,
58 and do Core Lint when necessary.
59
60 \begin{code}
61 endPass :: DynFlags -> String -> DynFlag -> [CoreBind] -> IO [CoreBind]
62 endPass dflags pass_name dump_flag binds
63   = do 
64         -- Report result size if required
65         -- This has the side effect of forcing the intermediate to be evaluated
66         debugTraceMsg dflags $
67                 "    Result size = " ++ show (coreBindsSize binds)
68
69         -- Report verbosely, if required
70         dumpIfSet_core dflags dump_flag pass_name (pprCoreBindings binds)
71
72         -- Type check
73         lintCoreBindings dflags pass_name binds
74
75         return binds
76 \end{code}
77
78
79 %************************************************************************
80 %*                                                                      *
81 \subsection[lintCoreBindings]{@lintCoreBindings@: Top-level interface}
82 %*                                                                      *
83 %************************************************************************
84
85 Checks that a set of core bindings is well-formed.  The PprStyle and String
86 just control what we print in the event of an error.  The Bool value
87 indicates whether we have done any specialisation yet (in which case we do
88 some extra checks).
89
90 We check for
91         (a) type errors
92         (b) Out-of-scope type variables
93         (c) Out-of-scope local variables
94         (d) Ill-kinded types
95
96 If we have done specialisation the we check that there are
97         (a) No top-level bindings of primitive (unboxed type)
98
99 Outstanding issues:
100
101     --
102     -- Things are *not* OK if:
103     --
104     -- * Unsaturated type app before specialisation has been done;
105     --
106     -- * Oversaturated type app after specialisation (eta reduction
107     --   may well be happening...);
108
109 \begin{code}
110 lintCoreBindings :: DynFlags -> String -> [CoreBind] -> IO ()
111
112 lintCoreBindings dflags whoDunnit binds
113   | not (dopt Opt_DoCoreLinting dflags)
114   = return ()
115
116 lintCoreBindings dflags whoDunnit binds
117   = case (initL (lint_binds binds)) of
118       Nothing       -> showPass dflags ("Core Linted result of " ++ whoDunnit)
119       Just bad_news -> printDump (display bad_news)     >>
120                        ghcExit 1
121   where
122         -- Put all the top-level binders in scope at the start
123         -- This is because transformation rules can bring something
124         -- into use 'unexpectedly'
125     lint_binds binds = addInScopeVars (bindersOfBinds binds) $
126                        mapM lint_bind binds 
127
128     lint_bind (Rec prs)         = mapM_ (lintSingleBinding Recursive) prs
129     lint_bind (NonRec bndr rhs) = lintSingleBinding NonRecursive (bndr,rhs)
130
131     display bad_news
132       = vcat [  text ("*** Core Lint Errors: in result of " ++ whoDunnit ++ " ***"),
133                 bad_news,
134                 ptext SLIT("*** Offending Program ***"),
135                 pprCoreBindings binds,
136                 ptext SLIT("*** End of Offense ***")
137         ]
138 \end{code}
139
140 %************************************************************************
141 %*                                                                      *
142 \subsection[lintUnfolding]{lintUnfolding}
143 %*                                                                      *
144 %************************************************************************
145
146 We use this to check all unfoldings that come in from interfaces
147 (it is very painful to catch errors otherwise):
148
149 \begin{code}
150 lintUnfolding :: SrcLoc
151               -> [Var]          -- Treat these as in scope
152               -> CoreExpr
153               -> Maybe Message  -- Nothing => OK
154
155 lintUnfolding locn vars expr
156   = initL (addLoc (ImportedUnfolding locn) $
157            addInScopeVars vars             $
158            lintCoreExpr expr)
159 \end{code}
160
161 %************************************************************************
162 %*                                                                      *
163 \subsection[lintCoreBinding]{lintCoreBinding}
164 %*                                                                      *
165 %************************************************************************
166
167 Check a core binding, returning the list of variables bound.
168
169 \begin{code}
170 lintSingleBinding rec_flag (binder,rhs)
171   = addLoc (RhsOf binder) $
172          -- Check the rhs 
173     do { ty <- lintCoreExpr rhs 
174        ; lintBinder binder -- Check match to RHS type
175        ; binder_ty <- applySubst binder_ty
176        ; checkTys binder_ty ty (mkRhsMsg binder ty)
177         -- Check (not isUnLiftedType) (also checks for bogus unboxed tuples)
178        ; checkL (not (isUnLiftedType binder_ty)
179             || (isNonRec rec_flag && exprOkForSpeculation rhs))
180            (mkRhsPrimMsg binder rhs)
181         -- Check whether binder's specialisations contain any out-of-scope variables
182        ; mapM_ (checkBndrIdInScope binder) bndr_vars }
183           
184         -- We should check the unfolding, if any, but this is tricky because
185         -- the unfolding is a SimplifiableCoreExpr. Give up for now.
186   where
187     binder_ty = idType binder
188     bndr_vars = varSetElems (idFreeVars binder)
189 \end{code}
190
191 %************************************************************************
192 %*                                                                      *
193 \subsection[lintCoreExpr]{lintCoreExpr}
194 %*                                                                      *
195 %************************************************************************
196
197 \begin{code}
198
199 lintCoreExpr :: CoreExpr -> LintM Type
200 -- The returned type has the substitution from the monad 
201 -- already applied to it:
202 --      lintCoreExpr e subst = exprTpye (subst e)
203
204 lintCoreExpr (Var var)
205   = do  { checkIdInScope var 
206         ; applySubst (idType var) }
207
208 lintCoreExpr (Lit lit)
209   = return (literalType lit)
210
211 lintCoreExpr (Note (Coerce to_ty from_ty) expr)
212   = do  { expr_ty <- lintCoreExpr expr
213         ; to_ty <- lintTy to_ty
214         ; from_ty <- lintTy from_ty     
215         ; checkTys from_ty expr_ty (mkCoerceErr from_ty expr_ty)
216         ; return to_ty }
217
218 lintCoreExpr (Note other_note expr)
219   = lintCoreExpr expr
220
221 lintCoreExpr (Let (NonRec bndr rhs) body)
222   = do  { lintSingleBinding NonRecursive (bndr,rhs)
223         ; addLoc (BodyOfLetRec [bndr])
224                  (addInScopeVars [bndr] (lintCoreExpr body)) }
225
226 lintCoreExpr (Let (Rec pairs) body) 
227   = addInScopeVars bndrs        $
228     do  { mapM (lintSingleBinding Recursive) pairs      
229         ; addLoc (BodyOfLetRec bndrs) (lintCoreExpr body) }
230   where
231     bndrs = map fst pairs
232
233 lintCoreExpr (App fun (Type ty))
234 -- This is like 'let' for types
235 -- It's needed when dealing with desugarer output for GADTs. Consider
236 --   data T = forall a. T a (a->Int) Bool
237 --    f :: T -> ... -> 
238 --    f (T x f True)  = <e1>
239 --    f (T y g False) = <e2>
240 -- After desugaring we get
241 --      f t b = case t of 
242 --                T a (x::a) (f::a->Int) (b:Bool) ->
243 --                  case b of 
244 --                      True -> <e1>
245 --                      False -> (/\b. let y=x; g=f in <e2>) a
246 -- And for a reason I now forget, the ...<e2>... can mention a; so 
247 -- we want Lint to know that b=a.  Ugh.
248 --
249 -- I tried quite hard to make the necessity for this go away, by changing the 
250 -- desugarer, but the fundamental problem is this:
251 --      
252 --      T a (x::a) (y::Int) -> let fail::a = ...
253 --                             in (/\b. ...(case ... of       
254 --                                              True  -> x::b
255 --                                              False -> fail)
256 --                                ) a
257 -- Now the inner case look as though it has incompatible branches.
258   = go fun [ty]
259   where
260     go (App fun (Type ty)) tys
261         = do { go fun (ty:tys) }
262     go (Lam tv body) (ty:tys)
263         = do  { checkL (isTyVar tv) (mkKindErrMsg tv ty)        -- Not quite accurate
264               ; ty' <- lintTy ty; 
265               ; checkKinds tv ty'
266                 -- Now extend the substitution so we 
267                 -- take advantage of it in the body
268               ; addInScopeVars [tv] $
269                 extendSubstL tv ty' $
270                 go body tys }
271     go fun tys
272         = do  { fun_ty <- lintCoreExpr fun
273               ; lintCoreArgs fun_ty (map Type tys) }
274
275 lintCoreExpr e@(App fun arg)
276   = do  { ty <- lintCoreExpr fun
277         ; addLoc (AnExpr e) $
278           lintCoreArg ty arg }
279
280 lintCoreExpr (Lam var expr)
281   = addLoc (LambdaBodyOf var) $
282     do  { lintBinder var        
283         ; ty <- addInScopeVars [var] $
284                 lintCoreExpr expr
285         ; applySubst (mkPiType var ty) }
286         -- The applySubst is needed to apply the subst to var
287
288 lintCoreExpr e@(Case scrut var alt_ty alts) =
289        -- Check the scrutinee
290   do { scrut_ty <- lintCoreExpr scrut
291      ; alt_ty   <- lintTy alt_ty  
292      ; var_ty   <- lintTy (idType var)  
293         -- Don't use lintId on var, because unboxed tuple is legitimate
294
295      ; checkTys var_ty scrut_ty (mkScrutMsg var scrut_ty)
296
297      -- If the binder is an unboxed tuple type, don't put it in scope
298      ; let vars = if (isUnboxedTupleType (idType var)) then [] else [var]
299      ; addInScopeVars vars $
300        do { -- Check the alternatives
301             checkCaseAlts e scrut_ty alts
302           ; mapM (lintCoreAlt scrut_ty alt_ty) alts
303           ; return alt_ty } }
304
305 lintCoreExpr e@(Type ty)
306   = addErrL (mkStrangeTyMsg e)
307 \end{code}
308
309 %************************************************************************
310 %*                                                                      *
311 \subsection[lintCoreArgs]{lintCoreArgs}
312 %*                                                                      *
313 %************************************************************************
314
315 The basic version of these functions checks that the argument is a
316 subtype of the required type, as one would expect.
317
318 \begin{code}
319 lintCoreArgs :: Type -> [CoreArg] -> LintM Type
320 lintCoreArg  :: Type -> CoreArg   -> LintM Type
321 -- First argument has already had substitution applied to it
322 \end{code}
323
324 \begin{code}
325 lintCoreArgs ty [] = return ty
326 lintCoreArgs ty (a : args) = 
327   do { res <- lintCoreArg ty a
328      ; lintCoreArgs res args }
329
330 lintCoreArg ty a@(Type arg_ty) = 
331   do { arg_ty <- lintTy arg_ty  
332      ; lintTyApp ty arg_ty }
333
334 lintCoreArg fun_ty arg = 
335        -- Make sure function type matches argument
336   do { arg_ty <- lintCoreExpr arg
337      ; let err = mkAppMsg fun_ty arg_ty
338      ; case splitFunTy_maybe fun_ty of
339         Just (arg,res) -> 
340           do { checkTys arg arg_ty err 
341              ; return res }
342         _ -> addErrL err }
343 \end{code}
344
345 \begin{code}
346 -- Both args have had substitution applied
347 lintTyApp ty arg_ty 
348   = case splitForAllTy_maybe ty of
349       Nothing -> addErrL (mkTyAppMsg ty arg_ty)
350
351       Just (tyvar,body)
352         -> do   { checkL (isTyVar tyvar) (mkTyAppMsg ty arg_ty)
353                 ; checkKinds tyvar arg_ty
354                 ; return (substTyWith [tyvar] [arg_ty] body) }
355
356 lintTyApps fun_ty [] = return fun_ty
357
358 lintTyApps fun_ty (arg_ty : arg_tys) = 
359   do { fun_ty' <- lintTyApp fun_ty arg_ty
360      ; lintTyApps fun_ty' arg_tys }
361
362 checkKinds tyvar arg_ty
363         -- Arg type might be boxed for a function with an uncommitted
364         -- tyvar; notably this is used so that we can give
365         --      error :: forall a:*. String -> a
366         -- and then apply it to both boxed and unboxed types.
367   = checkL (argty_kind `isSubKind` tyvar_kind)
368            (mkKindErrMsg tyvar arg_ty)
369   where
370     tyvar_kind = tyVarKind tyvar
371     argty_kind = typeKind arg_ty
372 \end{code}
373
374
375 %************************************************************************
376 %*                                                                      *
377 \subsection[lintCoreAlts]{lintCoreAlts}
378 %*                                                                      *
379 %************************************************************************
380
381 \begin{code}
382 checkCaseAlts :: CoreExpr -> Type -> [CoreAlt] -> LintM ()
383 -- a) Check that the alts are non-empty
384 -- b) Check that the DEFAULT comes first, if it exists
385 -- c) Check that there's a default for infinite types
386 -- NB: Algebraic cases are not necessarily exhaustive, because
387 --     the simplifer correctly eliminates case that can't 
388 --     possibly match.
389
390 checkCaseAlts e ty [] 
391   = addErrL (mkNullAltsMsg e)
392
393 checkCaseAlts e ty alts = 
394   do { checkL (all non_deflt con_alts) (mkNonDefltMsg e)
395      ; checkL (isJust maybe_deflt || not is_infinite_ty)
396            (nonExhaustiveAltsMsg e) }
397   where
398     (con_alts, maybe_deflt) = findDefault alts
399
400     non_deflt (DEFAULT, _, _) = False
401     non_deflt alt             = True
402
403     is_infinite_ty = case splitTyConApp_maybe ty of
404                         Nothing                     -> False
405                         Just (tycon, tycon_arg_tys) -> isPrimTyCon tycon
406 \end{code}
407
408 \begin{code}
409 checkAltExpr :: CoreExpr -> Type -> LintM ()
410 checkAltExpr expr ty    
411   = do { actual_ty <- lintCoreExpr expr 
412        ; ty' <- applySubst ty
413        ; checkTys actual_ty ty' (mkCaseAltMsg expr actual_ty ty') }
414
415 lintCoreAlt :: Type                     -- Type of scrutinee
416             -> Type                     -- Type of the alternative
417             -> CoreAlt
418             -> LintM ()
419
420 lintCoreAlt scrut_ty alt_ty alt@(DEFAULT, args, rhs) = 
421   do { checkL (null args) (mkDefaultArgsMsg args)
422      ; checkAltExpr rhs alt_ty }
423
424 lintCoreAlt scrut_ty alt_ty alt@(LitAlt lit, args, rhs) = 
425   do { checkL (null args) (mkDefaultArgsMsg args)
426      ; checkTys lit_ty scrut_ty
427           (mkBadPatMsg lit_ty scrut_ty) 
428      ; checkAltExpr rhs alt_ty } 
429   where
430     lit_ty = literalType lit
431
432 lintCoreAlt scrut_ty alt_ty alt@(DataAlt con, args, rhs)
433   | Just (tycon, tycon_arg_tys) <- splitTyConApp_maybe scrut_ty,
434     tycon == dataConTyCon con
435   = addLoc (CaseAlt alt) $
436     addInScopeVars args $       -- Put the args in scope before lintBinder,
437                                 -- because the Ids mention the type variables
438     if isVanillaDataCon con then
439     do  { mapM lintBinder args 
440                 -- FIX! Add check that all args are Ids.
441                  -- Check the pattern
442                  -- Scrutinee type must be a tycon applicn; checked by caller
443                  -- This code is remarkably compact considering what it does!
444                  -- NB: args must be in scope here so that the lintCoreArgs line works.
445                  -- NB: relies on existential type args coming *after* ordinary type args
446
447         ; con_type <- lintTyApps (dataConRepType con) tycon_arg_tys
448                  -- Can just map Var as we know that this is a vanilla datacon
449         ; con_result_ty <- lintCoreArgs con_type (map Var args)
450         ; checkTys con_result_ty scrut_ty (mkBadPatMsg con_result_ty scrut_ty) 
451                  -- Check the RHS
452         ; checkAltExpr rhs alt_ty }
453
454     else        -- GADT
455     do  { let (tvs,ids) = span isTyVar args
456               pat_res_ty = dataConResTy con (mkTyVarTys tvs)          
457
458         ; subst <- getTvSubst 
459         ; case coreRefineTys tvs subst pat_res_ty scrut_ty of {
460              Nothing   -> return () ;   -- Alternative is dead code
461              Just senv -> updateTvSubstEnv senv $
462     do  { tvs'     <- mapM lintTy (mkTyVarTys tvs)
463         ; con_type <- lintTyApps (dataConRepType con) tvs'
464         ; mapM lintBinder ids   -- Lint Ids in the refined world
465         ; lintCoreArgs con_type (map Var ids)
466         ; checkAltExpr rhs alt_ty
467     } } }
468
469   | otherwise   -- Scrut-ty is wrong shape
470   = addErrL (mkBadAltMsg scrut_ty alt)
471 \end{code}
472
473 %************************************************************************
474 %*                                                                      *
475 \subsection[lint-types]{Types}
476 %*                                                                      *
477 %************************************************************************
478
479 \begin{code}
480 lintBinder :: Var -> LintM ()
481 lintBinder var | isId var  = lintId var >> return ()
482                | otherwise = return ()
483
484 lintId :: Var -> LintM Type
485 -- ToDo: lint its rules
486 lintId id
487   = do  { checkL (not (isUnboxedTupleType (idType id))) 
488                  (mkUnboxedTupleMsg id)
489                 -- No variable can be bound to an unboxed tuple.
490         ; lintTy (idType id) }
491
492 lintTy :: Type -> LintM Type
493 -- Check the type, and apply the substitution to it
494 -- ToDo: check the kind structure of the type
495 lintTy ty 
496   = do  { ty' <- applySubst ty
497         ; mapM_ checkIdInScope (varSetElems (tyVarsOfType ty'))
498         ; return ty' }
499 \end{code}
500
501     
502 %************************************************************************
503 %*                                                                      *
504 \subsection[lint-monad]{The Lint monad}
505 %*                                                                      *
506 %************************************************************************
507
508 \begin{code}
509 newtype LintM a = 
510    LintM { unLintM :: 
511             [LintLocInfo] ->         -- Locations
512             TvSubst ->               -- Current type substitution; we also use this
513                                      -- to keep track of all the variables in scope,
514                                      -- both Ids and TyVars
515             Bag Message ->           -- Error messages so far
516             (Maybe a, Bag Message) } -- Result and error messages (if any)
517
518 instance Monad LintM where
519   return x = LintM (\ loc subst errs -> (Just x, errs))
520   fail err = LintM (\ loc subst errs -> (Nothing, addErr subst errs (text err) loc))
521   m >>= k  = LintM (\ loc subst errs -> 
522                        let (res, errs') = unLintM m loc subst errs in
523                          case res of
524                            Just r -> unLintM (k r) loc subst errs'
525                            Nothing -> (Nothing, errs'))
526
527 data LintLocInfo
528   = RhsOf Id            -- The variable bound
529   | LambdaBodyOf Id     -- The lambda-binder
530   | BodyOfLetRec [Id]   -- One of the binders
531   | CaseAlt CoreAlt     -- Pattern of a case alternative
532   | AnExpr CoreExpr     -- Some expression
533   | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
534 \end{code}
535
536                  
537 \begin{code}
538 initL :: LintM a -> Maybe Message {- errors -}
539 initL m
540   = case unLintM m [] emptyTvSubst emptyBag of
541       (_, errs) | isEmptyBag errs -> Nothing
542                 | otherwise       -> Just (vcat (punctuate (text "") (bagToList errs)))
543 \end{code}
544
545 \begin{code}
546 checkL :: Bool -> Message -> LintM ()
547 checkL True  msg = return ()
548 checkL False msg = addErrL msg
549
550 addErrL :: Message -> LintM a
551 addErrL msg = LintM (\ loc subst errs -> (Nothing, addErr subst errs msg loc))
552
553 addErr :: TvSubst -> Bag Message -> Message -> [LintLocInfo] -> Bag Message
554 addErr subst errs_so_far msg locs
555   = ASSERT( notNull locs )
556     errs_so_far `snocBag` mk_msg msg
557   where
558    (loc, cxt1) = dumpLoc (head locs)
559    cxts        = [snd (dumpLoc loc) | loc <- locs]   
560    context     | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1 $$
561                                       ptext SLIT("Substitution:") <+> ppr subst
562                | otherwise          = cxt1
563  
564    mk_msg msg = mkLocMessage (mkSrcSpan loc loc) (context $$ msg)
565
566 addLoc :: LintLocInfo -> LintM a -> LintM a
567 addLoc extra_loc m =
568   LintM (\ loc subst errs -> unLintM m (extra_loc:loc) subst errs)
569
570 addInScopeVars :: [Var] -> LintM a -> LintM a
571 addInScopeVars vars m = 
572   LintM (\ loc subst errs -> unLintM m loc (extendTvInScope subst vars) errs)
573
574 -- gaw 2004
575 updateTvSubstEnv :: TvSubstEnv -> LintM a -> LintM a
576 updateTvSubstEnv substenv m = 
577   LintM (\ loc subst errs -> unLintM m loc (setTvSubstEnv subst substenv) errs)
578
579 getTvSubst :: LintM TvSubst
580 getTvSubst = LintM (\ loc subst errs -> (Just subst, errs))
581
582 applySubst :: Type -> LintM Type
583 applySubst ty = do { subst <- getTvSubst; return (substTy subst ty) }
584
585 extendSubstL :: TyVar -> Type -> LintM a -> LintM a
586 extendSubstL tv ty m
587   = LintM (\ loc subst errs -> unLintM m loc (extendTvSubst subst tv ty) errs)
588 \end{code}
589
590 \begin{code}
591 checkIdInScope :: Var -> LintM ()
592 checkIdInScope id 
593   = checkInScope (ptext SLIT("is out of scope")) id
594
595 checkBndrIdInScope :: Var -> Var -> LintM ()
596 checkBndrIdInScope binder id 
597   = checkInScope msg id
598     where
599      msg = ptext SLIT("is out of scope inside info for") <+> 
600            ppr binder
601
602 checkInScope :: SDoc -> Var -> LintM ()
603 checkInScope loc_msg var =
604  do { subst <- getTvSubst
605     ; checkL (not (mustHaveLocalBinding var) || (var `isInScope` subst))
606              (hsep [ppr var, loc_msg]) }
607
608 checkTys :: Type -> Type -> Message -> LintM ()
609 -- check ty2 is subtype of ty1 (ie, has same structure but usage
610 -- annotations need only be consistent, not equal)
611 -- Assumes ty1,ty2 are have alrady had the substitution applied
612 checkTys ty1 ty2 msg = checkL (ty1 `eqType` ty2) msg
613 \end{code}
614
615 %************************************************************************
616 %*                                                                      *
617 \subsection{Error messages}
618 %*                                                                      *
619 %************************************************************************
620
621 \begin{code}
622 dumpLoc (RhsOf v)
623   = (getSrcLoc v, brackets (ptext SLIT("RHS of") <+> pp_binders [v]))
624
625 dumpLoc (LambdaBodyOf b)
626   = (getSrcLoc b, brackets (ptext SLIT("in body of lambda with binder") <+> pp_binder b))
627
628 dumpLoc (BodyOfLetRec [])
629   = (noSrcLoc, brackets (ptext SLIT("In body of a letrec with no binders")))
630
631 dumpLoc (BodyOfLetRec bs@(_:_))
632   = ( getSrcLoc (head bs), brackets (ptext SLIT("in body of letrec with binders") <+> pp_binders bs))
633
634 dumpLoc (AnExpr e)
635   = (noSrcLoc, text "In the expression:" <+> ppr e)
636
637 dumpLoc (CaseAlt (con, args, rhs))
638   = (noSrcLoc, text "In a case alternative:" <+> parens (ppr con <+> ppr args))
639
640 dumpLoc (ImportedUnfolding locn)
641   = (locn, brackets (ptext SLIT("in an imported unfolding")))
642
643 pp_binders :: [Var] -> SDoc
644 pp_binders bs = sep (punctuate comma (map pp_binder bs))
645
646 pp_binder :: Var -> SDoc
647 pp_binder b | isId b    = hsep [ppr b, dcolon, ppr (idType b)]
648             | isTyVar b = hsep [ppr b, dcolon, ppr (tyVarKind b)]
649 \end{code}
650
651 \begin{code}
652 ------------------------------------------------------
653 --      Messages for case expressions
654
655 mkNullAltsMsg :: CoreExpr -> Message
656 mkNullAltsMsg e 
657   = hang (text "Case expression with no alternatives:")
658          4 (ppr e)
659
660 mkDefaultArgsMsg :: [Var] -> Message
661 mkDefaultArgsMsg args 
662   = hang (text "DEFAULT case with binders")
663          4 (ppr args)
664
665 mkCaseAltMsg :: CoreExpr -> Type -> Type -> Message
666 mkCaseAltMsg e ty1 ty2
667   = hang (text "Type of case alternatives not the same as the annotation on case:")
668          4 (vcat [ppr ty1, ppr ty2, ppr e])
669
670 mkScrutMsg :: Id -> Type -> Message
671 mkScrutMsg var scrut_ty
672   = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
673           text "Result binder type:" <+> ppr (idType var),
674           text "Scrutinee type:" <+> ppr scrut_ty]
675
676
677 mkNonDefltMsg e
678   = hang (text "Case expression with DEFAULT not at the beginnning") 4 (ppr e)
679
680 nonExhaustiveAltsMsg :: CoreExpr -> Message
681 nonExhaustiveAltsMsg e
682   = hang (text "Case expression with non-exhaustive alternatives") 4 (ppr e)
683
684 mkBadPatMsg :: Type -> Type -> Message
685 mkBadPatMsg con_result_ty scrut_ty
686   = vcat [
687         text "In a case alternative, pattern result type doesn't match scrutinee type:",
688         text "Pattern result type:" <+> ppr con_result_ty,
689         text "Scrutinee type:" <+> ppr scrut_ty
690     ]
691
692 mkBadAltMsg :: Type -> CoreAlt -> Message
693 mkBadAltMsg scrut_ty alt
694   = vcat [ text "Data alternative when scrutinee is not a tycon application",
695            text "Scrutinee type:" <+> ppr scrut_ty,
696            text "Alternative:" <+> pprCoreAlt alt ]
697
698 ------------------------------------------------------
699 --      Other error messages
700
701 mkAppMsg :: Type -> Type -> Message
702 mkAppMsg fun arg
703   = vcat [ptext SLIT("Argument value doesn't match argument type:"),
704               hang (ptext SLIT("Fun type:")) 4 (ppr fun),
705               hang (ptext SLIT("Arg type:")) 4 (ppr arg)]
706
707 mkKindErrMsg :: TyVar -> Type -> Message
708 mkKindErrMsg tyvar arg_ty
709   = vcat [ptext SLIT("Kinds don't match in type application:"),
710           hang (ptext SLIT("Type variable:"))
711                  4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
712           hang (ptext SLIT("Arg type:"))   
713                  4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
714
715 mkTyAppMsg :: Type -> Type -> Message
716 mkTyAppMsg ty arg_ty
717   = vcat [text "Illegal type application:",
718               hang (ptext SLIT("Exp type:"))
719                  4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
720               hang (ptext SLIT("Arg type:"))   
721                  4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
722
723 mkRhsMsg :: Id -> Type -> Message
724 mkRhsMsg binder ty
725   = vcat
726     [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
727             ppr binder],
728      hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
729      hsep [ptext SLIT("Rhs type:"), ppr ty]]
730
731 mkRhsPrimMsg :: Id -> CoreExpr -> Message
732 mkRhsPrimMsg binder rhs
733   = vcat [hsep [ptext SLIT("The type of this binder is primitive:"),
734                      ppr binder],
735               hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]
736              ]
737
738 mkUnboxedTupleMsg :: Id -> Message
739 mkUnboxedTupleMsg binder
740   = vcat [hsep [ptext SLIT("A variable has unboxed tuple type:"), ppr binder],
741           hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]]
742
743 mkCoerceErr from_ty expr_ty
744   = vcat [ptext SLIT("From-type of Coerce differs from type of enclosed expression"),
745           ptext SLIT("From-type:") <+> ppr from_ty,
746           ptext SLIT("Type of enclosed expr:") <+> ppr expr_ty
747     ]
748
749 mkStrangeTyMsg e
750   = ptext SLIT("Type where expression expected:") <+> ppr e
751 \end{code}