2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[CoreLint]{A ``lint'' pass to check for Core correctness}
10 showPass, endPass, endPassWithRules
13 #include "HsVersions.h"
15 import IO ( hPutStr, hPutStrLn, stdout )
18 import Rules ( RuleBase, pprRuleBase )
19 import CoreFVs ( idFreeVars, mustHaveLocalBinding )
20 import CoreUtils ( exprOkForSpeculation, coreBindsSize, mkPiType )
23 import Literal ( literalType )
24 import DataCon ( dataConRepType )
25 import Var ( Var, Id, TyVar, idType, tyVarKind, isTyVar, isId )
27 import Subst ( mkTyVarSubst, substTy )
28 import Name ( getSrcLoc )
30 import ErrUtils ( doIfSet, dumpIfSet, ghcExit, Message, showPass,
31 ErrMsg, addErrLocHdrLine, pprBagOfErrors,
32 WarnMsg, pprBagOfWarnings)
33 import SrcLoc ( SrcLoc, noSrcLoc )
34 import Type ( Type, tyVarsOfType,
35 splitFunTy_maybe, mkTyVarTy,
36 splitForAllTy_maybe, splitTyConApp_maybe, splitTyConApp,
37 isUnLiftedType, typeKind,
41 import TyCon ( isPrimTyCon )
42 import BasicTypes ( RecFlag(..), isNonRec )
47 infixr 9 `thenL`, `seqL`
50 %************************************************************************
52 \subsection{Start and end pass}
54 %************************************************************************
56 @beginPass@ and @endPass@ don't really belong here, but it makes a convenient
57 place for them. They print out stuff before and after core passes,
58 and do Core Lint when necessary.
61 endPass :: DynFlags -> String -> Bool -> [CoreBind] -> IO [CoreBind]
62 endPass dflags pass_name dump_flag binds
64 (binds, _) <- endPassWithRules dflags pass_name dump_flag binds Nothing
67 endPassWithRules :: DynFlags -> String -> Bool -> [CoreBind] -> Maybe RuleBase
68 -> IO ([CoreBind], Maybe RuleBase)
69 endPassWithRules dflags pass_name dump_flag binds rules
71 -- ToDo: force the rules?
73 -- Report result size if required
74 -- This has the side effect of forcing the intermediate to be evaluated
75 if verbosity dflags >= 2 then
76 hPutStrLn stdout (" Result size = " ++ show (coreBindsSize binds))
80 -- Report verbosely, if required
81 dumpIfSet dump_flag pass_name
82 (pprCoreBindings binds $$ case rules of
84 Just rb -> pprRuleBase rb)
87 lintCoreBindings dflags pass_name binds
88 -- ToDo: lint the rules
94 %************************************************************************
96 \subsection[lintCoreBindings]{@lintCoreBindings@: Top-level interface}
98 %************************************************************************
100 Checks that a set of core bindings is well-formed. The PprStyle and String
101 just control what we print in the event of an error. The Bool value
102 indicates whether we have done any specialisation yet (in which case we do
107 (b) Out-of-scope type variables
108 (c) Out-of-scope local variables
111 If we have done specialisation the we check that there are
112 (a) No top-level bindings of primitive (unboxed type)
117 -- Things are *not* OK if:
119 -- * Unsaturated type app before specialisation has been done;
121 -- * Oversaturated type app after specialisation (eta reduction
122 -- may well be happening...);
125 lintCoreBindings :: DynFlags -> String -> [CoreBind] -> IO ()
127 lintCoreBindings dflags whoDunnit binds
128 | not (dopt Opt_DoCoreLinting dflags)
131 lintCoreBindings dflags whoDunnit binds
132 = case (initL (lint_binds binds)) of
133 (Nothing, Nothing) -> done_lint
135 (Nothing, Just warnings) -> printDump (warn warnings) >>
138 (Just bad_news, warns) -> printDump (display bad_news warns) >>
141 -- Put all the top-level binders in scope at the start
142 -- This is because transformation rules can bring something
143 -- into use 'unexpectedly'
144 lint_binds binds = addInScopeVars (bindersOfBinds binds) $
147 lint_bind (Rec prs) = mapL (lintSingleBinding Recursive) prs `seqL`
149 lint_bind (NonRec bndr rhs) = lintSingleBinding NonRecursive (bndr,rhs)
151 done_lint = doIfSet (verbosity dflags >= 2)
152 (hPutStr stdout ("*** Core Linted result of " ++ whoDunnit ++ "\n"))
155 text ("*** Core Lint Warnings: in result of " ++ whoDunnit ++ " ***"),
160 display bad_news warns
162 text ("*** Core Lint Errors: in result of " ++ whoDunnit ++ " ***"),
164 maybe offender warn warns -- either offender or warnings (with offender)
169 ptext SLIT("*** Offending Program ***"),
170 pprCoreBindings binds,
171 ptext SLIT("*** End of Offense ***")
175 %************************************************************************
177 \subsection[lintUnfolding]{lintUnfolding}
179 %************************************************************************
181 We use this to check all unfoldings that come in from interfaces
182 (it is very painful to catch errors otherwise):
185 lintUnfolding :: DynFlags
187 -> [Var] -- Treat these as in scope
189 -> (Maybe Message, Maybe Message) -- (Nothing,_) => OK
191 lintUnfolding dflags locn vars expr
192 | not (dopt Opt_DoCoreLinting dflags)
196 = initL (addLoc (ImportedUnfolding locn) $
197 addInScopeVars vars $
201 %************************************************************************
203 \subsection[lintCoreBinding]{lintCoreBinding}
205 %************************************************************************
207 Check a core binding, returning the list of variables bound.
210 lintSingleBinding rec_flag (binder,rhs)
211 = addLoc (RhsOf binder) $
214 lintCoreExpr rhs `thenL` \ ty ->
216 -- Check match to RHS type
217 lintBinder binder `seqL`
218 checkTys binder_ty ty (mkRhsMsg binder ty) `seqL`
220 -- Check (not isUnLiftedType) (also checks for bogus unboxed tuples)
221 checkL (not (isUnLiftedType binder_ty)
222 || (isNonRec rec_flag && exprOkForSpeculation rhs))
223 (mkRhsPrimMsg binder rhs) `seqL`
225 -- Check whether binder's specialisations contain any out-of-scope variables
226 mapL (checkBndrIdInScope binder) bndr_vars `seqL`
229 -- We should check the unfolding, if any, but this is tricky because
230 -- the unfolding is a SimplifiableCoreExpr. Give up for now.
232 binder_ty = idType binder
233 bndr_vars = varSetElems (idFreeVars binder)
236 %************************************************************************
238 \subsection[lintCoreExpr]{lintCoreExpr}
240 %************************************************************************
243 lintCoreExpr :: CoreExpr -> LintM Type
245 lintCoreExpr (Var var) = checkIdInScope var `seqL` returnL (idType var)
246 lintCoreExpr (Lit lit) = returnL (literalType lit)
248 lintCoreExpr (Note (Coerce to_ty from_ty) expr)
249 = lintCoreExpr expr `thenL` \ expr_ty ->
251 lintTy from_ty `seqL`
252 checkTys from_ty expr_ty (mkCoerceErr from_ty expr_ty) `seqL`
255 lintCoreExpr (Note other_note expr)
258 lintCoreExpr (Let (NonRec bndr rhs) body)
259 = lintSingleBinding NonRecursive (bndr,rhs) `seqL`
260 addLoc (BodyOfLetRec [bndr])
261 (addInScopeVars [bndr] (lintCoreExpr body))
263 lintCoreExpr (Let (Rec pairs) body)
264 = addInScopeVars bndrs $
265 mapL (lintSingleBinding Recursive) pairs `seqL`
266 addLoc (BodyOfLetRec bndrs) (lintCoreExpr body)
268 bndrs = map fst pairs
270 lintCoreExpr e@(App fun arg)
271 = lintCoreExpr fun `thenL` \ ty ->
275 lintCoreExpr (Lam var expr)
276 = addLoc (LambdaBodyOf var) $
278 checkL (not (isUnboxedTupleType (idType var))) (mkUnboxedTupleMsg var)
282 (addInScopeVars [var] $
283 lintCoreExpr expr `thenL` \ ty ->
285 returnL (mkPiType var ty))
287 lintCoreExpr e@(Case scrut var alts)
288 = -- Check the scrutinee
289 lintCoreExpr scrut `thenL` \ scrut_ty ->
292 lintBinder var `seqL`
294 -- If this is an unboxed tuple case, then the binder must be dead
296 checkL (if isUnboxedTupleType (idType var)
297 then isDeadBinder var
298 else True) (mkUnboxedTupleMsg var) `seqL`
301 checkTys (idType var) scrut_ty (mkScrutMsg var scrut_ty) `seqL`
303 addInScopeVars [var] (
305 -- Check the alternatives
306 checkAllCasesCovered e scrut_ty alts `seqL`
308 mapL (lintCoreAlt scrut_ty) alts `thenL` \ (alt_ty : alt_tys) ->
309 mapL (check alt_ty) alt_tys `seqL`
312 check alt_ty1 alt_ty2 = checkTys alt_ty1 alt_ty2 (mkCaseAltMsg e)
314 lintCoreExpr e@(Type ty)
315 = addErrL (mkStrangeTyMsg e)
318 %************************************************************************
320 \subsection[lintCoreArgs]{lintCoreArgs}
322 %************************************************************************
324 The basic version of these functions checks that the argument is a
325 subtype of the required type, as one would expect.
328 lintCoreArgs :: Type -> [CoreArg] -> LintM Type
329 lintCoreArgs = lintCoreArgs0 checkTys
331 lintCoreArg :: Type -> CoreArg -> LintM Type
332 lintCoreArg = lintCoreArg0 checkTys
335 The primitive version of these functions takes a check argument,
336 allowing a different comparison.
339 lintCoreArgs0 check_tys ty [] = returnL ty
340 lintCoreArgs0 check_tys ty (a : args)
341 = lintCoreArg0 check_tys ty a `thenL` \ res ->
342 lintCoreArgs0 check_tys res args
344 lintCoreArg0 check_tys ty a@(Type arg_ty)
345 = lintTy arg_ty `seqL`
348 lintCoreArg0 check_tys fun_ty arg
349 = -- Make sure function type matches argument
350 lintCoreExpr arg `thenL` \ arg_ty ->
352 err = mkAppMsg fun_ty arg_ty
354 case splitFunTy_maybe fun_ty of
355 Just (arg,res) -> check_tys arg arg_ty err `seqL`
362 = case splitForAllTy_maybe ty of
363 Nothing -> addErrL (mkTyAppMsg ty arg_ty)
366 if not (isTyVar tyvar) then addErrL (mkTyAppMsg ty arg_ty) else
368 tyvar_kind = tyVarKind tyvar
369 argty_kind = typeKind arg_ty
371 if argty_kind `hasMoreBoxityInfo` tyvar_kind
372 -- Arg type might be boxed for a function with an uncommitted
373 -- tyvar; notably this is used so that we can give
374 -- error :: forall a:*. String -> a
375 -- and then apply it to both boxed and unboxed types.
377 returnL (substTy (mkTyVarSubst [tyvar] [arg_ty]) body)
379 addErrL (mkKindErrMsg tyvar arg_ty)
384 lintTyApps fun_ty (arg_ty : arg_tys)
385 = lintTyApp fun_ty arg_ty `thenL` \ fun_ty' ->
386 lintTyApps fun_ty' arg_tys
391 %************************************************************************
393 \subsection[lintCoreAlts]{lintCoreAlts}
395 %************************************************************************
398 checkAllCasesCovered :: CoreExpr -> Type -> [CoreAlt] -> LintM ()
400 checkAllCasesCovered e ty [] = addErrL (mkNullAltsMsg e)
402 checkAllCasesCovered e ty [(DEFAULT,_,_)] = nopL
404 checkAllCasesCovered e scrut_ty alts
405 = case splitTyConApp_maybe scrut_ty of {
406 Nothing -> addErrL (badAltsMsg e);
407 Just (tycon, tycon_arg_tys) ->
409 if isPrimTyCon tycon then
410 checkL (hasDefault alts) (nonExhaustiveAltsMsg e)
414 -- Algebraic cases are not necessarily exhaustive, because
415 -- the simplifer correctly eliminates case that can't
417 -- This code just emits a message to say so
419 missing_cons = filter not_in_alts (tyConDataCons tycon)
420 not_in_alts con = all (not_in_alt con) alts
421 not_in_alt con (DataCon con', _, _) = con /= con'
422 not_in_alt con other = True
424 case_bndr = case e of { Case _ bndr alts -> bndr }
426 if not (hasDefault alts || null missing_cons) then
427 pprTrace "Exciting (but not a problem)! Non-exhaustive case:"
428 (ppr case_bndr <+> ppr missing_cons)
435 hasDefault [] = False
436 hasDefault ((DEFAULT,_,_) : alts) = True
437 hasDefault (alt : alts) = hasDefault alts
441 lintCoreAlt :: Type -- Type of scrutinee
443 -> LintM Type -- Type of alternatives
445 lintCoreAlt scrut_ty alt@(DEFAULT, args, rhs)
446 = checkL (null args) (mkDefaultArgsMsg args) `seqL`
449 lintCoreAlt scrut_ty alt@(LitAlt lit, args, rhs)
450 = checkL (null args) (mkDefaultArgsMsg args) `seqL`
451 checkTys lit_ty scrut_ty
452 (mkBadPatMsg lit_ty scrut_ty) `seqL`
455 lit_ty = literalType lit
457 lintCoreAlt scrut_ty alt@(DataAlt con, args, rhs)
458 = addLoc (CaseAlt alt) (
460 mapL (\arg -> checkL (not (isUnboxedTupleType (idType arg)))
461 (mkUnboxedTupleMsg arg)) args `seqL`
463 addInScopeVars args (
466 -- Scrutinee type must be a tycon applicn; checked by caller
467 -- This code is remarkably compact considering what it does!
468 -- NB: args must be in scope here so that the lintCoreArgs line works.
469 case splitTyConApp scrut_ty of { (tycon, tycon_arg_tys) ->
470 lintTyApps (dataConRepType con) tycon_arg_tys `thenL` \ con_type ->
471 lintCoreArgs con_type (map mk_arg args) `thenL` \ con_result_ty ->
472 checkTys con_result_ty scrut_ty (mkBadPatMsg con_result_ty scrut_ty)
479 mk_arg b | isTyVar b = Type (mkTyVarTy b)
481 | otherwise = pprPanic "lintCoreAlt:mk_arg " (ppr b)
484 %************************************************************************
486 \subsection[lint-types]{Types}
488 %************************************************************************
491 lintBinder :: Var -> LintM ()
493 -- ToDo: lint its type
494 -- ToDo: lint its rules
496 lintTy :: Type -> LintM ()
497 lintTy ty = mapL checkIdInScope (varSetElems (tyVarsOfType ty)) `seqL`
499 -- ToDo: check the kind structure of the type
503 %************************************************************************
505 \subsection[lint-monad]{The Lint monad}
507 %************************************************************************
510 type LintM a = [LintLocInfo] -- Locations
511 -> IdSet -- Local vars in scope
512 -> Bag ErrMsg -- Error messages so far
513 -> Bag WarnMsg -- Warning messages so far
514 -> (Maybe a, Bag ErrMsg, Bag WarnMsg) -- Result and error/warning messages (if any)
517 = RhsOf Id -- The variable bound
518 | LambdaBodyOf Id -- The lambda-binder
519 | BodyOfLetRec [Id] -- One of the binders
520 | CaseAlt CoreAlt -- Pattern of a case alternative
521 | AnExpr CoreExpr -- Some expression
522 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
526 initL :: LintM a -> (Maybe Message {- errors -}, Maybe Message {- warnings -})
528 = case m [] emptyVarSet emptyBag emptyBag of
529 (_, errs, warns) -> (ifNonEmptyBag errs pprBagOfErrors,
530 ifNonEmptyBag warns pprBagOfWarnings)
532 ifNonEmptyBag bag f | isEmptyBag bag = Nothing
533 | otherwise = Just (f bag)
535 returnL :: a -> LintM a
536 returnL r loc scope errs warns = (Just r, errs, warns)
539 nopL loc scope errs warns = (Nothing, errs, warns)
541 thenL :: LintM a -> (a -> LintM b) -> LintM b
542 thenL m k loc scope errs warns
543 = case m loc scope errs warns of
544 (Just r, errs', warns') -> k r loc scope errs' warns'
545 (Nothing, errs', warns') -> (Nothing, errs', warns')
547 seqL :: LintM a -> LintM b -> LintM b
548 seqL m k loc scope errs warns
549 = case m loc scope errs warns of
550 (_, errs', warns') -> k loc scope errs' warns'
552 mapL :: (a -> LintM b) -> [a] -> LintM [b]
553 mapL f [] = returnL []
556 mapL f xs `thenL` \ rs ->
561 checkL :: Bool -> Message -> LintM ()
562 checkL True msg = nopL
563 checkL False msg = addErrL msg
565 addErrL :: Message -> LintM a
566 addErrL msg loc scope errs warns = (Nothing, addErr errs msg loc, warns)
568 addWarnL :: Message -> LintM a
569 addWarnL msg loc scope errs warns = (Nothing, errs, addErr warns msg loc)
571 addErr :: Bag ErrMsg -> Message -> [LintLocInfo] -> Bag ErrMsg
572 -- errors or warnings, actually... they're the same type.
573 addErr errs_so_far msg locs
574 = ASSERT( not (null locs) )
575 errs_so_far `snocBag` mk_msg msg
577 (loc, cxt1) = dumpLoc (head locs)
578 cxts = [snd (dumpLoc loc) | loc <- locs]
579 context | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1
582 mk_msg msg = addErrLocHdrLine loc context msg
584 addLoc :: LintLocInfo -> LintM a -> LintM a
585 addLoc extra_loc m loc scope errs warns
586 = m (extra_loc:loc) scope errs warns
588 addInScopeVars :: [Var] -> LintM a -> LintM a
589 addInScopeVars ids m loc scope errs warns
590 = m loc (scope `unionVarSet` mkVarSet ids) errs warns
594 checkIdInScope :: Var -> LintM ()
596 = checkInScope (ptext SLIT("is out of scope")) id
598 checkBndrIdInScope :: Var -> Var -> LintM ()
599 checkBndrIdInScope binder id
600 = checkInScope msg id
602 msg = ptext SLIT("is out of scope inside info for") <+>
605 checkInScope :: SDoc -> Var -> LintM ()
606 checkInScope loc_msg var loc scope errs warns
607 | mustHaveLocalBinding var && not (var `elemVarSet` scope)
608 = (Nothing, addErr errs (hsep [ppr var, loc_msg]) loc, warns)
610 = nopL loc scope errs warns
612 checkTys :: Type -> Type -> Message -> LintM ()
613 -- check ty2 is subtype of ty1 (ie, has same structure but usage
614 -- annotations need only be consistent, not equal)
617 | otherwise = addErrL msg
621 %************************************************************************
623 \subsection{Error messages}
625 %************************************************************************
629 = (getSrcLoc v, brackets (ptext SLIT("RHS of") <+> pp_binders [v]))
631 dumpLoc (LambdaBodyOf b)
632 = (getSrcLoc b, brackets (ptext SLIT("in body of lambda with binder") <+> pp_binder b))
634 dumpLoc (BodyOfLetRec [])
635 = (noSrcLoc, brackets (ptext SLIT("In body of a letrec with no binders")))
637 dumpLoc (BodyOfLetRec bs@(_:_))
638 = ( getSrcLoc (head bs), brackets (ptext SLIT("in body of letrec with binders") <+> pp_binders bs))
641 = (noSrcLoc, text "In the expression:" <+> ppr e)
643 dumpLoc (CaseAlt (con, args, rhs))
644 = (noSrcLoc, text "In a case pattern:" <+> parens (ppr con <+> ppr args))
646 dumpLoc (ImportedUnfolding locn)
647 = (locn, brackets (ptext SLIT("in an imported unfolding")))
649 pp_binders :: [Var] -> SDoc
650 pp_binders bs = sep (punctuate comma (map pp_binder bs))
652 pp_binder :: Var -> SDoc
653 pp_binder b | isId b = hsep [ppr b, dcolon, ppr (idType b)]
654 | isTyVar b = hsep [ppr b, dcolon, ppr (tyVarKind b)]
658 ------------------------------------------------------
659 -- Messages for case expressions
661 mkNullAltsMsg :: CoreExpr -> Message
663 = hang (text "Case expression with no alternatives:")
666 mkDefaultArgsMsg :: [Var] -> Message
667 mkDefaultArgsMsg args
668 = hang (text "DEFAULT case with binders")
671 mkCaseAltMsg :: CoreExpr -> Message
673 = hang (text "Type of case alternatives not the same:")
676 mkScrutMsg :: Id -> Type -> Message
677 mkScrutMsg var scrut_ty
678 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
679 text "Result binder type:" <+> ppr (idType var),
680 text "Scrutinee type:" <+> ppr scrut_ty]
682 badAltsMsg :: CoreExpr -> Message
684 = hang (text "Case statement scrutinee is not a data type:")
687 nonExhaustiveAltsMsg :: CoreExpr -> Message
688 nonExhaustiveAltsMsg e
689 = hang (text "Case expression with non-exhaustive alternatives")
692 mkBadPatMsg :: Type -> Type -> Message
693 mkBadPatMsg con_result_ty scrut_ty
695 text "In a case alternative, pattern result type doesn't match scrutinee type:",
696 text "Pattern result type:" <+> ppr con_result_ty,
697 text "Scrutinee type:" <+> ppr scrut_ty
700 ------------------------------------------------------
701 -- Other error messages
703 mkAppMsg :: Type -> Type -> Message
705 = vcat [ptext SLIT("Argument value doesn't match argument type:"),
706 hang (ptext SLIT("Fun type:")) 4 (ppr fun),
707 hang (ptext SLIT("Arg type:")) 4 (ppr arg)]
709 mkKindErrMsg :: TyVar -> Type -> Message
710 mkKindErrMsg tyvar arg_ty
711 = vcat [ptext SLIT("Kinds don't match in type application:"),
712 hang (ptext SLIT("Type variable:"))
713 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
714 hang (ptext SLIT("Arg type:"))
715 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
717 mkTyAppMsg :: Type -> Type -> Message
719 = vcat [text "Illegal type application:",
720 hang (ptext SLIT("Exp type:"))
721 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
722 hang (ptext SLIT("Arg type:"))
723 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
725 mkRhsMsg :: Id -> Type -> Message
728 [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
730 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
731 hsep [ptext SLIT("Rhs type:"), ppr ty]]
733 mkRhsPrimMsg :: Id -> CoreExpr -> Message
734 mkRhsPrimMsg binder rhs
735 = vcat [hsep [ptext SLIT("The type of this binder is primitive:"),
737 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]
740 mkUnboxedTupleMsg :: Id -> Message
741 mkUnboxedTupleMsg binder
742 = vcat [hsep [ptext SLIT("A variable has unboxed tuple type:"), ppr binder],
743 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]]
745 mkCoerceErr from_ty expr_ty
746 = vcat [ptext SLIT("From-type of Coerce differs from type of enclosed expression"),
747 ptext SLIT("From-type:") <+> ppr from_ty,
748 ptext SLIT("Type of enclosed expr:") <+> ppr expr_ty
752 = ptext SLIT("Type where expression expected:") <+> ppr e