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