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')
219 lintCoreExpr (Lit lit)
220 = return (literalType lit)
222 lintCoreExpr (Cast expr co)
223 = do { expr_ty <- lintCoreExpr expr
224 ; co' <- applySubst co
225 ; (from_ty, to_ty) <- lintCoercion co'
226 ; checkTys from_ty expr_ty (mkCastErr from_ty expr_ty)
229 lintCoreExpr (Note _ expr)
232 lintCoreExpr (Let (NonRec tv (Type ty)) body)
233 = -- See Note [Type let] in CoreSyn
234 do { checkL (isTyVar tv) (mkKindErrMsg tv ty) -- Not quite accurate
236 ; lintTyBndr tv $ \ tv' ->
237 addLoc (BodyOfLetRec [tv]) $
238 extendSubstL tv' ty' $ do
240 -- Now extend the substitution so we
241 -- take advantage of it in the body
242 ; lintCoreExpr body } }
244 lintCoreExpr (Let (NonRec bndr rhs) body)
245 = do { lintSingleBinding NotTopLevel NonRecursive (bndr,rhs)
246 ; addLoc (BodyOfLetRec [bndr])
247 (lintAndScopeId bndr $ \_ -> (lintCoreExpr body)) }
249 lintCoreExpr (Let (Rec pairs) body)
250 = lintAndScopeIds bndrs $ \_ ->
251 do { mapM_ (lintSingleBinding NotTopLevel Recursive) pairs
252 ; addLoc (BodyOfLetRec bndrs) (lintCoreExpr body) }
254 bndrs = map fst pairs
256 lintCoreExpr e@(App fun arg)
257 = do { fun_ty <- lintCoreExpr fun
258 ; addLoc (AnExpr e) $
259 lintCoreArg fun_ty arg }
261 lintCoreExpr (Lam var expr)
262 = addLoc (LambdaBodyOf var) $
263 lintBinders [var] $ \[var'] ->
264 do { body_ty <- lintCoreExpr expr
266 return (mkFunTy (idType var') body_ty)
268 return (mkForAllTy var' body_ty)
270 -- The applySubst is needed to apply the subst to var
272 lintCoreExpr e@(Case scrut var alt_ty alts) =
273 -- Check the scrutinee
274 do { scrut_ty <- lintCoreExpr scrut
275 ; alt_ty <- lintInTy alt_ty
276 ; var_ty <- lintInTy (idType var)
278 ; let mb_tc_app = splitTyConApp_maybe (idType var)
283 not (isOpenTyCon tycon) &&
284 null (tyConDataCons tycon) ->
285 pprTrace "Lint warning: case binder's type has no constructors" (ppr var <+> ppr (idType var))
286 -- This can legitimately happen for type families
288 _otherwise -> return ()
290 -- Don't use lintIdBndr on var, because unboxed tuple is legitimate
292 ; subst <- getTvSubst
293 ; checkTys var_ty scrut_ty (mkScrutMsg var var_ty scrut_ty subst)
295 -- If the binder is an unboxed tuple type, don't put it in scope
296 ; let scope = if (isUnboxedTupleType (idType var)) then
298 else lintAndScopeId var
300 do { -- Check the alternatives
301 mapM_ (lintCoreAlt scrut_ty alt_ty) alts
302 ; checkCaseAlts e scrut_ty alts
307 lintCoreExpr (Type ty)
308 = do { ty' <- lintInTy ty
309 ; return (typeKind ty') }
312 %************************************************************************
314 \subsection[lintCoreArgs]{lintCoreArgs}
316 %************************************************************************
318 The basic version of these functions checks that the argument is a
319 subtype of the required type, as one would expect.
322 lintCoreArgs :: OutType -> [CoreArg] -> LintM OutType
323 lintCoreArg :: OutType -> CoreArg -> LintM OutType
324 -- First argument has already had substitution applied to it
328 lintCoreArgs ty [] = return ty
329 lintCoreArgs ty (a : args) =
330 do { res <- lintCoreArg ty a
331 ; lintCoreArgs res args }
333 lintCoreArg fun_ty (Type arg_ty)
334 | Just (tyvar,body) <- splitForAllTy_maybe fun_ty
335 = do { arg_ty' <- applySubst arg_ty
336 ; checkKinds tyvar arg_ty'
337 ; if isCoVar tyvar then
338 return body -- Co-vars don't appear in body!
340 return (substTyWith [tyvar] [arg_ty'] body) }
342 = failWithL (mkTyAppMsg fun_ty arg_ty)
344 lintCoreArg fun_ty arg
345 -- Make sure function type matches argument
346 = do { arg_ty <- lintCoreExpr arg
347 ; let err1 = mkAppMsg fun_ty arg_ty arg
348 err2 = mkNonFunAppMsg fun_ty arg_ty arg
349 ; case splitFunTy_maybe fun_ty of
351 do { checkTys arg arg_ty err1
353 _ -> failWithL err2 }
357 checkKinds :: Var -> OutType -> LintM ()
358 -- Both args have had substitution applied
359 checkKinds tyvar arg_ty
360 -- Arg type might be boxed for a function with an uncommitted
361 -- tyvar; notably this is used so that we can give
362 -- error :: forall a:*. String -> a
363 -- and then apply it to both boxed and unboxed types.
364 | isCoVar tyvar = do { (s2,t2) <- lintCoercion arg_ty
365 ; unless (s1 `coreEqType` s2 && t1 `coreEqType` t2)
366 (addErrL (mkCoAppErrMsg tyvar arg_ty)) }
367 | otherwise = do { arg_kind <- lintType arg_ty
368 ; unless (arg_kind `isSubKind` tyvar_kind)
369 (addErrL (mkKindErrMsg tyvar arg_ty)) }
371 tyvar_kind = tyVarKind tyvar
372 (s1,t1) = coVarKind tyvar
374 checkDeadIdOcc :: Id -> LintM ()
375 -- Occurrences of an Id should never be dead....
376 -- except when we are checking a case pattern
378 | isDeadOcc (idOccInfo id)
379 = do { in_case <- inCasePat
381 (ptext (sLit "Occurrence of a dead Id") <+> ppr id) }
387 %************************************************************************
389 \subsection[lintCoreAlts]{lintCoreAlts}
391 %************************************************************************
394 checkCaseAlts :: CoreExpr -> OutType -> [CoreAlt] -> LintM ()
395 -- a) Check that the alts are non-empty
396 -- b1) Check that the DEFAULT comes first, if it exists
397 -- b2) Check that the others are in increasing order
398 -- c) Check that there's a default for infinite types
399 -- NB: Algebraic cases are not necessarily exhaustive, because
400 -- the simplifer correctly eliminates case that can't
404 = addErrL (mkNullAltsMsg e)
406 checkCaseAlts e ty alts =
407 do { checkL (all non_deflt con_alts) (mkNonDefltMsg e)
408 ; checkL (increasing_tag con_alts) (mkNonIncreasingAltsMsg e)
409 ; checkL (isJust maybe_deflt || not is_infinite_ty)
410 (nonExhaustiveAltsMsg e) }
412 (con_alts, maybe_deflt) = findDefault alts
414 -- Check that successive alternatives have increasing tags
415 increasing_tag (alt1 : rest@( alt2 : _)) = alt1 `ltAlt` alt2 && increasing_tag rest
416 increasing_tag _ = True
418 non_deflt (DEFAULT, _, _) = False
421 is_infinite_ty = case splitTyConApp_maybe ty of
423 Just (tycon, _) -> isPrimTyCon tycon
427 checkAltExpr :: CoreExpr -> OutType -> LintM ()
428 checkAltExpr expr ann_ty
429 = do { actual_ty <- lintCoreExpr expr
430 ; checkTys actual_ty ann_ty (mkCaseAltMsg expr actual_ty ann_ty) }
432 lintCoreAlt :: OutType -- Type of scrutinee
433 -> OutType -- Type of the alternative
437 lintCoreAlt _ alt_ty (DEFAULT, args, rhs) =
438 do { checkL (null args) (mkDefaultArgsMsg args)
439 ; checkAltExpr rhs alt_ty }
441 lintCoreAlt scrut_ty alt_ty (LitAlt lit, args, rhs) =
442 do { checkL (null args) (mkDefaultArgsMsg args)
443 ; checkTys lit_ty scrut_ty (mkBadPatMsg lit_ty scrut_ty)
444 ; checkAltExpr rhs alt_ty }
446 lit_ty = literalType lit
448 lintCoreAlt scrut_ty alt_ty alt@(DataAlt con, args, rhs)
449 | isNewTyCon (dataConTyCon con) = addErrL (mkNewTyDataConAltMsg scrut_ty alt)
450 | Just (tycon, tycon_arg_tys) <- splitTyConApp_maybe scrut_ty
451 = addLoc (CaseAlt alt) $ do
452 { -- First instantiate the universally quantified
453 -- type variables of the data constructor
454 -- We've already check
455 checkL (tycon == dataConTyCon con) (mkBadConMsg tycon con)
456 ; let con_payload_ty = applyTys (dataConRepType con) tycon_arg_tys
458 -- And now bring the new binders into scope
459 ; lintBinders args $ \ args -> do
460 { addLoc (CasePat alt) $ do
461 { -- Check the pattern
462 -- Scrutinee type must be a tycon applicn; checked by caller
463 -- This code is remarkably compact considering what it does!
464 -- NB: args must be in scope here so that the lintCoreArgs
466 -- NB: relies on existential type args coming *after*
467 -- ordinary type args
468 ; con_result_ty <- lintCoreArgs con_payload_ty (varsToCoreExprs args)
469 ; checkTys con_result_ty scrut_ty (mkBadPatMsg con_result_ty scrut_ty)
472 ; checkAltExpr rhs alt_ty } }
474 | otherwise -- Scrut-ty is wrong shape
475 = addErrL (mkBadAltMsg scrut_ty alt)
478 %************************************************************************
480 \subsection[lint-types]{Types}
482 %************************************************************************
485 -- When we lint binders, we (one at a time and in order):
486 -- 1. Lint var types or kinds (possibly substituting)
487 -- 2. Add the binder to the in scope set, and if its a coercion var,
488 -- we may extend the substitution to reflect its (possibly) new kind
489 lintBinders :: [Var] -> ([Var] -> LintM a) -> LintM a
490 lintBinders [] linterF = linterF []
491 lintBinders (var:vars) linterF = lintBinder var $ \var' ->
492 lintBinders vars $ \ vars' ->
495 lintBinder :: Var -> (Var -> LintM a) -> LintM a
496 lintBinder var linterF
497 | isId var = lintIdBndr var linterF
498 | otherwise = lintTyBndr var linterF
500 lintTyBndr :: InTyVar -> (OutTyVar -> LintM a) -> LintM a
501 lintTyBndr tv thing_inside
502 = do { subst <- getTvSubst
503 ; let (subst', tv') = substTyVarBndr subst tv
505 ; updateTvSubst subst' (thing_inside tv') }
507 lintIdBndr :: Id -> (Id -> LintM a) -> LintM a
508 -- Do substitution on the type of a binder and add the var with this
509 -- new type to the in-scope set of the second argument
510 -- ToDo: lint its rules
512 lintIdBndr id linterF
513 = do { checkL (not (isUnboxedTupleType (idType id)))
514 (mkUnboxedTupleMsg id)
515 -- No variable can be bound to an unboxed tuple.
516 ; lintAndScopeId id $ \id' -> linterF id' }
518 lintAndScopeIds :: [Var] -> ([Var] -> LintM a) -> LintM a
519 lintAndScopeIds ids linterF
523 go (id:ids) = lintAndScopeId id $ \id ->
524 lintAndScopeIds ids $ \ids ->
527 lintAndScopeId :: InVar -> (OutVar -> LintM a) -> LintM a
528 lintAndScopeId id linterF
529 = do { ty <- lintInTy (idType id)
530 ; let id' = setIdType id ty
531 ; addInScopeVar id' $ (linterF id') }
535 %************************************************************************
537 \subsection[lint-monad]{The Lint monad}
539 %************************************************************************
542 lintInTy :: InType -> LintM OutType
543 -- Check the type, and apply the substitution to it
544 -- See Note [Linting type lets]
545 -- ToDo: check the kind structure of the type
547 = addLoc (InType ty) $
548 do { ty' <- applySubst ty
553 lintKind :: Kind -> LintM ()
554 -- Check well-formedness of kinds: *, *->*, etc
555 lintKind (TyConApp tc [])
556 | getUnique tc `elem` kindKeys
558 lintKind (FunTy k1 k2)
559 = lintKind k1 >> lintKind k2
561 = addErrL (hang (ptext (sLit "Malformed kind:")) 2 (quotes (ppr kind)))
564 lintTyBndrKind :: OutTyVar -> LintM ()
566 | isCoVar tv = lintCoVarKind tv
567 | otherwise = lintKind (tyVarKind tv)
570 lintCoVarKind :: OutCoVar -> LintM ()
571 -- Check the kind of a coercion binder
573 = do { (ty1,ty2) <- lintSplitCoVar tv
576 ; unless (k1 `eqKind` k2)
577 (addErrL (sep [ ptext (sLit "Kind mis-match in coercion kind of:")
578 , nest 2 (quotes (ppr tv))
582 lintSplitCoVar :: CoVar -> LintM (Type,Type)
584 = case coVarKind_maybe cv of
586 Nothing -> failWithL (sep [ ptext (sLit "Coercion variable with non-equality kind:")
587 , nest 2 (ppr cv <+> dcolon <+> ppr (tyVarKind cv))])
590 lintCoercion :: OutType -> LintM (OutType, OutType)
591 -- Check the kind of a coercion term, returning the kind
592 lintCoercion ty@(TyVarTy tv)
593 = do { checkTyVarInScope tv
594 ; if isCoVar tv then return (coVarKind tv)
595 else return (ty, ty) }
597 lintCoercion ty@(AppTy ty1 ty2)
598 = do { (s1,t1) <- lintCoercion ty1
599 ; (s2,t2) <- lintCoercion ty2
600 ; check_co_app ty (typeKind s1) [s2]
601 ; return (AppTy s1 s2, AppTy t1 t2) }
603 lintCoercion ty@(FunTy ty1 ty2)
604 = do { (s1,t1) <- lintCoercion ty1
605 ; (s2,t2) <- lintCoercion ty2
606 ; check_co_app ty (tyConKind funTyCon) [s1, s2]
607 ; return (FunTy s1 s2, FunTy t1 t2) }
609 lintCoercion ty@(TyConApp tc tys)
610 | Just (ar, desc) <- isCoercionTyCon_maybe tc
611 = do { unless (tys `lengthAtLeast` ar) (badCo ty)
612 ; (s,t) <- lintCoTyConApp ty desc (take ar tys)
613 ; (ss,ts) <- mapAndUnzipM lintCoercion (drop ar tys)
614 ; check_co_app ty (typeKind s) ss
615 ; return (mkAppTys s ss, mkAppTys t ts) }
617 | not (tyConHasKind tc) -- Just something bizarre like SuperKindTyCon
621 = do { (ss,ts) <- mapAndUnzipM lintCoercion tys
622 ; check_co_app ty (tyConKind tc) ss
623 ; return (TyConApp tc ss, TyConApp tc ts) }
625 lintCoercion ty@(PredTy (ClassP cls tys))
626 = do { (ss,ts) <- mapAndUnzipM lintCoercion tys
627 ; check_co_app ty (tyConKind (classTyCon cls)) ss
628 ; return (PredTy (ClassP cls ss), PredTy (ClassP cls ts)) }
630 lintCoercion (PredTy (IParam n p_ty))
631 = do { (s,t) <- lintCoercion p_ty
632 ; return (PredTy (IParam n s), PredTy (IParam n t)) }
634 lintCoercion ty@(PredTy (EqPred {}))
635 = failWithL (badEq ty)
637 lintCoercion (ForAllTy tv ty)
639 = do { (co1, co2) <- lintSplitCoVar tv
640 ; (s1,t1) <- lintCoercion co1
641 ; (s2,t2) <- lintCoercion co2
642 ; (sr,tr) <- lintCoercion ty
643 ; return (mkCoPredTy s1 s2 sr, mkCoPredTy t1 t2 tr) }
646 = do { lintKind (tyVarKind tv)
647 ; (s,t) <- addInScopeVar tv (lintCoercion ty)
648 ; return (ForAllTy tv s, ForAllTy tv t) }
650 badCo :: Coercion -> LintM a
651 badCo co = failWithL (hang (ptext (sLit "Ill-kinded coercion term:")) 2 (ppr co))
654 lintCoTyConApp :: Coercion -> CoTyConDesc -> [Coercion] -> LintM (Type,Type)
655 -- Always called with correct number of coercion arguments
656 -- First arg is just for error message
657 lintCoTyConApp _ CoLeft (co:_) = lintLR fst co
658 lintCoTyConApp _ CoRight (co:_) = lintLR snd co
659 lintCoTyConApp _ CoCsel1 (co:_) = lintCsel fstOf3 co
660 lintCoTyConApp _ CoCsel2 (co:_) = lintCsel sndOf3 co
661 lintCoTyConApp _ CoCselR (co:_) = lintCsel thirdOf3 co
663 lintCoTyConApp _ CoSym (co:_)
664 = do { (ty1,ty2) <- lintCoercion co
667 lintCoTyConApp co CoTrans (co1:co2:_)
668 = do { (ty1a, ty1b) <- lintCoercion co1
669 ; (ty2a, ty2b) <- lintCoercion co2
670 ; checkL (ty1b `coreEqType` ty2a)
671 (hang (ptext (sLit "Trans coercion mis-match:") <+> ppr co)
672 2 (vcat [ppr ty1a, ppr ty1b, ppr ty2a, ppr ty2b]))
673 ; return (ty1a, ty2b) }
675 lintCoTyConApp _ CoInst (co:arg_ty:_)
676 = do { co_tys <- lintCoercion co
677 ; arg_kind <- lintType arg_ty
678 ; case decompInst_maybe co_tys of
679 Just ((tv1,tv2), (ty1,ty2))
680 | arg_kind `isSubKind` tyVarKind tv1
681 -> return (substTyWith [tv1] [arg_ty] ty1,
682 substTyWith [tv2] [arg_ty] ty2)
684 -> failWithL (ptext (sLit "Kind mis-match in inst coercion"))
685 Nothing -> failWithL (ptext (sLit "Bad argument of inst")) }
687 lintCoTyConApp _ (CoAxiom { co_ax_tvs = tvs
688 , co_ax_lhs = lhs_ty, co_ax_rhs = rhs_ty }) cos
689 = do { (tys1, tys2) <- mapAndUnzipM lintCoercion cos
690 ; sequence_ (zipWith checkKinds tvs tys1)
691 ; return (substTyWith tvs tys1 lhs_ty,
692 substTyWith tvs tys2 rhs_ty) }
694 lintCoTyConApp _ CoUnsafe (ty1:ty2:_)
695 = do { _ <- lintType ty1
696 ; _ <- lintType ty2 -- Ignore kinds; it's unsafe!
699 lintCoTyConApp _ _ _ = panic "lintCoTyConApp" -- Called with wrong number of coercion args
702 lintLR :: (forall a. (a,a)->a) -> Coercion -> LintM (Type,Type)
704 = do { (ty1,ty2) <- lintCoercion co
705 ; case decompLR_maybe (ty1,ty2) of
706 Just res -> return (sel res)
707 Nothing -> failWithL (ptext (sLit "Bad argument of left/right")) }
710 lintCsel :: (forall a. (a,a,a)->a) -> Coercion -> LintM (Type,Type)
712 = do { (ty1,ty2) <- lintCoercion co
713 ; case decompCsel_maybe (ty1,ty2) of
714 Just res -> return (sel res)
715 Nothing -> failWithL (ptext (sLit "Bad argument of csel")) }
718 lintType :: OutType -> LintM Kind
719 lintType (TyVarTy tv)
720 = do { checkTyVarInScope tv
721 ; return (tyVarKind tv) }
723 lintType ty@(AppTy t1 t2)
724 = do { k1 <- lintType t1
725 ; lint_ty_app ty k1 [t2] }
727 lintType ty@(FunTy t1 t2)
728 = lint_ty_app ty (tyConKind funTyCon) [t1,t2]
730 lintType ty@(TyConApp tc tys)
732 = lint_ty_app ty (tyConKind tc) tys
734 = failWithL (hang (ptext (sLit "Malformed type:")) 2 (ppr ty))
736 lintType (ForAllTy tv ty)
737 = do { lintTyBndrKind tv
738 ; addInScopeVar tv (lintType ty) }
740 lintType ty@(PredTy (ClassP cls tys))
741 = lint_ty_app ty (tyConKind (classTyCon cls)) tys
743 lintType (PredTy (IParam _ p_ty))
746 lintType ty@(PredTy (EqPred {}))
747 = failWithL (badEq ty)
750 lint_ty_app :: Type -> Kind -> [OutType] -> LintM Kind
752 = do { ks <- mapM lintType tys
753 ; lint_kind_app (ptext (sLit "type") <+> quotes (ppr ty)) k ks }
756 check_co_app :: Coercion -> Kind -> [OutType] -> LintM ()
757 check_co_app ty k tys
758 = do { _ <- lint_kind_app (ptext (sLit "coercion") <+> quotes (ppr ty))
763 lint_kind_app :: SDoc -> Kind -> [Kind] -> LintM Kind
764 lint_kind_app doc kfn ks = go kfn ks
766 fail_msg = vcat [hang (ptext (sLit "Kind application error in")) 2 doc,
767 nest 2 (ptext (sLit "Function kind =") <+> ppr kfn),
768 nest 2 (ptext (sLit "Arg kinds =") <+> ppr ks)]
770 go kfn [] = return kfn
771 go kfn (k:ks) = case splitKindFunTy_maybe kfn of
772 Nothing -> failWithL fail_msg
773 Just (kfa, kfb) -> do { unless (k `isSubKind` kfa)
777 badEq :: Type -> SDoc
778 badEq ty = hang (ptext (sLit "Unexpected equality predicate:"))
782 %************************************************************************
784 \subsection[lint-monad]{The Lint monad}
786 %************************************************************************
791 [LintLocInfo] -> -- Locations
792 TvSubst -> -- Current type substitution; we also use this
793 -- to keep track of all the variables in scope,
794 -- both Ids and TyVars
795 WarnsAndErrs -> -- Error and warning messages so far
796 (Maybe a, WarnsAndErrs) } -- Result and messages (if any)
798 type WarnsAndErrs = (Bag Message, Bag Message)
800 {- Note [Type substitution]
801 ~~~~~~~~~~~~~~~~~~~~~~~~
802 Why do we need a type substitution? Consider
803 /\(a:*). \(x:a). /\(a:*). id a x
804 This is ill typed, because (renaming variables) it is really
805 /\(a:*). \(x:a). /\(b:*). id b x
806 Hence, when checking an application, we can't naively compare x's type
807 (at its binding site) with its expected type (at a use site). So we
808 rename type binders as we go, maintaining a substitution.
810 The same substitution also supports let-type, current expressed as
812 Here we substitute 'ty' for 'a' in 'body', on the fly.
815 instance Monad LintM where
816 return x = LintM (\ _ _ errs -> (Just x, errs))
817 fail err = failWithL (text err)
818 m >>= k = LintM (\ loc subst errs ->
819 let (res, errs') = unLintM m loc subst errs in
821 Just r -> unLintM (k r) loc subst errs'
822 Nothing -> (Nothing, errs'))
825 = RhsOf Id -- The variable bound
826 | LambdaBodyOf Id -- The lambda-binder
827 | BodyOfLetRec [Id] -- One of the binders
828 | CaseAlt CoreAlt -- Case alternative
829 | CasePat CoreAlt -- The *pattern* of the case alternative
830 | AnExpr CoreExpr -- Some expression
831 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
833 | InType Type -- Inside a type
838 initL :: LintM a -> WarnsAndErrs -- Errors and warnings
840 = case unLintM m [] emptyTvSubst (emptyBag, emptyBag) of
845 checkL :: Bool -> Message -> LintM ()
846 checkL True _ = return ()
847 checkL False msg = failWithL msg
849 failWithL :: Message -> LintM a
850 failWithL msg = LintM $ \ loc subst (warns,errs) ->
851 (Nothing, (warns, addMsg subst errs msg loc))
853 addErrL :: Message -> LintM ()
854 addErrL msg = LintM $ \ loc subst (warns,errs) ->
855 (Just (), (warns, addMsg subst errs msg loc))
857 addWarnL :: Message -> LintM ()
858 addWarnL msg = LintM $ \ loc subst (warns,errs) ->
859 (Just (), (addMsg subst warns msg loc, errs))
861 addMsg :: TvSubst -> Bag Message -> Message -> [LintLocInfo] -> Bag Message
862 addMsg subst msgs msg locs
863 = ASSERT( notNull locs )
864 msgs `snocBag` mk_msg msg
866 (loc, cxt1) = dumpLoc (head locs)
867 cxts = [snd (dumpLoc loc) | loc <- locs]
868 context | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1 $$
869 ptext (sLit "Substitution:") <+> ppr subst
872 mk_msg msg = mkLocMessage (mkSrcSpan loc loc) (context $$ msg)
874 addLoc :: LintLocInfo -> LintM a -> LintM a
876 LintM (\ loc subst errs -> unLintM m (extra_loc:loc) subst errs)
878 inCasePat :: LintM Bool -- A slight hack; see the unique call site
879 inCasePat = LintM $ \ loc _ errs -> (Just (is_case_pat loc), errs)
881 is_case_pat (CasePat {} : _) = True
882 is_case_pat _other = False
884 addInScopeVars :: [Var] -> LintM a -> LintM a
885 addInScopeVars vars m
887 = LintM (\ loc subst errs -> unLintM m loc (extendTvInScopeList subst vars) errs)
889 = failWithL (dupVars dups)
891 (_, dups) = removeDups compare vars
893 addInScopeVar :: Var -> LintM a -> LintM a
895 = LintM (\ loc subst errs -> unLintM m loc (extendTvInScope subst var) errs)
897 updateTvSubst :: TvSubst -> LintM a -> LintM a
898 updateTvSubst subst' m =
899 LintM (\ loc _ errs -> unLintM m loc subst' errs)
901 getTvSubst :: LintM TvSubst
902 getTvSubst = LintM (\ _ subst errs -> (Just subst, errs))
904 applySubst :: Type -> LintM Type
905 applySubst ty = do { subst <- getTvSubst; return (substTy subst ty) }
907 extendSubstL :: TyVar -> Type -> LintM a -> LintM a
909 = LintM (\ loc subst errs -> unLintM m loc (extendTvSubst subst tv ty) errs)
913 lookupIdInScope :: Id -> LintM Id
915 | not (mustHaveLocalBinding id)
916 = return id -- An imported Id
918 = do { subst <- getTvSubst
919 ; case lookupInScope (getTvInScope subst) id of
921 Nothing -> do { addErrL out_of_scope
924 out_of_scope = ppr id <+> ptext (sLit "is out of scope")
927 oneTupleDataConId :: Id -- Should not happen
928 oneTupleDataConId = dataConWorkId (tupleCon Boxed 1)
930 checkBndrIdInScope :: Var -> Var -> LintM ()
931 checkBndrIdInScope binder id
932 = checkInScope msg id
934 msg = ptext (sLit "is out of scope inside info for") <+>
937 checkTyVarInScope :: TyVar -> LintM ()
938 checkTyVarInScope tv = checkInScope (ptext (sLit "is out of scope")) tv
940 checkInScope :: SDoc -> Var -> LintM ()
941 checkInScope loc_msg var =
942 do { subst <- getTvSubst
943 ; checkL (not (mustHaveLocalBinding var) || (var `isInScope` subst))
944 (hsep [ppr var, loc_msg]) }
946 checkTys :: Type -> Type -> Message -> LintM ()
947 -- check ty2 is subtype of ty1 (ie, has same structure but usage
948 -- annotations need only be consistent, not equal)
949 -- Assumes ty1,ty2 are have alrady had the substitution applied
950 checkTys ty1 ty2 msg = checkL (ty1 `coreEqType` ty2) msg
953 %************************************************************************
955 \subsection{Error messages}
957 %************************************************************************
960 dumpLoc :: LintLocInfo -> (SrcLoc, SDoc)
963 = (getSrcLoc v, brackets (ptext (sLit "RHS of") <+> pp_binders [v]))
965 dumpLoc (LambdaBodyOf b)
966 = (getSrcLoc b, brackets (ptext (sLit "in body of lambda with binder") <+> pp_binder b))
968 dumpLoc (BodyOfLetRec [])
969 = (noSrcLoc, brackets (ptext (sLit "In body of a letrec with no binders")))
971 dumpLoc (BodyOfLetRec bs@(_:_))
972 = ( getSrcLoc (head bs), brackets (ptext (sLit "in body of letrec with binders") <+> pp_binders bs))
975 = (noSrcLoc, text "In the expression:" <+> ppr e)
977 dumpLoc (CaseAlt (con, args, _))
978 = (noSrcLoc, text "In a case alternative:" <+> parens (ppr con <+> pp_binders args))
980 dumpLoc (CasePat (con, args, _))
981 = (noSrcLoc, text "In the pattern of a case alternative:" <+> parens (ppr con <+> pp_binders args))
983 dumpLoc (ImportedUnfolding locn)
984 = (locn, brackets (ptext (sLit "in an imported unfolding")))
985 dumpLoc TopLevelBindings
988 = (noSrcLoc, text "In the type" <+> quotes (ppr ty))
990 pp_binders :: [Var] -> SDoc
991 pp_binders bs = sep (punctuate comma (map pp_binder bs))
993 pp_binder :: Var -> SDoc
994 pp_binder b | isId b = hsep [ppr b, dcolon, ppr (idType b)]
995 | otherwise = hsep [ppr b, dcolon, ppr (tyVarKind b)]
999 ------------------------------------------------------
1000 -- Messages for case expressions
1002 mkNullAltsMsg :: CoreExpr -> Message
1004 = hang (text "Case expression with no alternatives:")
1007 mkDefaultArgsMsg :: [Var] -> Message
1008 mkDefaultArgsMsg args
1009 = hang (text "DEFAULT case with binders")
1012 mkCaseAltMsg :: CoreExpr -> Type -> Type -> Message
1013 mkCaseAltMsg e ty1 ty2
1014 = hang (text "Type of case alternatives not the same as the annotation on case:")
1015 4 (vcat [ppr ty1, ppr ty2, ppr e])
1017 mkScrutMsg :: Id -> Type -> Type -> TvSubst -> Message
1018 mkScrutMsg var var_ty scrut_ty subst
1019 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
1020 text "Result binder type:" <+> ppr var_ty,--(idType var),
1021 text "Scrutinee type:" <+> ppr scrut_ty,
1022 hsep [ptext (sLit "Current TV subst"), ppr subst]]
1024 mkNonDefltMsg, mkNonIncreasingAltsMsg :: CoreExpr -> Message
1026 = hang (text "Case expression with DEFAULT not at the beginnning") 4 (ppr e)
1027 mkNonIncreasingAltsMsg e
1028 = hang (text "Case expression with badly-ordered alternatives") 4 (ppr e)
1030 nonExhaustiveAltsMsg :: CoreExpr -> Message
1031 nonExhaustiveAltsMsg e
1032 = hang (text "Case expression with non-exhaustive alternatives") 4 (ppr e)
1034 mkBadConMsg :: TyCon -> DataCon -> Message
1035 mkBadConMsg tycon datacon
1037 text "In a case alternative, data constructor isn't in scrutinee type:",
1038 text "Scrutinee type constructor:" <+> ppr tycon,
1039 text "Data con:" <+> ppr datacon
1042 mkBadPatMsg :: Type -> Type -> Message
1043 mkBadPatMsg con_result_ty scrut_ty
1045 text "In a case alternative, pattern result type doesn't match scrutinee type:",
1046 text "Pattern result type:" <+> ppr con_result_ty,
1047 text "Scrutinee type:" <+> ppr scrut_ty
1050 mkBadAltMsg :: Type -> CoreAlt -> Message
1051 mkBadAltMsg scrut_ty alt
1052 = vcat [ text "Data alternative when scrutinee is not a tycon application",
1053 text "Scrutinee type:" <+> ppr scrut_ty,
1054 text "Alternative:" <+> pprCoreAlt alt ]
1056 mkNewTyDataConAltMsg :: Type -> CoreAlt -> Message
1057 mkNewTyDataConAltMsg scrut_ty alt
1058 = vcat [ text "Data alternative for newtype datacon",
1059 text "Scrutinee type:" <+> ppr scrut_ty,
1060 text "Alternative:" <+> pprCoreAlt alt ]
1063 ------------------------------------------------------
1064 -- Other error messages
1066 mkAppMsg :: Type -> Type -> CoreExpr -> Message
1067 mkAppMsg fun_ty arg_ty arg
1068 = vcat [ptext (sLit "Argument value doesn't match argument type:"),
1069 hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
1070 hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
1071 hang (ptext (sLit "Arg:")) 4 (ppr arg)]
1073 mkNonFunAppMsg :: Type -> Type -> CoreExpr -> Message
1074 mkNonFunAppMsg fun_ty arg_ty arg
1075 = vcat [ptext (sLit "Non-function type in function position"),
1076 hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
1077 hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
1078 hang (ptext (sLit "Arg:")) 4 (ppr arg)]
1080 mkKindErrMsg :: TyVar -> Type -> Message
1081 mkKindErrMsg tyvar arg_ty
1082 = vcat [ptext (sLit "Kinds don't match in type application:"),
1083 hang (ptext (sLit "Type variable:"))
1084 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
1085 hang (ptext (sLit "Arg type:"))
1086 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
1088 mkCoAppErrMsg :: TyVar -> Type -> Message
1089 mkCoAppErrMsg tyvar arg_ty
1090 = vcat [ptext (sLit "Kinds don't match in coercion application:"),
1091 hang (ptext (sLit "Coercion variable:"))
1092 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
1093 hang (ptext (sLit "Arg coercion:"))
1094 4 (ppr arg_ty <+> dcolon <+> pprEqPred (coercionKind arg_ty))]
1096 mkTyAppMsg :: Type -> Type -> Message
1097 mkTyAppMsg ty arg_ty
1098 = vcat [text "Illegal type application:",
1099 hang (ptext (sLit "Exp type:"))
1100 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
1101 hang (ptext (sLit "Arg type:"))
1102 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
1104 mkRhsMsg :: Id -> Type -> Message
1107 [hsep [ptext (sLit "The type of this binder doesn't match the type of its RHS:"),
1109 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)],
1110 hsep [ptext (sLit "Rhs type:"), ppr ty]]
1112 mkRhsPrimMsg :: Id -> CoreExpr -> Message
1113 mkRhsPrimMsg binder _rhs
1114 = vcat [hsep [ptext (sLit "The type of this binder is primitive:"),
1116 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)]
1119 mkStrictMsg :: Id -> Message
1121 = vcat [hsep [ptext (sLit "Recursive or top-level binder has strict demand info:"),
1123 hsep [ptext (sLit "Binder's demand info:"), ppr (idDemandInfo binder)]
1126 mkArityMsg :: Id -> Message
1128 = vcat [hsep [ptext (sLit "Demand type has "),
1129 ppr (dmdTypeDepth dmd_ty),
1130 ptext (sLit " arguments, rhs has "),
1131 ppr (idArity binder),
1132 ptext (sLit "arguments, "),
1134 hsep [ptext (sLit "Binder's strictness signature:"), ppr dmd_ty]
1137 where (StrictSig dmd_ty) = idStrictness binder
1139 mkUnboxedTupleMsg :: Id -> Message
1140 mkUnboxedTupleMsg binder
1141 = vcat [hsep [ptext (sLit "A variable has unboxed tuple type:"), ppr binder],
1142 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)]]
1144 mkCastErr :: Type -> Type -> Message
1145 mkCastErr from_ty expr_ty
1146 = vcat [ptext (sLit "From-type of Cast differs from type of enclosed expression"),
1147 ptext (sLit "From-type:") <+> ppr from_ty,
1148 ptext (sLit "Type of enclosed expr:") <+> ppr expr_ty
1151 dupVars :: [[Var]] -> Message
1153 = hang (ptext (sLit "Duplicate variables brought into scope"))