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