3 % (c) The University of Glasgow 2006
4 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
7 A ``lint'' pass to check for Core correctness
10 module CoreLint ( lintCoreBindings, lintUnfolding ) where
12 #include "HsVersions.h"
46 %************************************************************************
48 \subsection[lintCoreBindings]{@lintCoreBindings@: Top-level interface}
50 %************************************************************************
52 Checks that a set of core bindings is well-formed. The PprStyle and String
53 just control what we print in the event of an error. The Bool value
54 indicates whether we have done any specialisation yet (in which case we do
59 (b) Out-of-scope type variables
60 (c) Out-of-scope local variables
63 If we have done specialisation the we check that there are
64 (a) No top-level bindings of primitive (unboxed type)
69 -- Things are *not* OK if:
71 -- * Unsaturated type app before specialisation has been done;
73 -- * Oversaturated type app after specialisation (eta reduction
74 -- may well be happening...);
77 Note [Linting type lets]
78 ~~~~~~~~~~~~~~~~~~~~~~~~
79 In the desugarer, it's very very convenient to be able to say (in effect)
80 let a = Type Int in <body>
81 That is, use a type let. See Note [Type let] in CoreSyn.
83 However, when linting <body> we need to remember that a=Int, else we might
84 reject a correct program. So we carry a type substitution (in this example
85 [a -> Int]) and apply this substitution before comparing types. The functin
86 lintInTy :: Type -> LintM Type
87 returns a substituted type; that's the only reason it returns anything.
89 When we encounter a binder (like x::a) we must apply the substitution
90 to the type of the binding variable. lintBinders does this.
92 For Ids, the type-substituted Id is added to the in_scope set (which
93 itself is part of the TvSubst we are carrying down), and when we
94 find an occurence of an Id, we fetch it from the in-scope set.
98 lintCoreBindings :: [CoreBind] -> (Bag Message, Bag Message)
99 -- Returns (warnings, errors)
100 lintCoreBindings binds
101 = initL (lint_binds binds)
103 -- Put all the top-level binders in scope at the start
104 -- This is because transformation rules can bring something
105 -- into use 'unexpectedly'
106 lint_binds binds = addLoc TopLevelBindings $
107 addInScopeVars (bindersOfBinds binds) $
110 lint_bind (Rec prs) = mapM_ (lintSingleBinding TopLevel Recursive) prs
111 lint_bind (NonRec bndr rhs) = lintSingleBinding TopLevel NonRecursive (bndr,rhs)
114 %************************************************************************
116 \subsection[lintUnfolding]{lintUnfolding}
118 %************************************************************************
120 We use this to check all unfoldings that come in from interfaces
121 (it is very painful to catch errors otherwise):
124 lintUnfolding :: SrcLoc
125 -> [Var] -- Treat these as in scope
127 -> Maybe Message -- Nothing => OK
129 lintUnfolding locn vars expr
130 | isEmptyBag errs = Nothing
131 | otherwise = Just (pprMessageBag errs)
133 (_warns, errs) = initL (addLoc (ImportedUnfolding locn) $
134 addInScopeVars vars $
138 %************************************************************************
140 \subsection[lintCoreBinding]{lintCoreBinding}
142 %************************************************************************
144 Check a core binding, returning the list of variables bound.
147 lintSingleBinding :: TopLevelFlag -> RecFlag -> (Id, CoreExpr) -> LintM ()
148 lintSingleBinding top_lvl_flag rec_flag (binder,rhs)
149 = addLoc (RhsOf binder) $
151 do { ty <- lintCoreExpr rhs
152 ; lintBinder binder -- Check match to RHS type
153 ; binder_ty <- applySubst binder_ty
154 ; checkTys binder_ty ty (mkRhsMsg binder ty)
155 -- Check (not isUnLiftedType) (also checks for bogus unboxed tuples)
156 ; checkL (not (isUnLiftedType binder_ty)
157 || (isNonRec rec_flag && exprOkForSpeculation rhs))
158 (mkRhsPrimMsg binder rhs)
159 -- Check that if the binder is top-level or recursive, it's not demanded
160 ; checkL (not (isStrictId binder)
161 || (isNonRec rec_flag && not (isTopLevel top_lvl_flag)))
163 -- Check whether binder's specialisations contain any out-of-scope variables
164 ; mapM_ (checkBndrIdInScope binder) bndr_vars
166 ; when (isNonRuleLoopBreaker (idOccInfo binder) && isInlinePragma (idInlinePragma binder))
167 (addWarnL (ptext (sLit "INLINE binder is (non-rule) loop breaker:") <+> ppr binder))
168 -- Only non-rule loop breakers inhibit inlining
170 -- Check whether arity and demand type are consistent (only if demand analysis
172 ; checkL (case maybeDmdTy of
173 Just (StrictSig dmd_ty) -> idArity binder >= dmdTypeDepth dmd_ty || exprIsTrivial rhs
175 (mkArityMsg binder) }
177 -- We should check the unfolding, if any, but this is tricky because
178 -- the unfolding is a SimplifiableCoreExpr. Give up for now.
180 binder_ty = idType binder
181 maybeDmdTy = idStrictness_maybe binder
182 bndr_vars = varSetElems (idFreeVars binder)
183 lintBinder var | isId var = lintIdBndr var $ \_ -> (return ())
184 | otherwise = return ()
187 %************************************************************************
189 \subsection[lintCoreExpr]{lintCoreExpr}
191 %************************************************************************
194 type InType = Type -- Substitution not yet applied
198 type OutType = Type -- Substitution has been applied to this
200 type OutTyVar = TyVar
201 type OutCoVar = CoVar
203 lintCoreExpr :: CoreExpr -> LintM OutType
204 -- The returned type has the substitution from the monad
205 -- already applied to it:
206 -- lintCoreExpr e subst = exprType (subst e)
208 -- The returned "type" can be a kind, if the expression is (Type ty)
210 lintCoreExpr (Var var)
211 = do { checkL (not (var == oneTupleDataConId))
212 (ptext (sLit "Illegal one-tuple"))
215 ; var' <- lookupIdInScope var
216 ; return (idType var') }
218 lintCoreExpr (Lit lit)
219 = return (literalType lit)
221 lintCoreExpr (Cast expr co)
222 = do { expr_ty <- lintCoreExpr expr
223 ; co' <- applySubst co
224 ; (from_ty, to_ty) <- lintCoercion co'
225 ; checkTys from_ty expr_ty (mkCastErr from_ty expr_ty)
228 lintCoreExpr (Note _ expr)
231 lintCoreExpr (Let (NonRec tv (Type ty)) body)
233 = -- See Note [Linting type lets]
234 do { ty' <- addLoc (RhsOf tv) $ lintInTy ty
235 ; lintTyBndr tv $ \ tv' ->
236 addLoc (BodyOfLetRec [tv]) $
237 extendSubstL tv' ty' $ do
239 -- Now extend the substitution so we
240 -- take advantage of it in the body
241 ; lintCoreExpr body } }
244 = do { co <- applySubst ty
245 ; (s1,s2) <- addLoc (RhsOf tv) $ lintCoercion co
246 ; lintTyBndr tv $ \ tv' ->
247 addLoc (BodyOfLetRec [tv]) $ do
248 { let (t1,t2) = coVarKind tv'
249 ; checkTys s1 t1 (mkTyVarLetErr tv ty)
250 ; checkTys s2 t2 (mkTyVarLetErr tv ty)
251 ; lintCoreExpr body } }
254 = failWithL (mkTyVarLetErr tv ty) -- Not quite accurate
256 lintCoreExpr (Let (NonRec bndr rhs) body)
257 = do { lintSingleBinding NotTopLevel NonRecursive (bndr,rhs)
258 ; addLoc (BodyOfLetRec [bndr])
259 (lintAndScopeId bndr $ \_ -> (lintCoreExpr body)) }
261 lintCoreExpr (Let (Rec pairs) body)
262 = lintAndScopeIds bndrs $ \_ ->
263 do { mapM_ (lintSingleBinding NotTopLevel Recursive) pairs
264 ; addLoc (BodyOfLetRec bndrs) (lintCoreExpr body) }
266 bndrs = map fst pairs
268 lintCoreExpr e@(App fun arg)
269 = do { fun_ty <- lintCoreExpr fun
270 ; addLoc (AnExpr e) $
271 lintCoreArg fun_ty arg }
273 lintCoreExpr (Lam var expr)
274 = addLoc (LambdaBodyOf var) $
275 lintBinders [var] $ \[var'] ->
276 do { body_ty <- lintCoreExpr expr
278 return (mkFunTy (idType var') body_ty)
280 return (mkForAllTy var' body_ty)
282 -- The applySubst is needed to apply the subst to var
284 lintCoreExpr e@(Case scrut var alt_ty alts) =
285 -- Check the scrutinee
286 do { scrut_ty <- lintCoreExpr scrut
287 ; alt_ty <- lintInTy alt_ty
288 ; var_ty <- lintInTy (idType var)
290 ; let mb_tc_app = splitTyConApp_maybe (idType var)
295 not (isFamilyTyCon tycon || isAbstractTyCon tycon) &&
296 null (tyConDataCons tycon) ->
297 pprTrace "Lint warning: case binder's type has no constructors" (ppr var <+> ppr (idType var))
298 -- This can legitimately happen for type families
300 _otherwise -> return ()
302 -- Don't use lintIdBndr on var, because unboxed tuple is legitimate
304 ; subst <- getTvSubst
305 ; checkTys var_ty scrut_ty (mkScrutMsg var var_ty scrut_ty subst)
307 -- If the binder is an unboxed tuple type, don't put it in scope
308 ; let scope = if (isUnboxedTupleType (idType var)) then
310 else lintAndScopeId var
312 do { -- Check the alternatives
313 mapM_ (lintCoreAlt scrut_ty alt_ty) alts
314 ; checkCaseAlts e scrut_ty alts
319 lintCoreExpr (Type ty)
320 = do { ty' <- lintInTy ty
321 ; return (typeKind ty') }
324 %************************************************************************
326 \subsection[lintCoreArgs]{lintCoreArgs}
328 %************************************************************************
330 The basic version of these functions checks that the argument is a
331 subtype of the required type, as one would expect.
334 lintCoreArg :: OutType -> CoreArg -> LintM OutType
335 lintCoreArg fun_ty (Type arg_ty)
336 = do { arg_ty' <- applySubst arg_ty
337 ; lintTyApp fun_ty arg_ty' }
339 lintCoreArg fun_ty arg
340 = do { arg_ty <- lintCoreExpr arg
341 ; lintValApp arg fun_ty arg_ty }
344 lintAltBinders :: OutType -- Scrutinee type
345 -> OutType -- Constructor type
346 -> [OutVar] -- Binders
348 lintAltBinders scrut_ty con_ty []
349 = checkTys con_ty scrut_ty (mkBadPatMsg con_ty scrut_ty)
350 lintAltBinders scrut_ty con_ty (bndr:bndrs)
352 = do { con_ty' <- lintTyApp con_ty (mkTyVarTy bndr)
353 ; lintAltBinders scrut_ty con_ty' bndrs }
355 = do { con_ty' <- lintValApp (Var bndr) con_ty (idType bndr)
356 ; lintAltBinders scrut_ty con_ty' bndrs }
359 lintTyApp :: OutType -> OutType -> LintM OutType
360 lintTyApp fun_ty arg_ty
361 | Just (tyvar,body_ty) <- splitForAllTy_maybe fun_ty
362 = do { checkKinds tyvar arg_ty
363 ; if isCoVar tyvar then
364 return body_ty -- Co-vars don't appear in body_ty!
366 return (substTyWith [tyvar] [arg_ty] body_ty) }
368 = failWithL (mkTyAppMsg fun_ty arg_ty)
371 lintValApp :: CoreExpr -> OutType -> OutType -> LintM OutType
372 lintValApp arg fun_ty arg_ty
373 | Just (arg,res) <- splitFunTy_maybe fun_ty
374 = do { checkTys arg arg_ty err1
379 err1 = mkAppMsg fun_ty arg_ty arg
380 err2 = mkNonFunAppMsg fun_ty arg_ty arg
384 checkKinds :: Var -> OutType -> LintM ()
385 -- Both args have had substitution applied
386 checkKinds tyvar arg_ty
387 -- Arg type might be boxed for a function with an uncommitted
388 -- tyvar; notably this is used so that we can give
389 -- error :: forall a:*. String -> a
390 -- and then apply it to both boxed and unboxed types.
391 | isCoVar tyvar = do { (s2,t2) <- lintCoercion arg_ty
392 ; unless (s1 `coreEqType` s2 && t1 `coreEqType` t2)
393 (addErrL (mkCoAppErrMsg tyvar arg_ty)) }
394 | otherwise = do { arg_kind <- lintType arg_ty
395 ; unless (arg_kind `isSubKind` tyvar_kind)
396 (addErrL (mkKindErrMsg tyvar arg_ty)) }
398 tyvar_kind = tyVarKind tyvar
399 (s1,t1) = coVarKind tyvar
401 checkDeadIdOcc :: Id -> LintM ()
402 -- Occurrences of an Id should never be dead....
403 -- except when we are checking a case pattern
405 | isDeadOcc (idOccInfo id)
406 = do { in_case <- inCasePat
408 (ptext (sLit "Occurrence of a dead Id") <+> ppr id) }
414 %************************************************************************
416 \subsection[lintCoreAlts]{lintCoreAlts}
418 %************************************************************************
421 checkCaseAlts :: CoreExpr -> OutType -> [CoreAlt] -> LintM ()
422 -- a) Check that the alts are non-empty
423 -- b1) Check that the DEFAULT comes first, if it exists
424 -- b2) Check that the others are in increasing order
425 -- c) Check that there's a default for infinite types
426 -- NB: Algebraic cases are not necessarily exhaustive, because
427 -- the simplifer correctly eliminates case that can't
431 = addErrL (mkNullAltsMsg e)
433 checkCaseAlts e ty alts =
434 do { checkL (all non_deflt con_alts) (mkNonDefltMsg e)
435 ; checkL (increasing_tag con_alts) (mkNonIncreasingAltsMsg e)
436 ; checkL (isJust maybe_deflt || not is_infinite_ty)
437 (nonExhaustiveAltsMsg e) }
439 (con_alts, maybe_deflt) = findDefault alts
441 -- Check that successive alternatives have increasing tags
442 increasing_tag (alt1 : rest@( alt2 : _)) = alt1 `ltAlt` alt2 && increasing_tag rest
443 increasing_tag _ = True
445 non_deflt (DEFAULT, _, _) = False
448 is_infinite_ty = case splitTyConApp_maybe ty of
450 Just (tycon, _) -> isPrimTyCon tycon
454 checkAltExpr :: CoreExpr -> OutType -> LintM ()
455 checkAltExpr expr ann_ty
456 = do { actual_ty <- lintCoreExpr expr
457 ; checkTys actual_ty ann_ty (mkCaseAltMsg expr actual_ty ann_ty) }
459 lintCoreAlt :: OutType -- Type of scrutinee
460 -> OutType -- Type of the alternative
464 lintCoreAlt _ alt_ty (DEFAULT, args, rhs) =
465 do { checkL (null args) (mkDefaultArgsMsg args)
466 ; checkAltExpr rhs alt_ty }
468 lintCoreAlt scrut_ty alt_ty (LitAlt lit, args, rhs) =
469 do { checkL (null args) (mkDefaultArgsMsg args)
470 ; checkTys lit_ty scrut_ty (mkBadPatMsg lit_ty scrut_ty)
471 ; checkAltExpr rhs alt_ty }
473 lit_ty = literalType lit
475 lintCoreAlt scrut_ty alt_ty alt@(DataAlt con, args, rhs)
476 | isNewTyCon (dataConTyCon con)
477 = addErrL (mkNewTyDataConAltMsg scrut_ty alt)
478 | Just (tycon, tycon_arg_tys) <- splitTyConApp_maybe scrut_ty
479 = addLoc (CaseAlt alt) $ do
480 { -- First instantiate the universally quantified
481 -- type variables of the data constructor
482 -- We've already check
483 checkL (tycon == dataConTyCon con) (mkBadConMsg tycon con)
484 ; let con_payload_ty = applyTys (dataConRepType con) tycon_arg_tys
486 -- And now bring the new binders into scope
487 ; lintBinders args $ \ args' -> do
488 { addLoc (CasePat alt) (lintAltBinders scrut_ty con_payload_ty args')
489 ; checkAltExpr rhs alt_ty } }
491 | otherwise -- Scrut-ty is wrong shape
492 = addErrL (mkBadAltMsg scrut_ty alt)
495 %************************************************************************
497 \subsection[lint-types]{Types}
499 %************************************************************************
502 -- When we lint binders, we (one at a time and in order):
503 -- 1. Lint var types or kinds (possibly substituting)
504 -- 2. Add the binder to the in scope set, and if its a coercion var,
505 -- we may extend the substitution to reflect its (possibly) new kind
506 lintBinders :: [Var] -> ([Var] -> LintM a) -> LintM a
507 lintBinders [] linterF = linterF []
508 lintBinders (var:vars) linterF = lintBinder var $ \var' ->
509 lintBinders vars $ \ vars' ->
512 lintBinder :: Var -> (Var -> LintM a) -> LintM a
513 lintBinder var linterF
514 | isId var = lintIdBndr var linterF
515 | otherwise = lintTyBndr var linterF
517 lintTyBndr :: InTyVar -> (OutTyVar -> LintM a) -> LintM a
518 lintTyBndr tv thing_inside
519 = do { subst <- getTvSubst
520 ; let (subst', tv') = substTyVarBndr subst tv
522 ; updateTvSubst subst' (thing_inside tv') }
524 lintIdBndr :: Id -> (Id -> LintM a) -> LintM a
525 -- Do substitution on the type of a binder and add the var with this
526 -- new type to the in-scope set of the second argument
527 -- ToDo: lint its rules
529 lintIdBndr id linterF
530 = do { checkL (not (isUnboxedTupleType (idType id)))
531 (mkUnboxedTupleMsg id)
532 -- No variable can be bound to an unboxed tuple.
533 ; lintAndScopeId id $ \id' -> linterF id' }
535 lintAndScopeIds :: [Var] -> ([Var] -> LintM a) -> LintM a
536 lintAndScopeIds ids linterF
540 go (id:ids) = lintAndScopeId id $ \id ->
541 lintAndScopeIds ids $ \ids ->
544 lintAndScopeId :: InVar -> (OutVar -> LintM a) -> LintM a
545 lintAndScopeId id linterF
546 = do { ty <- lintInTy (idType id)
547 ; let id' = setIdType id ty
548 ; addInScopeVar id' $ (linterF id') }
552 %************************************************************************
554 \subsection[lint-monad]{The Lint monad}
556 %************************************************************************
559 lintInTy :: InType -> LintM OutType
560 -- Check the type, and apply the substitution to it
561 -- See Note [Linting type lets]
562 -- ToDo: check the kind structure of the type
564 = addLoc (InType ty) $
565 do { ty' <- applySubst ty
570 lintKind :: Kind -> LintM ()
571 -- Check well-formedness of kinds: *, *->*, etc
572 lintKind (TyConApp tc [])
573 | getUnique tc `elem` kindKeys
575 lintKind (FunTy k1 k2)
576 = lintKind k1 >> lintKind k2
578 = addErrL (hang (ptext (sLit "Malformed kind:")) 2 (quotes (ppr kind)))
581 lintTyBndrKind :: OutTyVar -> LintM ()
583 | isCoVar tv = lintCoVarKind tv
584 | otherwise = lintKind (tyVarKind tv)
587 lintCoVarKind :: OutCoVar -> LintM ()
588 -- Check the kind of a coercion binder
590 = do { (ty1,ty2) <- lintSplitCoVar tv
593 ; unless (k1 `eqKind` k2)
594 (addErrL (sep [ ptext (sLit "Kind mis-match in coercion kind of:")
595 , nest 2 (quotes (ppr tv))
599 lintSplitCoVar :: CoVar -> LintM (Type,Type)
601 = case coVarKind_maybe cv of
603 Nothing -> failWithL (sep [ ptext (sLit "Coercion variable with non-equality kind:")
604 , nest 2 (ppr cv <+> dcolon <+> ppr (tyVarKind cv))])
607 lintCoercion :: OutType -> LintM (OutType, OutType)
608 -- Check the kind of a coercion term, returning the kind
609 lintCoercion ty@(TyVarTy tv)
610 = do { checkTyVarInScope tv
611 ; if isCoVar tv then return (coVarKind tv)
612 else return (ty, ty) }
614 lintCoercion ty@(AppTy ty1 ty2)
615 = do { (s1,t1) <- lintCoercion ty1
616 ; (s2,t2) <- lintCoercion ty2
617 ; check_co_app ty (typeKind s1) [s2]
618 ; return (AppTy s1 s2, AppTy t1 t2) }
620 lintCoercion ty@(FunTy ty1 ty2)
621 = do { (s1,t1) <- lintCoercion ty1
622 ; (s2,t2) <- lintCoercion ty2
623 ; check_co_app ty (tyConKind funTyCon) [s1, s2]
624 ; return (FunTy s1 s2, FunTy t1 t2) }
626 lintCoercion ty@(TyConApp tc tys)
627 | Just (ar, desc) <- isCoercionTyCon_maybe tc
628 = do { unless (tys `lengthAtLeast` ar) (badCo ty)
629 ; (s,t) <- lintCoTyConApp ty desc (take ar tys)
630 ; (ss,ts) <- mapAndUnzipM lintCoercion (drop ar tys)
631 ; check_co_app ty (typeKind s) ss
632 ; return (mkAppTys s ss, mkAppTys t ts) }
634 | not (tyConHasKind tc) -- Just something bizarre like SuperKindTyCon
638 = do { (ss,ts) <- mapAndUnzipM lintCoercion tys
639 ; check_co_app ty (tyConKind tc) ss
640 ; return (TyConApp tc ss, TyConApp tc ts) }
642 lintCoercion ty@(PredTy (ClassP cls tys))
643 = do { (ss,ts) <- mapAndUnzipM lintCoercion tys
644 ; check_co_app ty (tyConKind (classTyCon cls)) ss
645 ; return (PredTy (ClassP cls ss), PredTy (ClassP cls ts)) }
647 lintCoercion (PredTy (IParam n p_ty))
648 = do { (s,t) <- lintCoercion p_ty
649 ; return (PredTy (IParam n s), PredTy (IParam n t)) }
651 lintCoercion ty@(PredTy (EqPred {}))
652 = failWithL (badEq ty)
654 lintCoercion (ForAllTy tv ty)
656 = do { (co1, co2) <- lintSplitCoVar tv
657 ; (s1,t1) <- lintCoercion co1
658 ; (s2,t2) <- lintCoercion co2
659 ; (sr,tr) <- lintCoercion ty
660 ; return (mkCoPredTy s1 s2 sr, mkCoPredTy t1 t2 tr) }
663 = do { lintKind (tyVarKind tv)
664 ; (s,t) <- addInScopeVar tv (lintCoercion ty)
665 ; return (ForAllTy tv s, ForAllTy tv t) }
667 badCo :: Coercion -> LintM a
668 badCo co = failWithL (hang (ptext (sLit "Ill-kinded coercion term:")) 2 (ppr co))
671 lintCoTyConApp :: Coercion -> CoTyConDesc -> [Coercion] -> LintM (Type,Type)
672 -- Always called with correct number of coercion arguments
673 -- First arg is just for error message
674 lintCoTyConApp _ CoLeft (co:_) = lintLR fst co
675 lintCoTyConApp _ CoRight (co:_) = lintLR snd co
676 lintCoTyConApp _ CoCsel1 (co:_) = lintCsel fstOf3 co
677 lintCoTyConApp _ CoCsel2 (co:_) = lintCsel sndOf3 co
678 lintCoTyConApp _ CoCselR (co:_) = lintCsel thirdOf3 co
680 lintCoTyConApp _ CoSym (co:_)
681 = do { (ty1,ty2) <- lintCoercion co
684 lintCoTyConApp co CoTrans (co1:co2:_)
685 = do { (ty1a, ty1b) <- lintCoercion co1
686 ; (ty2a, ty2b) <- lintCoercion co2
687 ; checkL (ty1b `coreEqType` ty2a)
688 (hang (ptext (sLit "Trans coercion mis-match:") <+> ppr co)
689 2 (vcat [ppr ty1a, ppr ty1b, ppr ty2a, ppr ty2b]))
690 ; return (ty1a, ty2b) }
692 lintCoTyConApp _ CoInst (co:arg_ty:_)
693 = do { co_tys <- lintCoercion co
694 ; arg_kind <- lintType arg_ty
695 ; case decompInst_maybe co_tys of
696 Just ((tv1,tv2), (ty1,ty2))
697 | arg_kind `isSubKind` tyVarKind tv1
698 -> return (substTyWith [tv1] [arg_ty] ty1,
699 substTyWith [tv2] [arg_ty] ty2)
701 -> failWithL (ptext (sLit "Kind mis-match in inst coercion"))
702 Nothing -> failWithL (ptext (sLit "Bad argument of inst")) }
704 lintCoTyConApp _ (CoAxiom { co_ax_tvs = tvs
705 , co_ax_lhs = lhs_ty, co_ax_rhs = rhs_ty }) cos
706 = do { (tys1, tys2) <- mapAndUnzipM lintCoercion cos
707 ; sequence_ (zipWith checkKinds tvs tys1)
708 ; return (substTyWith tvs tys1 lhs_ty,
709 substTyWith tvs tys2 rhs_ty) }
711 lintCoTyConApp _ CoUnsafe (ty1:ty2:_)
712 = do { _ <- lintType ty1
713 ; _ <- lintType ty2 -- Ignore kinds; it's unsafe!
716 lintCoTyConApp _ _ _ = panic "lintCoTyConApp" -- Called with wrong number of coercion args
719 lintLR :: (forall a. (a,a)->a) -> Coercion -> LintM (Type,Type)
721 = do { (ty1,ty2) <- lintCoercion co
722 ; case decompLR_maybe (ty1,ty2) of
723 Just res -> return (sel res)
724 Nothing -> failWithL (ptext (sLit "Bad argument of left/right")) }
727 lintCsel :: (forall a. (a,a,a)->a) -> Coercion -> LintM (Type,Type)
729 = do { (ty1,ty2) <- lintCoercion co
730 ; case decompCsel_maybe (ty1,ty2) of
731 Just res -> return (sel res)
732 Nothing -> failWithL (ptext (sLit "Bad argument of csel")) }
735 lintType :: OutType -> LintM Kind
736 lintType (TyVarTy tv)
737 = do { checkTyVarInScope tv
738 ; return (tyVarKind tv) }
740 lintType ty@(AppTy t1 t2)
741 = do { k1 <- lintType t1
742 ; lint_ty_app ty k1 [t2] }
744 lintType ty@(FunTy t1 t2)
745 = lint_ty_app ty (tyConKind funTyCon) [t1,t2]
747 lintType ty@(TyConApp tc tys)
749 = lint_ty_app ty (tyConKind tc) tys
751 = failWithL (hang (ptext (sLit "Malformed type:")) 2 (ppr ty))
753 lintType (ForAllTy tv ty)
754 = do { lintTyBndrKind tv
755 ; addInScopeVar tv (lintType ty) }
757 lintType ty@(PredTy (ClassP cls tys))
758 = lint_ty_app ty (tyConKind (classTyCon cls)) tys
760 lintType (PredTy (IParam _ p_ty))
763 lintType ty@(PredTy (EqPred {}))
764 = failWithL (badEq ty)
767 lint_ty_app :: Type -> Kind -> [OutType] -> LintM Kind
769 = do { ks <- mapM lintType tys
770 ; lint_kind_app (ptext (sLit "type") <+> quotes (ppr ty)) k ks }
773 check_co_app :: Coercion -> Kind -> [OutType] -> LintM ()
774 check_co_app ty k tys
775 = do { _ <- lint_kind_app (ptext (sLit "coercion") <+> quotes (ppr ty))
780 lint_kind_app :: SDoc -> Kind -> [Kind] -> LintM Kind
781 lint_kind_app doc kfn ks = go kfn ks
783 fail_msg = vcat [hang (ptext (sLit "Kind application error in")) 2 doc,
784 nest 2 (ptext (sLit "Function kind =") <+> ppr kfn),
785 nest 2 (ptext (sLit "Arg kinds =") <+> ppr ks)]
787 go kfn [] = return kfn
788 go kfn (k:ks) = case splitKindFunTy_maybe kfn of
789 Nothing -> failWithL fail_msg
790 Just (kfa, kfb) -> do { unless (k `isSubKind` kfa)
794 badEq :: Type -> SDoc
795 badEq ty = hang (ptext (sLit "Unexpected equality predicate:"))
799 %************************************************************************
801 \subsection[lint-monad]{The Lint monad}
803 %************************************************************************
808 [LintLocInfo] -> -- Locations
809 TvSubst -> -- Current type substitution; we also use this
810 -- to keep track of all the variables in scope,
811 -- both Ids and TyVars
812 WarnsAndErrs -> -- Error and warning messages so far
813 (Maybe a, WarnsAndErrs) } -- Result and messages (if any)
815 type WarnsAndErrs = (Bag Message, Bag Message)
817 {- Note [Type substitution]
818 ~~~~~~~~~~~~~~~~~~~~~~~~
819 Why do we need a type substitution? Consider
820 /\(a:*). \(x:a). /\(a:*). id a x
821 This is ill typed, because (renaming variables) it is really
822 /\(a:*). \(x:a). /\(b:*). id b x
823 Hence, when checking an application, we can't naively compare x's type
824 (at its binding site) with its expected type (at a use site). So we
825 rename type binders as we go, maintaining a substitution.
827 The same substitution also supports let-type, current expressed as
829 Here we substitute 'ty' for 'a' in 'body', on the fly.
832 instance Monad LintM where
833 return x = LintM (\ _ _ errs -> (Just x, errs))
834 fail err = failWithL (text err)
835 m >>= k = LintM (\ loc subst errs ->
836 let (res, errs') = unLintM m loc subst errs in
838 Just r -> unLintM (k r) loc subst errs'
839 Nothing -> (Nothing, errs'))
842 = RhsOf Id -- The variable bound
843 | LambdaBodyOf Id -- The lambda-binder
844 | BodyOfLetRec [Id] -- One of the binders
845 | CaseAlt CoreAlt -- Case alternative
846 | CasePat CoreAlt -- The *pattern* of the case alternative
847 | AnExpr CoreExpr -- Some expression
848 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
850 | InType Type -- Inside a type
855 initL :: LintM a -> WarnsAndErrs -- Errors and warnings
857 = case unLintM m [] emptyTvSubst (emptyBag, emptyBag) of
862 checkL :: Bool -> Message -> LintM ()
863 checkL True _ = return ()
864 checkL False msg = failWithL msg
866 failWithL :: Message -> LintM a
867 failWithL msg = LintM $ \ loc subst (warns,errs) ->
868 (Nothing, (warns, addMsg subst errs msg loc))
870 addErrL :: Message -> LintM ()
871 addErrL msg = LintM $ \ loc subst (warns,errs) ->
872 (Just (), (warns, addMsg subst errs msg loc))
874 addWarnL :: Message -> LintM ()
875 addWarnL msg = LintM $ \ loc subst (warns,errs) ->
876 (Just (), (addMsg subst warns msg loc, errs))
878 addMsg :: TvSubst -> Bag Message -> Message -> [LintLocInfo] -> Bag Message
879 addMsg subst msgs msg locs
880 = ASSERT( notNull locs )
881 msgs `snocBag` mk_msg msg
883 (loc, cxt1) = dumpLoc (head locs)
884 cxts = [snd (dumpLoc loc) | loc <- locs]
885 context | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1 $$
886 ptext (sLit "Substitution:") <+> ppr subst
889 mk_msg msg = mkLocMessage (mkSrcSpan loc loc) (context $$ msg)
891 addLoc :: LintLocInfo -> LintM a -> LintM a
893 LintM (\ loc subst errs -> unLintM m (extra_loc:loc) subst errs)
895 inCasePat :: LintM Bool -- A slight hack; see the unique call site
896 inCasePat = LintM $ \ loc _ errs -> (Just (is_case_pat loc), errs)
898 is_case_pat (CasePat {} : _) = True
899 is_case_pat _other = False
901 addInScopeVars :: [Var] -> LintM a -> LintM a
902 addInScopeVars vars m
904 = LintM (\ loc subst errs -> unLintM m loc (extendTvInScopeList subst vars) errs)
906 = failWithL (dupVars dups)
908 (_, dups) = removeDups compare vars
910 addInScopeVar :: Var -> LintM a -> LintM a
912 = LintM (\ loc subst errs -> unLintM m loc (extendTvInScope subst var) errs)
914 updateTvSubst :: TvSubst -> LintM a -> LintM a
915 updateTvSubst subst' m =
916 LintM (\ loc _ errs -> unLintM m loc subst' errs)
918 getTvSubst :: LintM TvSubst
919 getTvSubst = LintM (\ _ subst errs -> (Just subst, errs))
921 applySubst :: Type -> LintM Type
922 applySubst ty = do { subst <- getTvSubst; return (substTy subst ty) }
924 extendSubstL :: TyVar -> Type -> LintM a -> LintM a
926 = LintM (\ loc subst errs -> unLintM m loc (extendTvSubst subst tv ty) errs)
930 lookupIdInScope :: Id -> LintM Id
932 | not (mustHaveLocalBinding id)
933 = return id -- An imported Id
935 = do { subst <- getTvSubst
936 ; case lookupInScope (getTvInScope subst) id of
938 Nothing -> do { addErrL out_of_scope
941 out_of_scope = ppr id <+> ptext (sLit "is out of scope")
944 oneTupleDataConId :: Id -- Should not happen
945 oneTupleDataConId = dataConWorkId (tupleCon Boxed 1)
947 checkBndrIdInScope :: Var -> Var -> LintM ()
948 checkBndrIdInScope binder id
949 = checkInScope msg id
951 msg = ptext (sLit "is out of scope inside info for") <+>
954 checkTyVarInScope :: TyVar -> LintM ()
955 checkTyVarInScope tv = checkInScope (ptext (sLit "is out of scope")) tv
957 checkInScope :: SDoc -> Var -> LintM ()
958 checkInScope loc_msg var =
959 do { subst <- getTvSubst
960 ; checkL (not (mustHaveLocalBinding var) || (var `isInScope` subst))
961 (hsep [ppr var, loc_msg]) }
963 checkTys :: OutType -> OutType -> Message -> LintM ()
964 -- check ty2 is subtype of ty1 (ie, has same structure but usage
965 -- annotations need only be consistent, not equal)
966 -- Assumes ty1,ty2 are have alrady had the substitution applied
967 checkTys ty1 ty2 msg = checkL (ty1 `coreEqType` ty2) msg
970 %************************************************************************
972 \subsection{Error messages}
974 %************************************************************************
977 dumpLoc :: LintLocInfo -> (SrcLoc, SDoc)
980 = (getSrcLoc v, brackets (ptext (sLit "RHS of") <+> pp_binders [v]))
982 dumpLoc (LambdaBodyOf b)
983 = (getSrcLoc b, brackets (ptext (sLit "in body of lambda with binder") <+> pp_binder b))
985 dumpLoc (BodyOfLetRec [])
986 = (noSrcLoc, brackets (ptext (sLit "In body of a letrec with no binders")))
988 dumpLoc (BodyOfLetRec bs@(_:_))
989 = ( getSrcLoc (head bs), brackets (ptext (sLit "in body of letrec with binders") <+> pp_binders bs))
992 = (noSrcLoc, text "In the expression:" <+> ppr e)
994 dumpLoc (CaseAlt (con, args, _))
995 = (noSrcLoc, text "In a case alternative:" <+> parens (ppr con <+> pp_binders args))
997 dumpLoc (CasePat (con, args, _))
998 = (noSrcLoc, text "In the pattern of a case alternative:" <+> parens (ppr con <+> pp_binders args))
1000 dumpLoc (ImportedUnfolding locn)
1001 = (locn, brackets (ptext (sLit "in an imported unfolding")))
1002 dumpLoc TopLevelBindings
1005 = (noSrcLoc, text "In the type" <+> quotes (ppr ty))
1007 pp_binders :: [Var] -> SDoc
1008 pp_binders bs = sep (punctuate comma (map pp_binder bs))
1010 pp_binder :: Var -> SDoc
1011 pp_binder b | isId b = hsep [ppr b, dcolon, ppr (idType b)]
1012 | otherwise = hsep [ppr b, dcolon, ppr (tyVarKind b)]
1016 ------------------------------------------------------
1017 -- Messages for case expressions
1019 mkNullAltsMsg :: CoreExpr -> Message
1021 = hang (text "Case expression with no alternatives:")
1024 mkDefaultArgsMsg :: [Var] -> Message
1025 mkDefaultArgsMsg args
1026 = hang (text "DEFAULT case with binders")
1029 mkCaseAltMsg :: CoreExpr -> Type -> Type -> Message
1030 mkCaseAltMsg e ty1 ty2
1031 = hang (text "Type of case alternatives not the same as the annotation on case:")
1032 4 (vcat [ppr ty1, ppr ty2, ppr e])
1034 mkScrutMsg :: Id -> Type -> Type -> TvSubst -> Message
1035 mkScrutMsg var var_ty scrut_ty subst
1036 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
1037 text "Result binder type:" <+> ppr var_ty,--(idType var),
1038 text "Scrutinee type:" <+> ppr scrut_ty,
1039 hsep [ptext (sLit "Current TV subst"), ppr subst]]
1041 mkNonDefltMsg, mkNonIncreasingAltsMsg :: CoreExpr -> Message
1043 = hang (text "Case expression with DEFAULT not at the beginnning") 4 (ppr e)
1044 mkNonIncreasingAltsMsg e
1045 = hang (text "Case expression with badly-ordered alternatives") 4 (ppr e)
1047 nonExhaustiveAltsMsg :: CoreExpr -> Message
1048 nonExhaustiveAltsMsg e
1049 = hang (text "Case expression with non-exhaustive alternatives") 4 (ppr e)
1051 mkBadConMsg :: TyCon -> DataCon -> Message
1052 mkBadConMsg tycon datacon
1054 text "In a case alternative, data constructor isn't in scrutinee type:",
1055 text "Scrutinee type constructor:" <+> ppr tycon,
1056 text "Data con:" <+> ppr datacon
1059 mkBadPatMsg :: Type -> Type -> Message
1060 mkBadPatMsg con_result_ty scrut_ty
1062 text "In a case alternative, pattern result type doesn't match scrutinee type:",
1063 text "Pattern result type:" <+> ppr con_result_ty,
1064 text "Scrutinee type:" <+> ppr scrut_ty
1067 mkBadAltMsg :: Type -> CoreAlt -> Message
1068 mkBadAltMsg scrut_ty alt
1069 = vcat [ text "Data alternative when scrutinee is not a tycon application",
1070 text "Scrutinee type:" <+> ppr scrut_ty,
1071 text "Alternative:" <+> pprCoreAlt alt ]
1073 mkNewTyDataConAltMsg :: Type -> CoreAlt -> Message
1074 mkNewTyDataConAltMsg scrut_ty alt
1075 = vcat [ text "Data alternative for newtype datacon",
1076 text "Scrutinee type:" <+> ppr scrut_ty,
1077 text "Alternative:" <+> pprCoreAlt alt ]
1080 ------------------------------------------------------
1081 -- Other error messages
1083 mkAppMsg :: Type -> Type -> CoreExpr -> Message
1084 mkAppMsg fun_ty arg_ty arg
1085 = vcat [ptext (sLit "Argument value doesn't match argument type:"),
1086 hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
1087 hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
1088 hang (ptext (sLit "Arg:")) 4 (ppr arg)]
1090 mkNonFunAppMsg :: Type -> Type -> CoreExpr -> Message
1091 mkNonFunAppMsg fun_ty arg_ty arg
1092 = vcat [ptext (sLit "Non-function type in function position"),
1093 hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
1094 hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
1095 hang (ptext (sLit "Arg:")) 4 (ppr arg)]
1097 mkTyVarLetErr :: TyVar -> Type -> Message
1098 mkTyVarLetErr tyvar ty
1099 = vcat [ptext (sLit "Bad `let' binding for type or coercion variable:"),
1100 hang (ptext (sLit "Type/coercion variable:"))
1101 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
1102 hang (ptext (sLit "Arg type/coercion:"))
1105 mkKindErrMsg :: TyVar -> Type -> Message
1106 mkKindErrMsg tyvar arg_ty
1107 = vcat [ptext (sLit "Kinds don't match in type application:"),
1108 hang (ptext (sLit "Type variable:"))
1109 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
1110 hang (ptext (sLit "Arg type:"))
1111 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
1113 mkCoAppErrMsg :: TyVar -> Type -> Message
1114 mkCoAppErrMsg tyvar arg_ty
1115 = vcat [ptext (sLit "Kinds don't match in coercion application:"),
1116 hang (ptext (sLit "Coercion variable:"))
1117 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
1118 hang (ptext (sLit "Arg coercion:"))
1119 4 (ppr arg_ty <+> dcolon <+> pprEqPred (coercionKind arg_ty))]
1121 mkTyAppMsg :: Type -> Type -> Message
1122 mkTyAppMsg ty arg_ty
1123 = vcat [text "Illegal type application:",
1124 hang (ptext (sLit "Exp type:"))
1125 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
1126 hang (ptext (sLit "Arg type:"))
1127 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
1129 mkRhsMsg :: Id -> Type -> Message
1132 [hsep [ptext (sLit "The type of this binder doesn't match the type of its RHS:"),
1134 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)],
1135 hsep [ptext (sLit "Rhs type:"), ppr ty]]
1137 mkRhsPrimMsg :: Id -> CoreExpr -> Message
1138 mkRhsPrimMsg binder _rhs
1139 = vcat [hsep [ptext (sLit "The type of this binder is primitive:"),
1141 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)]
1144 mkStrictMsg :: Id -> Message
1146 = vcat [hsep [ptext (sLit "Recursive or top-level binder has strict demand info:"),
1148 hsep [ptext (sLit "Binder's demand info:"), ppr (idDemandInfo binder)]
1151 mkArityMsg :: Id -> Message
1153 = vcat [hsep [ptext (sLit "Demand type has "),
1154 ppr (dmdTypeDepth dmd_ty),
1155 ptext (sLit " arguments, rhs has "),
1156 ppr (idArity binder),
1157 ptext (sLit "arguments, "),
1159 hsep [ptext (sLit "Binder's strictness signature:"), ppr dmd_ty]
1162 where (StrictSig dmd_ty) = idStrictness binder
1164 mkUnboxedTupleMsg :: Id -> Message
1165 mkUnboxedTupleMsg binder
1166 = vcat [hsep [ptext (sLit "A variable has unboxed tuple type:"), ppr binder],
1167 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)]]
1169 mkCastErr :: Type -> Type -> Message
1170 mkCastErr from_ty expr_ty
1171 = vcat [ptext (sLit "From-type of Cast differs from type of enclosed expression"),
1172 ptext (sLit "From-type:") <+> ppr from_ty,
1173 ptext (sLit "Type of enclosed expr:") <+> ppr expr_ty
1176 dupVars :: [[Var]] -> Message
1178 = hang (ptext (sLit "Duplicate variables brought into scope"))