Don't import FastString in HsVersions.h
[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 (
11         lintCoreBindings,
12         lintUnfolding, 
13         showPass, endPass, endPassIf, endIteration
14     ) where
15
16 #include "HsVersions.h"
17
18 import NewDemand
19 import CoreSyn
20 import CoreFVs
21 import CoreUtils
22 import Bag
23 import Literal
24 import DataCon
25 import TysWiredIn
26 import Var
27 import VarEnv
28 import VarSet
29 import Name
30 import Id
31 import PprCore
32 import ErrUtils
33 import SrcLoc
34 import Type
35 import Coercion
36 import TyCon
37 import BasicTypes
38 import StaticFlags
39 import ListSetOps
40 import DynFlags
41 import Outputable
42 import FastString
43 import Util
44 import Data.Maybe
45 \end{code}
46
47 %************************************************************************
48 %*                                                                      *
49 \subsection{End pass}
50 %*                                                                      *
51 %************************************************************************
52
53 @showPass@ and @endPass@ don't really belong here, but it makes a convenient
54 place for them.  They print out stuff before and after core passes,
55 and do Core Lint when necessary.
56
57 \begin{code}
58 endPass :: DynFlags -> String -> DynFlag -> [CoreBind] -> IO [CoreBind]
59 endPass = dumpAndLint dumpIfSet_core
60
61 endPassIf :: Bool -> DynFlags -> String -> DynFlag -> [CoreBind] -> IO [CoreBind]
62 endPassIf cond = dumpAndLint (dumpIf_core cond)
63
64 endIteration :: DynFlags -> String -> DynFlag -> [CoreBind] -> IO [CoreBind]
65 endIteration = dumpAndLint dumpIfSet_dyn
66
67 dumpAndLint :: (DynFlags -> DynFlag -> String -> SDoc -> IO ())
68             -> DynFlags -> String -> DynFlag -> [CoreBind] -> IO [CoreBind]
69 dumpAndLint dump dflags pass_name dump_flag binds
70   = do 
71         -- Report result size if required
72         -- This has the side effect of forcing the intermediate to be evaluated
73         debugTraceMsg dflags 2 $
74                 (text "    Result size =" <+> int (coreBindsSize binds))
75
76         -- Report verbosely, if required
77         dump dflags dump_flag pass_name (pprCoreBindings binds)
78
79         -- Type check
80         lintCoreBindings dflags pass_name binds
81
82         return binds
83 \end{code}
84
85
86 %************************************************************************
87 %*                                                                      *
88 \subsection[lintCoreBindings]{@lintCoreBindings@: Top-level interface}
89 %*                                                                      *
90 %************************************************************************
91
92 Checks that a set of core bindings is well-formed.  The PprStyle and String
93 just control what we print in the event of an error.  The Bool value
94 indicates whether we have done any specialisation yet (in which case we do
95 some extra checks).
96
97 We check for
98         (a) type errors
99         (b) Out-of-scope type variables
100         (c) Out-of-scope local variables
101         (d) Ill-kinded types
102
103 If we have done specialisation the we check that there are
104         (a) No top-level bindings of primitive (unboxed type)
105
106 Outstanding issues:
107
108     --
109     -- Things are *not* OK if:
110     --
111     --  * Unsaturated type app before specialisation has been done;
112     --
113     --  * Oversaturated type app after specialisation (eta reduction
114     --   may well be happening...);
115
116
117 Note [Type lets]
118 ~~~~~~~~~~~~~~~~
119 In the desugarer, it's very very convenient to be able to say (in effect)
120         let a = Int in <body>
121 That is, use a type let.  (See notes just below for why we want this.)
122
123 We don't have type lets in Core, so the desugarer uses type lambda
124         (/\a. <body>) Int
125 However, in the lambda form, we'd get lint errors from:
126         (/\a. let x::a = 4 in <body>) Int
127 because (x::a) doesn't look compatible with (4::Int).
128
129 So (HACK ALERT) the Lint phase does type-beta reduction "on the fly",
130 as it were.  It carries a type substitution (in this example [a -> Int])
131 and applies this substitution before comparing types.  The functin
132         lintTy :: Type -> LintM Type
133 returns a substituted type; that's the only reason it returns anything.
134
135 When we encounter a binder (like x::a) we must apply the substitution
136 to the type of the binding variable.  lintBinders does this.
137
138 For Ids, the type-substituted Id is added to the in_scope set (which 
139 itself is part of the TvSubst we are carrying down), and when we
140 find an occurence of an Id, we fetch it from the in-scope set.
141
142
143 Why we need type let
144 ~~~~~~~~~~~~~~~~~~~~
145 It's needed when dealing with desugarer output for GADTs. Consider
146   data T = forall a. T a (a->Int) Bool
147    f :: T -> ... -> 
148    f (T x f True)  = <e1>
149    f (T y g False) = <e2>
150 After desugaring we get
151         f t b = case t of 
152                   T a (x::a) (f::a->Int) (b:Bool) ->
153                     case b of 
154                         True -> <e1>
155                         False -> (/\b. let y=x; g=f in <e2>) a
156 And for a reason I now forget, the ...<e2>... can mention a; so 
157 we want Lint to know that b=a.  Ugh.
158
159 I tried quite hard to make the necessity for this go away, by changing the 
160 desugarer, but the fundamental problem is this:
161         
162         T a (x::a) (y::Int) -> let fail::a = ...
163                                in (/\b. ...(case ... of       
164                                                 True  -> x::b
165                                                 False -> fail)
166                                   ) a
167 Now the inner case look as though it has incompatible branches.
168
169
170 \begin{code}
171 lintCoreBindings :: DynFlags -> String -> [CoreBind] -> IO ()
172
173 lintCoreBindings dflags _whoDunnit _binds
174   | not (dopt Opt_DoCoreLinting dflags)
175   = return ()
176
177 lintCoreBindings dflags whoDunnit binds
178   = case (initL (lint_binds binds)) of
179       Nothing       -> showPass dflags ("Core Linted result of " ++ whoDunnit)
180       Just bad_news -> printDump (display bad_news)     >>
181                        ghcExit dflags 1
182   where
183         -- Put all the top-level binders in scope at the start
184         -- This is because transformation rules can bring something
185         -- into use 'unexpectedly'
186     lint_binds binds = addLoc TopLevelBindings $
187                        addInScopeVars (bindersOfBinds binds) $
188                        mapM lint_bind binds 
189
190     lint_bind (Rec prs)         = mapM_ (lintSingleBinding TopLevel Recursive) prs
191     lint_bind (NonRec bndr rhs) = lintSingleBinding TopLevel NonRecursive (bndr,rhs)
192
193     display bad_news
194       = vcat [  text ("*** Core Lint Errors: in result of " ++ whoDunnit ++ " ***"),
195                 bad_news,
196                 ptext SLIT("*** Offending Program ***"),
197                 pprCoreBindings binds,
198                 ptext SLIT("*** End of Offense ***")
199         ]
200 \end{code}
201
202 %************************************************************************
203 %*                                                                      *
204 \subsection[lintUnfolding]{lintUnfolding}
205 %*                                                                      *
206 %************************************************************************
207
208 We use this to check all unfoldings that come in from interfaces
209 (it is very painful to catch errors otherwise):
210
211 \begin{code}
212 lintUnfolding :: SrcLoc
213               -> [Var]          -- Treat these as in scope
214               -> CoreExpr
215               -> Maybe Message  -- Nothing => OK
216
217 lintUnfolding locn vars expr
218   = initL (addLoc (ImportedUnfolding locn) $
219            addInScopeVars vars             $
220            lintCoreExpr expr)
221 \end{code}
222
223 %************************************************************************
224 %*                                                                      *
225 \subsection[lintCoreBinding]{lintCoreBinding}
226 %*                                                                      *
227 %************************************************************************
228
229 Check a core binding, returning the list of variables bound.
230
231 \begin{code}
232 lintSingleBinding :: TopLevelFlag -> RecFlag -> (Id, CoreExpr) -> LintM ()
233 lintSingleBinding top_lvl_flag rec_flag (binder,rhs)
234   = addLoc (RhsOf binder) $
235          -- Check the rhs 
236     do { ty <- lintCoreExpr rhs 
237        ; lintBinder binder -- Check match to RHS type
238        ; binder_ty <- applySubst binder_ty
239        ; checkTys binder_ty ty (mkRhsMsg binder ty)
240         -- Check (not isUnLiftedType) (also checks for bogus unboxed tuples)
241        ; checkL (not (isUnLiftedType binder_ty)
242             || (isNonRec rec_flag && exprOkForSpeculation rhs))
243            (mkRhsPrimMsg binder rhs)
244         -- Check that if the binder is top-level or recursive, it's not demanded
245        ; checkL (not (isStrictId binder)
246             || (isNonRec rec_flag && not (isTopLevel top_lvl_flag)))
247            (mkStrictMsg binder)
248         -- Check whether binder's specialisations contain any out-of-scope variables
249        ; mapM_ (checkBndrIdInScope binder) bndr_vars 
250
251       -- Check whether arity and demand type are consistent (only if demand analysis
252       -- already happened)
253        ; checkL (case maybeDmdTy of
254                   Just (StrictSig dmd_ty) -> idArity binder >= dmdTypeDepth dmd_ty || exprIsTrivial rhs
255                   Nothing -> True)
256            (mkArityMsg binder) }
257           
258         -- We should check the unfolding, if any, but this is tricky because
259         -- the unfolding is a SimplifiableCoreExpr. Give up for now.
260    where
261     binder_ty                  = idType binder
262     maybeDmdTy                 = idNewStrictness_maybe binder
263     bndr_vars                  = varSetElems (idFreeVars binder)
264     lintBinder var | isId var  = lintIdBndr var $ \_ -> (return ())
265                    | otherwise = return ()
266 \end{code}
267
268 %************************************************************************
269 %*                                                                      *
270 \subsection[lintCoreExpr]{lintCoreExpr}
271 %*                                                                      *
272 %************************************************************************
273
274 \begin{code}
275 type InType  = Type     -- Substitution not yet applied
276 type OutType = Type     -- Substitution has been applied to this
277
278 lintCoreExpr :: CoreExpr -> LintM OutType
279 -- The returned type has the substitution from the monad 
280 -- already applied to it:
281 --      lintCoreExpr e subst = exprType (subst e)
282
283 lintCoreExpr (Var var)
284   = do  { checkL (not (var == oneTupleDataConId))
285                  (ptext SLIT("Illegal one-tuple"))
286         ; var' <- lookupIdInScope var
287         ; return (idType var')
288         }
289
290 lintCoreExpr (Lit lit)
291   = return (literalType lit)
292
293 --lintCoreExpr (Note (Coerce to_ty from_ty) expr)
294 --  = do        { expr_ty <- lintCoreExpr expr
295 --      ; to_ty <- lintTy to_ty
296 --      ; from_ty <- lintTy from_ty     
297 --      ; checkTys from_ty expr_ty (mkCoerceErr from_ty expr_ty)
298 --      ; return to_ty }
299
300 lintCoreExpr (Cast expr co)
301   = do { expr_ty <- lintCoreExpr expr
302        ; co' <- lintTy co
303        ; let (from_ty, to_ty) = coercionKind co'
304        ; checkTys from_ty expr_ty (mkCastErr from_ty expr_ty)
305        ; return to_ty }
306
307 lintCoreExpr (Note _ expr)
308   = lintCoreExpr expr
309
310 lintCoreExpr (Let (NonRec bndr rhs) body)
311   = do  { lintSingleBinding NotTopLevel NonRecursive (bndr,rhs)
312         ; addLoc (BodyOfLetRec [bndr])
313                  (lintAndScopeId bndr $ \_ -> (lintCoreExpr body)) }
314
315 lintCoreExpr (Let (Rec pairs) body) 
316   = lintAndScopeIds bndrs       $ \_ ->
317     do  { mapM (lintSingleBinding NotTopLevel Recursive) pairs  
318         ; addLoc (BodyOfLetRec bndrs) (lintCoreExpr body) }
319   where
320     bndrs = map fst pairs
321
322 lintCoreExpr e@(App fun (Type ty))
323 -- See Note [Type let] above
324   = addLoc (AnExpr e) $
325     go fun [ty]
326   where
327     go (App fun (Type ty)) tys
328         = do { go fun (ty:tys) }
329     go (Lam tv body) (ty:tys)
330         = do  { checkL (isTyVar tv) (mkKindErrMsg tv ty)        -- Not quite accurate
331               ; ty' <- lintTy ty 
332               ; let kind = tyVarKind tv
333               ; kind' <- lintTy kind
334               ; let tv' = setTyVarKind tv kind'
335               ; checkKinds tv' ty'              
336                 -- Now extend the substitution so we 
337                 -- take advantage of it in the body
338               ; addInScopeVars [tv'] $
339                 extendSubstL tv' ty' $
340                 go body tys }
341     go fun tys
342         = do  { fun_ty <- lintCoreExpr fun
343               ; lintCoreArgs fun_ty (map Type tys) }
344
345 lintCoreExpr e@(App fun arg)
346   = do  { fun_ty <- lintCoreExpr fun
347         ; addLoc (AnExpr e) $
348           lintCoreArg fun_ty arg }
349
350 lintCoreExpr (Lam var expr)
351   = addLoc (LambdaBodyOf var) $
352     lintBinders [var] $ \[var'] -> 
353     do { body_ty <- lintCoreExpr expr
354        ; if isId var' then 
355              return (mkFunTy (idType var') body_ty) 
356          else
357              return (mkForAllTy var' body_ty)
358        }
359         -- The applySubst is needed to apply the subst to var
360
361 lintCoreExpr e@(Case scrut var alt_ty alts) =
362        -- Check the scrutinee
363   do { scrut_ty <- lintCoreExpr scrut
364      ; alt_ty   <- lintTy alt_ty  
365      ; var_ty   <- lintTy (idType var)  
366         -- Don't use lintIdBndr on var, because unboxed tuple is legitimate
367
368      ; subst <- getTvSubst 
369      ; checkTys var_ty scrut_ty (mkScrutMsg var var_ty scrut_ty subst)
370
371      -- If the binder is an unboxed tuple type, don't put it in scope
372      ; let scope = if (isUnboxedTupleType (idType var)) then 
373                        pass_var 
374                    else lintAndScopeId var
375      ; scope $ \_ ->
376        do { -- Check the alternatives
377             mapM (lintCoreAlt scrut_ty alt_ty) alts
378           ; checkCaseAlts e scrut_ty alts
379           ; return alt_ty } }
380   where
381     pass_var f = f var
382
383 lintCoreExpr e@(Type _)
384   = addErrL (mkStrangeTyMsg e)
385 \end{code}
386
387 %************************************************************************
388 %*                                                                      *
389 \subsection[lintCoreArgs]{lintCoreArgs}
390 %*                                                                      *
391 %************************************************************************
392
393 The basic version of these functions checks that the argument is a
394 subtype of the required type, as one would expect.
395
396 \begin{code}
397 lintCoreArgs :: OutType -> [CoreArg] -> LintM OutType
398 lintCoreArg  :: OutType -> CoreArg   -> LintM OutType
399 -- First argument has already had substitution applied to it
400 \end{code}
401
402 \begin{code}
403 lintCoreArgs ty [] = return ty
404 lintCoreArgs ty (a : args) = 
405   do { res <- lintCoreArg ty a
406      ; lintCoreArgs res args }
407
408 lintCoreArg fun_ty (Type arg_ty) =
409   do { arg_ty <- lintTy arg_ty  
410      ; lintTyApp fun_ty arg_ty }
411
412 lintCoreArg fun_ty arg = 
413        -- Make sure function type matches argument
414   do { arg_ty <- lintCoreExpr arg
415      ; let err1 =  mkAppMsg fun_ty arg_ty arg
416            err2 = mkNonFunAppMsg fun_ty arg_ty arg
417      ; case splitFunTy_maybe fun_ty of
418         Just (arg,res) -> 
419           do { checkTys arg arg_ty err1
420              ; return res }
421         _ -> addErrL err2 }
422 \end{code}
423
424 \begin{code}
425 -- Both args have had substitution applied
426 lintTyApp :: OutType -> OutType -> LintM OutType
427 lintTyApp ty arg_ty 
428   = case splitForAllTy_maybe ty of
429       Nothing -> addErrL (mkTyAppMsg ty arg_ty)
430
431       Just (tyvar,body)
432         -> do   { checkL (isTyVar tyvar) (mkTyAppMsg ty arg_ty)
433                 ; checkKinds tyvar arg_ty
434                 ; return (substTyWith [tyvar] [arg_ty] body) }
435
436 checkKinds :: Var -> Type -> LintM ()
437 checkKinds tyvar arg_ty
438         -- Arg type might be boxed for a function with an uncommitted
439         -- tyvar; notably this is used so that we can give
440         --      error :: forall a:*. String -> a
441         -- and then apply it to both boxed and unboxed types.
442   = checkL (arg_kind `isSubKind` tyvar_kind)
443            (mkKindErrMsg tyvar arg_ty)
444   where
445     tyvar_kind = tyVarKind tyvar
446     arg_kind | isCoVar tyvar = coercionKindPredTy arg_ty
447              | otherwise     = typeKind arg_ty
448 \end{code}
449
450
451 %************************************************************************
452 %*                                                                      *
453 \subsection[lintCoreAlts]{lintCoreAlts}
454 %*                                                                      *
455 %************************************************************************
456
457 \begin{code}
458 checkCaseAlts :: CoreExpr -> OutType -> [CoreAlt] -> LintM ()
459 -- a) Check that the alts are non-empty
460 -- b1) Check that the DEFAULT comes first, if it exists
461 -- b2) Check that the others are in increasing order
462 -- c) Check that there's a default for infinite types
463 -- NB: Algebraic cases are not necessarily exhaustive, because
464 --     the simplifer correctly eliminates case that can't 
465 --     possibly match.
466
467 checkCaseAlts e _ []
468   = addErrL (mkNullAltsMsg e)
469
470 checkCaseAlts e ty alts = 
471   do { checkL (all non_deflt con_alts) (mkNonDefltMsg e)
472      ; checkL (increasing_tag con_alts) (mkNonIncreasingAltsMsg e)
473      ; checkL (isJust maybe_deflt || not is_infinite_ty)
474            (nonExhaustiveAltsMsg e) }
475   where
476     (con_alts, maybe_deflt) = findDefault alts
477
478         -- Check that successive alternatives have increasing tags 
479     increasing_tag (alt1 : rest@( alt2 : _)) = alt1 `ltAlt` alt2 && increasing_tag rest
480     increasing_tag _                         = True
481
482     non_deflt (DEFAULT, _, _) = False
483     non_deflt _               = True
484
485     is_infinite_ty = case splitTyConApp_maybe ty of
486                         Nothing         -> False
487                         Just (tycon, _) -> isPrimTyCon tycon
488 \end{code}
489
490 \begin{code}
491 checkAltExpr :: CoreExpr -> OutType -> LintM ()
492 checkAltExpr expr ann_ty
493   = do { actual_ty <- lintCoreExpr expr 
494        ; checkTys actual_ty ann_ty (mkCaseAltMsg expr actual_ty ann_ty) }
495
496 lintCoreAlt :: OutType          -- Type of scrutinee
497             -> OutType          -- Type of the alternative
498             -> CoreAlt
499             -> LintM ()
500
501 lintCoreAlt _ alt_ty (DEFAULT, args, rhs) =
502   do { checkL (null args) (mkDefaultArgsMsg args)
503      ; checkAltExpr rhs alt_ty }
504
505 lintCoreAlt scrut_ty alt_ty (LitAlt lit, args, rhs) = 
506   do { checkL (null args) (mkDefaultArgsMsg args)
507      ; checkTys lit_ty scrut_ty (mkBadPatMsg lit_ty scrut_ty)   
508      ; checkAltExpr rhs alt_ty } 
509   where
510     lit_ty = literalType lit
511
512 lintCoreAlt scrut_ty alt_ty alt@(DataAlt con, args, rhs)
513   | isNewTyCon (dataConTyCon con) = addErrL (mkNewTyDataConAltMsg scrut_ty alt)
514   | Just (tycon, tycon_arg_tys) <- splitTyConApp_maybe scrut_ty
515   = addLoc (CaseAlt alt) $  do
516     {   -- First instantiate the universally quantified 
517         -- type variables of the data constructor
518         -- We've already check
519       checkL (tycon == dataConTyCon con) (mkBadConMsg tycon con)
520     ; let con_payload_ty = applyTys (dataConRepType con) tycon_arg_tys
521
522         -- And now bring the new binders into scope
523     ; lintBinders args $ \ args -> do
524     { addLoc (CasePat alt) $ do
525           {    -- Check the pattern
526                  -- Scrutinee type must be a tycon applicn; checked by caller
527                  -- This code is remarkably compact considering what it does!
528                  -- NB: args must be in scope here so that the lintCoreArgs
529                  --     line works. 
530                  -- NB: relies on existential type args coming *after*
531                  --     ordinary type args 
532           ; con_result_ty <- lintCoreArgs con_payload_ty (varsToCoreExprs args)
533           ; checkTys con_result_ty scrut_ty (mkBadPatMsg con_result_ty scrut_ty) 
534           }
535                -- Check the RHS
536     ; checkAltExpr rhs alt_ty } }
537
538   | otherwise   -- Scrut-ty is wrong shape
539   = addErrL (mkBadAltMsg scrut_ty alt)
540 \end{code}
541
542 %************************************************************************
543 %*                                                                      *
544 \subsection[lint-types]{Types}
545 %*                                                                      *
546 %************************************************************************
547
548 \begin{code}
549 -- When we lint binders, we (one at a time and in order):
550 --  1. Lint var types or kinds (possibly substituting)
551 --  2. Add the binder to the in scope set, and if its a coercion var,
552 --     we may extend the substitution to reflect its (possibly) new kind
553 lintBinders :: [Var] -> ([Var] -> LintM a) -> LintM a
554 lintBinders [] linterF = linterF []
555 lintBinders (var:vars) linterF = lintBinder var $ \var' ->
556                                  lintBinders vars $ \ vars' ->
557                                  linterF (var':vars')
558
559 lintBinder :: Var -> (Var -> LintM a) -> LintM a
560 lintBinder var linterF
561   | isTyVar var = lint_ty_bndr
562   | otherwise   = lintIdBndr var linterF
563   where
564     lint_ty_bndr = do { lintTy (tyVarKind var)
565                       ; subst <- getTvSubst
566                       ; let (subst', tv') = substTyVarBndr subst var
567                       ; updateTvSubst subst' (linterF tv') }
568
569 lintIdBndr :: Var -> (Var -> LintM a) -> LintM a
570 -- Do substitution on the type of a binder and add the var with this 
571 -- new type to the in-scope set of the second argument
572 -- ToDo: lint its rules
573 lintIdBndr id linterF 
574   = do  { checkL (not (isUnboxedTupleType (idType id))) 
575                  (mkUnboxedTupleMsg id)
576                 -- No variable can be bound to an unboxed tuple.
577         ; lintAndScopeId id $ \id' -> linterF id'
578         }
579
580 lintAndScopeIds :: [Var] -> ([Var] -> LintM a) -> LintM a
581 lintAndScopeIds ids linterF 
582   = go ids
583   where
584     go []       = linterF []
585     go (id:ids) = do { lintAndScopeId id $ \id ->
586                            lintAndScopeIds ids $ \ids ->
587                            linterF (id:ids) }
588
589 lintAndScopeId :: Var -> (Var -> LintM a) -> LintM a
590 lintAndScopeId id linterF 
591   = do { ty <- lintTy (idType id)
592        ; let id' = Var.setIdType id ty
593        ; addInScopeVars [id'] $ (linterF id')
594        }
595
596 lintTy :: InType -> LintM OutType
597 -- Check the type, and apply the substitution to it
598 -- ToDo: check the kind structure of the type
599 lintTy ty 
600   = do  { ty' <- applySubst ty
601         ; mapM_ checkTyVarInScope (varSetElems (tyVarsOfType ty'))
602         ; return ty' }
603 \end{code}
604
605     
606 %************************************************************************
607 %*                                                                      *
608 \subsection[lint-monad]{The Lint monad}
609 %*                                                                      *
610 %************************************************************************
611
612 \begin{code}
613 newtype LintM a = 
614    LintM { unLintM :: 
615             [LintLocInfo] ->         -- Locations
616             TvSubst ->               -- Current type substitution; we also use this
617                                      -- to keep track of all the variables in scope,
618                                      -- both Ids and TyVars
619             Bag Message ->           -- Error messages so far
620             (Maybe a, Bag Message) } -- Result and error messages (if any)
621
622 {-      Note [Type substitution]
623         ~~~~~~~~~~~~~~~~~~~~~~~~
624 Why do we need a type substitution?  Consider
625         /\(a:*). \(x:a). /\(a:*). id a x
626 This is ill typed, because (renaming variables) it is really
627         /\(a:*). \(x:a). /\(b:*). id b x
628 Hence, when checking an application, we can't naively compare x's type
629 (at its binding site) with its expected type (at a use site).  So we
630 rename type binders as we go, maintaining a substitution.
631
632 The same substitution also supports let-type, current expressed as
633         (/\(a:*). body) ty
634 Here we substitute 'ty' for 'a' in 'body', on the fly.
635 -}
636
637 instance Monad LintM where
638   return x = LintM (\ _   _     errs -> (Just x, errs))
639   fail err = LintM (\ loc subst errs -> (Nothing, addErr subst errs (text err) loc))
640   m >>= k  = LintM (\ loc subst errs -> 
641                        let (res, errs') = unLintM m loc subst errs in
642                          case res of
643                            Just r -> unLintM (k r) loc subst errs'
644                            Nothing -> (Nothing, errs'))
645
646 data LintLocInfo
647   = RhsOf Id            -- The variable bound
648   | LambdaBodyOf Id     -- The lambda-binder
649   | BodyOfLetRec [Id]   -- One of the binders
650   | CaseAlt CoreAlt     -- Case alternative
651   | CasePat CoreAlt     -- *Pattern* of the case alternative
652   | AnExpr CoreExpr     -- Some expression
653   | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
654   | TopLevelBindings
655 \end{code}
656
657                  
658 \begin{code}
659 initL :: LintM a -> Maybe Message {- errors -}
660 initL m
661   = case unLintM m [] emptyTvSubst emptyBag of
662       (_, errs) | isEmptyBag errs -> Nothing
663                 | otherwise       -> Just (vcat (punctuate (text "") (bagToList errs)))
664 \end{code}
665
666 \begin{code}
667 checkL :: Bool -> Message -> LintM ()
668 checkL True  _   = return ()
669 checkL False msg = addErrL msg
670
671 addErrL :: Message -> LintM a
672 addErrL msg = LintM (\ loc subst errs -> (Nothing, addErr subst errs msg loc))
673
674 addErr :: TvSubst -> Bag Message -> Message -> [LintLocInfo] -> Bag Message
675 addErr subst errs_so_far msg locs
676   = ASSERT( notNull locs )
677     errs_so_far `snocBag` mk_msg msg
678   where
679    (loc, cxt1) = dumpLoc (head locs)
680    cxts        = [snd (dumpLoc loc) | loc <- locs]   
681    context     | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1 $$
682                                       ptext SLIT("Substitution:") <+> ppr subst
683                | otherwise          = cxt1
684  
685    mk_msg msg = mkLocMessage (mkSrcSpan loc loc) (context $$ msg)
686
687 addLoc :: LintLocInfo -> LintM a -> LintM a
688 addLoc extra_loc m =
689   LintM (\ loc subst errs -> unLintM m (extra_loc:loc) subst errs)
690
691 addInScopeVars :: [Var] -> LintM a -> LintM a
692 addInScopeVars vars m
693   | null dups
694   = LintM (\ loc subst errs -> unLintM m loc (extendTvInScope subst vars) errs)
695   | otherwise
696   = addErrL (dupVars dups)
697   where
698     (_, dups) = removeDups compare vars 
699
700 updateTvSubst :: TvSubst -> LintM a -> LintM a
701 updateTvSubst subst' m = 
702   LintM (\ loc _ errs -> unLintM m loc subst' errs)
703
704 getTvSubst :: LintM TvSubst
705 getTvSubst = LintM (\ _ subst errs -> (Just subst, errs))
706
707 applySubst :: Type -> LintM Type
708 applySubst ty = do { subst <- getTvSubst; return (substTy subst ty) }
709
710 extendSubstL :: TyVar -> Type -> LintM a -> LintM a
711 extendSubstL tv ty m
712   = LintM (\ loc subst errs -> unLintM m loc (extendTvSubst subst tv ty) errs)
713 \end{code}
714
715 \begin{code}
716 lookupIdInScope :: Id -> LintM Id
717 lookupIdInScope id 
718   | not (mustHaveLocalBinding id)
719   = return id   -- An imported Id
720   | otherwise   
721   = do  { subst <- getTvSubst
722         ; case lookupInScope (getTvInScope subst) id of
723                 Just v  -> return v
724                 Nothing -> do { addErrL out_of_scope
725                               ; return id } }
726   where
727     out_of_scope = ppr id <+> ptext SLIT("is out of scope")
728
729
730 oneTupleDataConId :: Id -- Should not happen
731 oneTupleDataConId = dataConWorkId (tupleCon Boxed 1)
732
733 checkBndrIdInScope :: Var -> Var -> LintM ()
734 checkBndrIdInScope binder id 
735   = checkInScope msg id
736     where
737      msg = ptext SLIT("is out of scope inside info for") <+> 
738            ppr binder
739
740 checkTyVarInScope :: TyVar -> LintM ()
741 checkTyVarInScope tv = checkInScope (ptext SLIT("is out of scope")) tv
742
743 checkInScope :: SDoc -> Var -> LintM ()
744 checkInScope loc_msg var =
745  do { subst <- getTvSubst
746     ; checkL (not (mustHaveLocalBinding var) || (var `isInScope` subst))
747              (hsep [ppr var, loc_msg]) }
748
749 checkTys :: Type -> Type -> Message -> LintM ()
750 -- check ty2 is subtype of ty1 (ie, has same structure but usage
751 -- annotations need only be consistent, not equal)
752 -- Assumes ty1,ty2 are have alrady had the substitution applied
753 checkTys ty1 ty2 msg = checkL (ty1 `coreEqType` ty2) msg
754 \end{code}
755
756 %************************************************************************
757 %*                                                                      *
758 \subsection{Error messages}
759 %*                                                                      *
760 %************************************************************************
761
762 \begin{code}
763 dumpLoc :: LintLocInfo -> (SrcLoc, SDoc)
764
765 dumpLoc (RhsOf v)
766   = (getSrcLoc v, brackets (ptext SLIT("RHS of") <+> pp_binders [v]))
767
768 dumpLoc (LambdaBodyOf b)
769   = (getSrcLoc b, brackets (ptext SLIT("in body of lambda with binder") <+> pp_binder b))
770
771 dumpLoc (BodyOfLetRec [])
772   = (noSrcLoc, brackets (ptext SLIT("In body of a letrec with no binders")))
773
774 dumpLoc (BodyOfLetRec bs@(_:_))
775   = ( getSrcLoc (head bs), brackets (ptext SLIT("in body of letrec with binders") <+> pp_binders bs))
776
777 dumpLoc (AnExpr e)
778   = (noSrcLoc, text "In the expression:" <+> ppr e)
779
780 dumpLoc (CaseAlt (con, args, _))
781   = (noSrcLoc, text "In a case alternative:" <+> parens (ppr con <+> pp_binders args))
782
783 dumpLoc (CasePat (con, args, _))
784   = (noSrcLoc, text "In the pattern of a case alternative:" <+> parens (ppr con <+> pp_binders args))
785
786 dumpLoc (ImportedUnfolding locn)
787   = (locn, brackets (ptext SLIT("in an imported unfolding")))
788 dumpLoc TopLevelBindings
789   = (noSrcLoc, empty)
790
791 pp_binders :: [Var] -> SDoc
792 pp_binders bs = sep (punctuate comma (map pp_binder bs))
793
794 pp_binder :: Var -> SDoc
795 pp_binder b | isId b    = hsep [ppr b, dcolon, ppr (idType b)]
796             | otherwise = hsep [ppr b, dcolon, ppr (tyVarKind b)]
797 \end{code}
798
799 \begin{code}
800 ------------------------------------------------------
801 --      Messages for case expressions
802
803 mkNullAltsMsg :: CoreExpr -> Message
804 mkNullAltsMsg e 
805   = hang (text "Case expression with no alternatives:")
806          4 (ppr e)
807
808 mkDefaultArgsMsg :: [Var] -> Message
809 mkDefaultArgsMsg args 
810   = hang (text "DEFAULT case with binders")
811          4 (ppr args)
812
813 mkCaseAltMsg :: CoreExpr -> Type -> Type -> Message
814 mkCaseAltMsg e ty1 ty2
815   = hang (text "Type of case alternatives not the same as the annotation on case:")
816          4 (vcat [ppr ty1, ppr ty2, ppr e])
817
818 mkScrutMsg :: Id -> Type -> Type -> TvSubst -> Message
819 mkScrutMsg var var_ty scrut_ty subst
820   = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
821           text "Result binder type:" <+> ppr var_ty,--(idType var),
822           text "Scrutinee type:" <+> ppr scrut_ty,
823      hsep [ptext SLIT("Current TV subst"), ppr subst]]
824
825 mkNonDefltMsg, mkNonIncreasingAltsMsg :: CoreExpr -> Message
826 mkNonDefltMsg e
827   = hang (text "Case expression with DEFAULT not at the beginnning") 4 (ppr e)
828 mkNonIncreasingAltsMsg e
829   = hang (text "Case expression with badly-ordered alternatives") 4 (ppr e)
830
831 nonExhaustiveAltsMsg :: CoreExpr -> Message
832 nonExhaustiveAltsMsg e
833   = hang (text "Case expression with non-exhaustive alternatives") 4 (ppr e)
834
835 mkBadConMsg :: TyCon -> DataCon -> Message
836 mkBadConMsg tycon datacon
837   = vcat [
838         text "In a case alternative, data constructor isn't in scrutinee type:",
839         text "Scrutinee type constructor:" <+> ppr tycon,
840         text "Data con:" <+> ppr datacon
841     ]
842
843 mkBadPatMsg :: Type -> Type -> Message
844 mkBadPatMsg con_result_ty scrut_ty
845   = vcat [
846         text "In a case alternative, pattern result type doesn't match scrutinee type:",
847         text "Pattern result type:" <+> ppr con_result_ty,
848         text "Scrutinee type:" <+> ppr scrut_ty
849     ]
850
851 mkBadAltMsg :: Type -> CoreAlt -> Message
852 mkBadAltMsg scrut_ty alt
853   = vcat [ text "Data alternative when scrutinee is not a tycon application",
854            text "Scrutinee type:" <+> ppr scrut_ty,
855            text "Alternative:" <+> pprCoreAlt alt ]
856
857 mkNewTyDataConAltMsg :: Type -> CoreAlt -> Message
858 mkNewTyDataConAltMsg scrut_ty alt
859   = vcat [ text "Data alternative for newtype datacon",
860            text "Scrutinee type:" <+> ppr scrut_ty,
861            text "Alternative:" <+> pprCoreAlt alt ]
862
863
864 ------------------------------------------------------
865 --      Other error messages
866
867 mkAppMsg :: Type -> Type -> CoreExpr -> Message
868 mkAppMsg fun_ty arg_ty arg
869   = vcat [ptext SLIT("Argument value doesn't match argument type:"),
870               hang (ptext SLIT("Fun type:")) 4 (ppr fun_ty),
871               hang (ptext SLIT("Arg type:")) 4 (ppr arg_ty),
872               hang (ptext SLIT("Arg:")) 4 (ppr arg)]
873
874 mkNonFunAppMsg :: Type -> Type -> CoreExpr -> Message
875 mkNonFunAppMsg fun_ty arg_ty arg
876   = vcat [ptext SLIT("Non-function type in function position"),
877               hang (ptext SLIT("Fun type:")) 4 (ppr fun_ty),
878               hang (ptext SLIT("Arg type:")) 4 (ppr arg_ty),
879               hang (ptext SLIT("Arg:")) 4 (ppr arg)]
880
881 mkKindErrMsg :: TyVar -> Type -> Message
882 mkKindErrMsg tyvar arg_ty
883   = vcat [ptext SLIT("Kinds don't match in type application:"),
884           hang (ptext SLIT("Type variable:"))
885                  4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
886           hang (ptext SLIT("Arg type:"))   
887                  4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
888
889 mkTyAppMsg :: Type -> Type -> Message
890 mkTyAppMsg ty arg_ty
891   = vcat [text "Illegal type application:",
892               hang (ptext SLIT("Exp type:"))
893                  4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
894               hang (ptext SLIT("Arg type:"))   
895                  4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
896
897 mkRhsMsg :: Id -> Type -> Message
898 mkRhsMsg binder ty
899   = vcat
900     [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
901             ppr binder],
902      hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
903      hsep [ptext SLIT("Rhs type:"), ppr ty]]
904
905 mkRhsPrimMsg :: Id -> CoreExpr -> Message
906 mkRhsPrimMsg binder _rhs
907   = vcat [hsep [ptext SLIT("The type of this binder is primitive:"),
908                      ppr binder],
909               hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]
910              ]
911
912 mkStrictMsg :: Id -> Message
913 mkStrictMsg binder
914   = vcat [hsep [ptext SLIT("Recursive or top-level binder has strict demand info:"),
915                      ppr binder],
916               hsep [ptext SLIT("Binder's demand info:"), ppr (idNewDemandInfo binder)]
917              ]
918
919 mkArityMsg :: Id -> Message
920 mkArityMsg binder
921   = vcat [hsep [ptext SLIT("Demand type has "),
922                      ppr (dmdTypeDepth dmd_ty),
923                      ptext SLIT(" arguments, rhs has "),
924                      ppr (idArity binder),
925                      ptext SLIT("arguments, "),
926                      ppr binder],
927               hsep [ptext SLIT("Binder's strictness signature:"), ppr dmd_ty]
928
929          ]
930            where (StrictSig dmd_ty) = idNewStrictness binder
931
932 mkUnboxedTupleMsg :: Id -> Message
933 mkUnboxedTupleMsg binder
934   = vcat [hsep [ptext SLIT("A variable has unboxed tuple type:"), ppr binder],
935           hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]]
936
937 mkCastErr :: Type -> Type -> Message
938 mkCastErr from_ty expr_ty
939   = vcat [ptext SLIT("From-type of Cast differs from type of enclosed expression"),
940           ptext SLIT("From-type:") <+> ppr from_ty,
941           ptext SLIT("Type of enclosed expr:") <+> ppr expr_ty
942     ]
943
944 dupVars :: [[Var]] -> Message
945 dupVars vars
946   = hang (ptext SLIT("Duplicate variables brought into scope"))
947        2 (ppr vars)
948
949 mkStrangeTyMsg :: CoreExpr -> Message
950 mkStrangeTyMsg e
951   = ptext SLIT("Type where expression expected:") <+> ppr e
952 \end{code}