2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[CoreLint]{A ``lint'' pass to check for Core correctness}
10 beginPass, endPass, endPassWithRules
13 #include "HsVersions.h"
15 import IO ( hPutStr, hPutStrLn, stderr, stdout )
17 import CmdLineOpts ( opt_D_show_passes, opt_DoCoreLinting, opt_PprStyle_Debug )
19 import Rules ( RuleBase, pprRuleBase )
20 import CoreFVs ( idFreeVars, mustHaveLocalBinding )
21 import CoreUtils ( exprOkForSpeculation, coreBindsSize, mkPiType )
24 import Literal ( Literal, literalType )
25 import DataCon ( DataCon, dataConRepType )
26 import Id ( isDeadBinder )
27 import Var ( Var, Id, TyVar, idType, tyVarKind, isTyVar, isId )
29 import Subst ( mkTyVarSubst, substTy )
30 import Name ( isLocallyDefined, getSrcLoc )
32 import ErrUtils ( doIfSet, dumpIfSet, ghcExit, Message,
33 ErrMsg, addErrLocHdrLine, pprBagOfErrors,
34 WarnMsg, pprBagOfWarnings)
35 import PrimRep ( PrimRep(..) )
36 import SrcLoc ( SrcLoc, noSrcLoc, isNoSrcLoc )
37 import Type ( Type, Kind, tyVarsOfType,
38 splitFunTy_maybe, mkTyVarTy,
39 splitForAllTy_maybe, splitTyConApp_maybe,
40 isUnLiftedType, typeKind,
44 import PprType ( {- instance Outputable Type -} )
45 import TyCon ( TyCon, isPrimTyCon, tyConDataCons )
46 import BasicTypes ( RecFlag(..), isNonRec )
50 infixr 9 `thenL`, `seqL`
53 %************************************************************************
55 \subsection{Start and end pass}
57 %************************************************************************
59 @beginPass@ and @endPass@ don't really belong here, but it makes a convenient
60 place for them. They print out stuff before and after core passes,
61 and do Core Lint when necessary.
64 beginPass :: String -> IO ()
67 = hPutStrLn stderr ("*** " ++ pass_name)
72 endPass :: String -> Bool -> [CoreBind] -> IO [CoreBind]
73 endPass pass_name dump_flag binds
75 (binds, _) <- endPassWithRules pass_name dump_flag binds Nothing
78 endPassWithRules :: String -> Bool -> [CoreBind] -> Maybe RuleBase
79 -> IO ([CoreBind], Maybe RuleBase)
80 endPassWithRules pass_name dump_flag binds rules
82 -- ToDo: force the rules?
84 -- Report result size if required
85 -- This has the side effect of forcing the intermediate to be evaluated
86 if opt_D_show_passes then
87 hPutStrLn stdout (" Result size = " ++ show (coreBindsSize binds))
91 -- Report verbosely, if required
92 dumpIfSet dump_flag pass_name
93 (pprCoreBindings binds $$ case rules of
95 Just rb -> pprRuleBase rb)
98 lintCoreBindings pass_name binds
99 -- ToDo: lint the rules
101 return (binds, rules)
105 %************************************************************************
107 \subsection[lintCoreBindings]{@lintCoreBindings@: Top-level interface}
109 %************************************************************************
111 Checks that a set of core bindings is well-formed. The PprStyle and String
112 just control what we print in the event of an error. The Bool value
113 indicates whether we have done any specialisation yet (in which case we do
118 (b) Out-of-scope type variables
119 (c) Out-of-scope local variables
122 If we have done specialisation the we check that there are
123 (a) No top-level bindings of primitive (unboxed type)
128 -- Things are *not* OK if:
130 -- * Unsaturated type app before specialisation has been done;
132 -- * Oversaturated type app after specialisation (eta reduction
133 -- may well be happening...);
136 lintCoreBindings :: String -> [CoreBind] -> IO ()
138 lintCoreBindings whoDunnit binds
139 | not opt_DoCoreLinting
142 lintCoreBindings whoDunnit binds
143 = case (initL (lint_binds binds)) of
144 (Nothing, Nothing) -> done_lint
146 (Nothing, Just warnings) -> printDump (warn warnings) >>
149 (Just bad_news, warns) -> printDump (display bad_news warns) >>
152 -- Put all the top-level binders in scope at the start
153 -- This is because transformation rules can bring something
154 -- into use 'unexpectedly'
155 lint_binds binds = addInScopeVars (bindersOfBinds binds) $
158 lint_bind (Rec prs) = mapL (lintSingleBinding Recursive) prs `seqL`
160 lint_bind (NonRec bndr rhs) = lintSingleBinding NonRecursive (bndr,rhs)
162 done_lint = doIfSet opt_D_show_passes
163 (hPutStr stderr ("*** Core Linted result of " ++ whoDunnit ++ "\n"))
166 text ("*** Core Lint Warnings: in result of " ++ whoDunnit ++ " ***"),
171 display bad_news warns
173 text ("*** Core Lint Errors: in result of " ++ whoDunnit ++ " ***"),
175 maybe offender warn warns -- either offender or warnings (with offender)
180 ptext SLIT("*** Offending Program ***"),
181 pprCoreBindings binds,
182 ptext SLIT("*** End of Offense ***")
186 %************************************************************************
188 \subsection[lintUnfolding]{lintUnfolding}
190 %************************************************************************
192 We use this to check all unfoldings that come in from interfaces
193 (it is very painful to catch errors otherwise):
196 lintUnfolding :: SrcLoc
197 -> [Var] -- Treat these as in scope
199 -> (Maybe Message, Maybe Message) -- (Nothing,_) => OK
201 lintUnfolding locn vars expr
202 | not opt_DoCoreLinting
206 = initL (addLoc (ImportedUnfolding locn) $
207 addInScopeVars vars $
211 %************************************************************************
213 \subsection[lintCoreBinding]{lintCoreBinding}
215 %************************************************************************
217 Check a core binding, returning the list of variables bound.
220 lintSingleBinding rec_flag (binder,rhs)
221 = addLoc (RhsOf binder) $
224 lintCoreExpr rhs `thenL` \ ty ->
226 -- Check match to RHS type
227 lintBinder binder `seqL`
228 checkTys binder_ty ty (mkRhsMsg binder ty) `seqL`
230 -- Check (not isUnLiftedType) (also checks for bogus unboxed tuples)
231 checkL (not (isUnLiftedType binder_ty)
232 || (isNonRec rec_flag && exprOkForSpeculation rhs))
233 (mkRhsPrimMsg binder rhs) `seqL`
235 -- Check whether binder's specialisations contain any out-of-scope variables
236 mapL (checkBndrIdInScope binder) bndr_vars `seqL`
239 -- We should check the unfolding, if any, but this is tricky because
240 -- the unfolding is a SimplifiableCoreExpr. Give up for now.
242 binder_ty = idType binder
243 bndr_vars = varSetElems (idFreeVars binder)
246 %************************************************************************
248 \subsection[lintCoreExpr]{lintCoreExpr}
250 %************************************************************************
253 lintCoreExpr :: CoreExpr -> LintM Type
255 lintCoreExpr (Var var) = checkIdInScope var `seqL` returnL (idType var)
256 lintCoreExpr (Lit lit) = returnL (literalType lit)
258 lintCoreExpr (Note (Coerce to_ty from_ty) expr)
259 = lintCoreExpr expr `thenL` \ expr_ty ->
261 lintTy from_ty `seqL`
262 checkTys from_ty expr_ty (mkCoerceErr from_ty expr_ty) `seqL`
265 lintCoreExpr (Note other_note expr)
268 lintCoreExpr (Let (NonRec bndr rhs) body)
269 = lintSingleBinding NonRecursive (bndr,rhs) `seqL`
270 addLoc (BodyOfLetRec [bndr])
271 (addInScopeVars [bndr] (lintCoreExpr body))
273 lintCoreExpr (Let (Rec pairs) body)
274 = addInScopeVars bndrs $
275 mapL (lintSingleBinding Recursive) pairs `seqL`
276 addLoc (BodyOfLetRec bndrs) (lintCoreExpr body)
278 bndrs = map fst pairs
280 lintCoreExpr e@(App fun arg)
281 = lintCoreExpr fun `thenL` \ ty ->
285 lintCoreExpr (Lam var expr)
286 = addLoc (LambdaBodyOf var) $
288 checkL (not (isUnboxedTupleType (idType var))) (mkUnboxedTupleMsg var)
292 (addInScopeVars [var] $
293 lintCoreExpr expr `thenL` \ ty ->
295 returnL (mkPiType var ty))
297 lintCoreExpr e@(Case scrut var alts)
298 = -- Check the scrutinee
299 lintCoreExpr scrut `thenL` \ scrut_ty ->
302 lintBinder var `seqL`
304 -- If this is an unboxed tuple case, then the binder must be dead
306 checkL (if isUnboxedTupleType (idType var)
307 then isDeadBinder var
308 else True) (mkUnboxedTupleMsg var) `seqL`
311 checkTys (idType var) scrut_ty (mkScrutMsg var scrut_ty) `seqL`
313 addInScopeVars [var] (
315 -- Check the alternatives
316 checkAllCasesCovered e scrut_ty alts `seqL`
318 mapL (lintCoreAlt scrut_ty) alts `thenL` \ (alt_ty : alt_tys) ->
319 mapL (check alt_ty) alt_tys `seqL`
322 check alt_ty1 alt_ty2 = checkTys alt_ty1 alt_ty2 (mkCaseAltMsg e)
324 lintCoreExpr e@(Type ty)
325 = addErrL (mkStrangeTyMsg e)
328 %************************************************************************
330 \subsection[lintCoreArgs]{lintCoreArgs}
332 %************************************************************************
334 The basic version of these functions checks that the argument is a
335 subtype of the required type, as one would expect.
338 lintCoreArgs :: Type -> [CoreArg] -> LintM Type
339 lintCoreArgs = lintCoreArgs0 checkTys
341 lintCoreArg :: Type -> CoreArg -> LintM Type
342 lintCoreArg = lintCoreArg0 checkTys
345 The primitive version of these functions takes a check argument,
346 allowing a different comparison.
349 lintCoreArgs0 check_tys ty [] = returnL ty
350 lintCoreArgs0 check_tys ty (a : args)
351 = lintCoreArg0 check_tys ty a `thenL` \ res ->
352 lintCoreArgs0 check_tys res args
354 lintCoreArg0 check_tys ty a@(Type arg_ty)
355 = lintTy arg_ty `seqL`
358 lintCoreArg0 check_tys fun_ty arg
359 = -- Make sure function type matches argument
360 lintCoreExpr arg `thenL` \ arg_ty ->
362 err = mkAppMsg fun_ty arg_ty
364 case splitFunTy_maybe fun_ty of
365 Just (arg,res) -> check_tys arg arg_ty err `seqL`
372 = case splitForAllTy_maybe ty of
373 Nothing -> addErrL (mkTyAppMsg ty arg_ty)
376 if not (isTyVar tyvar) then addErrL (mkTyAppMsg ty arg_ty) else
378 tyvar_kind = tyVarKind tyvar
379 argty_kind = typeKind arg_ty
381 if argty_kind `hasMoreBoxityInfo` tyvar_kind
382 -- Arg type might be boxed for a function with an uncommitted
383 -- tyvar; notably this is used so that we can give
384 -- error :: forall a:*. String -> a
385 -- and then apply it to both boxed and unboxed types.
387 returnL (substTy (mkTyVarSubst [tyvar] [arg_ty]) body)
389 addErrL (mkKindErrMsg tyvar arg_ty)
394 lintTyApps fun_ty (arg_ty : arg_tys)
395 = lintTyApp fun_ty arg_ty `thenL` \ fun_ty' ->
396 lintTyApps fun_ty' arg_tys
401 %************************************************************************
403 \subsection[lintCoreAlts]{lintCoreAlts}
405 %************************************************************************
408 checkAllCasesCovered :: CoreExpr -> Type -> [CoreAlt] -> LintM ()
410 checkAllCasesCovered e ty [] = addErrL (mkNullAltsMsg e)
412 checkAllCasesCovered e ty [(DEFAULT,_,_)] = nopL
414 checkAllCasesCovered e scrut_ty alts
415 = case splitTyConApp_maybe scrut_ty of {
416 Nothing -> addErrL (badAltsMsg e);
417 Just (tycon, tycon_arg_tys) ->
419 if isPrimTyCon tycon then
420 checkL (hasDefault alts) (nonExhaustiveAltsMsg e)
424 -- Algebraic cases are not necessarily exhaustive, because
425 -- the simplifer correctly eliminates case that can't
427 -- This code just emits a message to say so
429 missing_cons = filter not_in_alts (tyConDataCons tycon)
430 not_in_alts con = all (not_in_alt con) alts
431 not_in_alt con (DataCon con', _, _) = con /= con'
432 not_in_alt con other = True
434 case_bndr = case e of { Case _ bndr alts -> bndr }
436 if not (hasDefault alts || null missing_cons) then
437 pprTrace "Exciting (but not a problem)! Non-exhaustive case:"
438 (ppr case_bndr <+> ppr missing_cons)
445 hasDefault [] = False
446 hasDefault ((DEFAULT,_,_) : alts) = True
447 hasDefault (alt : alts) = hasDefault alts
451 lintCoreAlt :: Type -- Type of scrutinee
453 -> LintM Type -- Type of alternatives
455 lintCoreAlt scrut_ty alt@(DEFAULT, args, rhs)
456 = checkL (null args) (mkDefaultArgsMsg args) `seqL`
459 lintCoreAlt scrut_ty alt@(LitAlt lit, args, rhs)
460 = checkL (null args) (mkDefaultArgsMsg args) `seqL`
461 checkTys lit_ty scrut_ty
462 (mkBadPatMsg lit_ty scrut_ty) `seqL`
465 lit_ty = literalType lit
467 lintCoreAlt scrut_ty alt@(DataAlt con, args, rhs)
468 = addLoc (CaseAlt alt) (
470 mapL (\arg -> checkL (not (isUnboxedTupleType (idType arg)))
471 (mkUnboxedTupleMsg arg)) args `seqL`
473 addInScopeVars args (
476 -- Scrutinee type must be a tycon applicn; checked by caller
477 -- This code is remarkably compact considering what it does!
478 -- NB: args must be in scope here so that the lintCoreArgs line works.
479 case splitTyConApp_maybe scrut_ty of { Just (tycon, tycon_arg_tys) ->
480 lintTyApps (dataConRepType con) tycon_arg_tys `thenL` \ con_type ->
481 lintCoreArgs con_type (map mk_arg args) `thenL` \ con_result_ty ->
482 checkTys con_result_ty scrut_ty (mkBadPatMsg con_result_ty scrut_ty)
489 mk_arg b | isTyVar b = Type (mkTyVarTy b)
491 | otherwise = pprPanic "lintCoreAlt:mk_arg " (ppr b)
494 %************************************************************************
496 \subsection[lint-types]{Types}
498 %************************************************************************
501 lintBinder :: Var -> LintM ()
503 -- ToDo: lint its type
504 -- ToDo: lint its rules
506 lintTy :: Type -> LintM ()
507 lintTy ty = mapL checkIdInScope (varSetElems (tyVarsOfType ty)) `seqL`
509 -- ToDo: check the kind structure of the type
513 %************************************************************************
515 \subsection[lint-monad]{The Lint monad}
517 %************************************************************************
520 type LintM a = [LintLocInfo] -- Locations
521 -> IdSet -- Local vars in scope
522 -> Bag ErrMsg -- Error messages so far
523 -> Bag WarnMsg -- Warning messages so far
524 -> (Maybe a, Bag ErrMsg, Bag WarnMsg) -- Result and error/warning messages (if any)
527 = RhsOf Id -- The variable bound
528 | LambdaBodyOf Id -- The lambda-binder
529 | BodyOfLetRec [Id] -- One of the binders
530 | CaseAlt CoreAlt -- Pattern of a case alternative
531 | AnExpr CoreExpr -- Some expression
532 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
536 initL :: LintM a -> (Maybe Message {- errors -}, Maybe Message {- warnings -})
538 = case m [] emptyVarSet emptyBag emptyBag of
539 (_, errs, warns) -> (ifNonEmptyBag errs pprBagOfErrors,
540 ifNonEmptyBag warns pprBagOfWarnings)
542 ifNonEmptyBag bag f | isEmptyBag bag = Nothing
543 | otherwise = Just (f bag)
545 returnL :: a -> LintM a
546 returnL r loc scope errs warns = (Just r, errs, warns)
549 nopL loc scope errs warns = (Nothing, errs, warns)
551 thenL :: LintM a -> (a -> LintM b) -> LintM b
552 thenL m k loc scope errs warns
553 = case m loc scope errs warns of
554 (Just r, errs', warns') -> k r loc scope errs' warns'
555 (Nothing, errs', warns') -> (Nothing, errs', warns')
557 seqL :: LintM a -> LintM b -> LintM b
558 seqL m k loc scope errs warns
559 = case m loc scope errs warns of
560 (_, errs', warns') -> k loc scope errs' warns'
562 mapL :: (a -> LintM b) -> [a] -> LintM [b]
563 mapL f [] = returnL []
566 mapL f xs `thenL` \ rs ->
571 checkL :: Bool -> Message -> LintM ()
572 checkL True msg = nopL
573 checkL False msg = addErrL msg
575 addErrL :: Message -> LintM a
576 addErrL msg loc scope errs warns = (Nothing, addErr errs msg loc, warns)
578 addWarnL :: Message -> LintM a
579 addWarnL msg loc scope errs warns = (Nothing, errs, addErr warns msg loc)
581 addErr :: Bag ErrMsg -> Message -> [LintLocInfo] -> Bag ErrMsg
582 -- errors or warnings, actually... they're the same type.
583 addErr errs_so_far msg locs
584 = ASSERT( not (null locs) )
585 errs_so_far `snocBag` mk_msg msg
587 (loc, cxt1) = dumpLoc (head locs)
588 cxts = [snd (dumpLoc loc) | loc <- locs]
589 context | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1
593 | isNoSrcLoc loc = (loc, hang context 4 msg)
594 | otherwise = addErrLocHdrLine loc context msg
596 addLoc :: LintLocInfo -> LintM a -> LintM a
597 addLoc extra_loc m loc scope errs warns
598 = m (extra_loc:loc) scope errs warns
600 addInScopeVars :: [Var] -> LintM a -> LintM a
601 addInScopeVars ids m loc scope errs warns
602 = m loc (scope `unionVarSet` mkVarSet ids) errs warns
606 checkIdInScope :: Var -> LintM ()
608 = checkInScope (ptext SLIT("is out of scope")) id
610 checkBndrIdInScope :: Var -> Var -> LintM ()
611 checkBndrIdInScope binder id
612 = checkInScope msg id
614 msg = ptext SLIT("is out of scope inside info for") <+>
617 checkInScope :: SDoc -> Var -> LintM ()
618 checkInScope loc_msg var loc scope errs warns
619 | mustHaveLocalBinding var && not (var `elemVarSet` scope)
620 = (Nothing, addErr errs (hsep [ppr var, loc_msg]) loc, warns)
622 = nopL loc scope errs warns
624 checkTys :: Type -> Type -> Message -> LintM ()
625 -- check ty2 is subtype of ty1 (ie, has same structure but usage
626 -- annotations need only be consistent, not equal)
629 | otherwise = addErrL msg
633 %************************************************************************
635 \subsection{Error messages}
637 %************************************************************************
641 = (getSrcLoc v, brackets (ptext SLIT("RHS of") <+> pp_binders [v]))
643 dumpLoc (LambdaBodyOf b)
644 = (getSrcLoc b, brackets (ptext SLIT("in body of lambda with binder") <+> pp_binder b))
646 dumpLoc (BodyOfLetRec [])
647 = (noSrcLoc, brackets (ptext SLIT("In body of a letrec with no binders")))
649 dumpLoc (BodyOfLetRec bs@(_:_))
650 = ( getSrcLoc (head bs), brackets (ptext SLIT("in body of letrec with binders") <+> pp_binders bs))
653 = (noSrcLoc, text "In the expression:" <+> ppr e)
655 dumpLoc (CaseAlt (con, args, rhs))
656 = (noSrcLoc, text "In a case pattern:" <+> parens (ppr con <+> ppr args))
658 dumpLoc (ImportedUnfolding locn)
659 = (locn, brackets (ptext SLIT("in an imported unfolding")))
661 pp_binders :: [Var] -> SDoc
662 pp_binders bs = sep (punctuate comma (map pp_binder bs))
664 pp_binder :: Var -> SDoc
665 pp_binder b | isId b = hsep [ppr b, dcolon, ppr (idType b)]
666 | isTyVar b = hsep [ppr b, dcolon, ppr (tyVarKind b)]
670 ------------------------------------------------------
671 -- Messages for case expressions
673 mkNullAltsMsg :: CoreExpr -> Message
675 = hang (text "Case expression with no alternatives:")
678 mkDefaultArgsMsg :: [Var] -> Message
679 mkDefaultArgsMsg args
680 = hang (text "DEFAULT case with binders")
683 mkCaseAltMsg :: CoreExpr -> Message
685 = hang (text "Type of case alternatives not the same:")
688 mkScrutMsg :: Id -> Type -> Message
689 mkScrutMsg var scrut_ty
690 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
691 text "Result binder type:" <+> ppr (idType var),
692 text "Scrutinee type:" <+> ppr scrut_ty]
694 badAltsMsg :: CoreExpr -> Message
696 = hang (text "Case statement scrutinee is not a data type:")
699 nonExhaustiveAltsMsg :: CoreExpr -> Message
700 nonExhaustiveAltsMsg e
701 = hang (text "Case expression with non-exhaustive alternatives")
704 mkBadPatMsg :: Type -> Type -> Message
705 mkBadPatMsg con_result_ty scrut_ty
707 text "In a case alternative, pattern result type doesn't match scrutinee type:",
708 text "Pattern result type:" <+> ppr con_result_ty,
709 text "Scrutinee type:" <+> ppr scrut_ty
712 ------------------------------------------------------
713 -- Other error messages
715 mkAppMsg :: Type -> Type -> Message
717 = vcat [ptext SLIT("Argument value doesn't match argument type:"),
718 hang (ptext SLIT("Fun type:")) 4 (ppr fun),
719 hang (ptext SLIT("Arg type:")) 4 (ppr arg)]
721 mkKindErrMsg :: TyVar -> Type -> Message
722 mkKindErrMsg tyvar arg_ty
723 = vcat [ptext SLIT("Kinds don't match in type application:"),
724 hang (ptext SLIT("Type variable:"))
725 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
726 hang (ptext SLIT("Arg type:"))
727 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
729 mkTyAppMsg :: Type -> Type -> Message
731 = vcat [text "Illegal type application:",
732 hang (ptext SLIT("Exp type:"))
733 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
734 hang (ptext SLIT("Arg type:"))
735 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
737 mkRhsMsg :: Id -> Type -> Message
740 [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
742 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
743 hsep [ptext SLIT("Rhs type:"), ppr ty]]
745 mkRhsPrimMsg :: Id -> CoreExpr -> Message
746 mkRhsPrimMsg binder rhs
747 = vcat [hsep [ptext SLIT("The type of this binder is primitive:"),
749 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]
752 mkUnboxedTupleMsg :: Id -> Message
753 mkUnboxedTupleMsg binder
754 = vcat [hsep [ptext SLIT("A variable has unboxed tuple type:"), ppr binder],
755 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]]
757 mkCoerceErr from_ty expr_ty
758 = vcat [ptext SLIT("From-type of Coerce differs from type of enclosed expression"),
759 ptext SLIT("From-type:") <+> ppr from_ty,
760 ptext SLIT("Type of enclosed expr:") <+> ppr expr_ty
764 = ptext SLIT("Type where expression expected:") <+> ppr e