2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[CoreLint]{A ``lint'' pass to check for Core correctness}
13 #include "HsVersions.h"
16 import CoreFVs ( idFreeVars )
17 import CoreUtils ( findDefault, exprOkForSpeculation, coreBindsSize, mkPiType )
20 import Literal ( literalType )
21 import DataCon ( dataConRepType )
22 import Var ( Var, Id, TyVar, idType, tyVarKind, isTyVar, isId, mustHaveLocalBinding )
24 import Subst ( substTyWith )
25 import Name ( getSrcLoc )
27 import ErrUtils ( dumpIfSet_core, ghcExit, Message, showPass,
29 import SrcLoc ( SrcLoc, noSrcLoc )
30 import Type ( Type, tyVarsOfType, eqType,
31 splitFunTy_maybe, mkTyVarTy,
32 splitForAllTy_maybe, splitTyConApp_maybe, splitTyConApp,
33 isUnLiftedType, typeKind,
37 import TyCon ( isPrimTyCon )
38 import BasicTypes ( RecFlag(..), isNonRec )
43 import IO ( hPutStrLn, stderr )
45 infixr 9 `thenL`, `seqL`
48 %************************************************************************
52 %************************************************************************
54 @showPass@ and @endPass@ don't really belong here, but it makes a convenient
55 place for them. They print out stuff before and after core passes,
56 and do Core Lint when necessary.
59 endPass :: DynFlags -> String -> DynFlag -> [CoreBind] -> IO [CoreBind]
60 endPass dflags pass_name dump_flag binds
62 -- Report result size if required
63 -- This has the side effect of forcing the intermediate to be evaluated
64 if verbosity dflags >= 2 then
65 hPutStrLn stderr (" Result size = " ++ show (coreBindsSize binds))
69 -- Report verbosely, if required
70 dumpIfSet_core dflags dump_flag pass_name (pprCoreBindings binds)
73 lintCoreBindings dflags pass_name binds
79 %************************************************************************
81 \subsection[lintCoreBindings]{@lintCoreBindings@: Top-level interface}
83 %************************************************************************
85 Checks that a set of core bindings is well-formed. The PprStyle and String
86 just control what we print in the event of an error. The Bool value
87 indicates whether we have done any specialisation yet (in which case we do
92 (b) Out-of-scope type variables
93 (c) Out-of-scope local variables
96 If we have done specialisation the we check that there are
97 (a) No top-level bindings of primitive (unboxed type)
102 -- Things are *not* OK if:
104 -- * Unsaturated type app before specialisation has been done;
106 -- * Oversaturated type app after specialisation (eta reduction
107 -- may well be happening...);
110 lintCoreBindings :: DynFlags -> String -> [CoreBind] -> IO ()
112 lintCoreBindings dflags whoDunnit binds
113 | not (dopt Opt_DoCoreLinting dflags)
116 lintCoreBindings dflags whoDunnit binds
117 = case (initL (lint_binds binds)) of
118 Nothing -> showPass dflags ("Core Linted result of " ++ whoDunnit)
119 Just bad_news -> printDump (display bad_news) >>
122 -- Put all the top-level binders in scope at the start
123 -- This is because transformation rules can bring something
124 -- into use 'unexpectedly'
125 lint_binds binds = addInScopeVars (bindersOfBinds binds) $
128 lint_bind (Rec prs) = mapL (lintSingleBinding Recursive) prs `seqL`
130 lint_bind (NonRec bndr rhs) = lintSingleBinding NonRecursive (bndr,rhs)
133 = vcat [ text ("*** Core Lint Errors: in result of " ++ whoDunnit ++ " ***"),
135 ptext SLIT("*** Offending Program ***"),
136 pprCoreBindings binds,
137 ptext SLIT("*** End of Offense ***")
141 %************************************************************************
143 \subsection[lintUnfolding]{lintUnfolding}
145 %************************************************************************
147 We use this to check all unfoldings that come in from interfaces
148 (it is very painful to catch errors otherwise):
151 lintUnfolding :: SrcLoc
152 -> [Var] -- Treat these as in scope
154 -> Maybe Message -- Nothing => OK
156 lintUnfolding locn vars expr
157 = initL (addLoc (ImportedUnfolding locn) $
158 addInScopeVars vars $
162 %************************************************************************
164 \subsection[lintCoreBinding]{lintCoreBinding}
166 %************************************************************************
168 Check a core binding, returning the list of variables bound.
171 lintSingleBinding rec_flag (binder,rhs)
172 = addLoc (RhsOf binder) $
175 lintCoreExpr rhs `thenL` \ ty ->
177 -- Check match to RHS type
178 lintBinder binder `seqL`
179 checkTys binder_ty ty (mkRhsMsg binder ty) `seqL`
181 -- Check (not isUnLiftedType) (also checks for bogus unboxed tuples)
182 checkL (not (isUnLiftedType binder_ty)
183 || (isNonRec rec_flag && exprOkForSpeculation rhs))
184 (mkRhsPrimMsg binder rhs) `seqL`
186 -- Check whether binder's specialisations contain any out-of-scope variables
187 mapL (checkBndrIdInScope binder) bndr_vars `seqL`
190 -- We should check the unfolding, if any, but this is tricky because
191 -- the unfolding is a SimplifiableCoreExpr. Give up for now.
193 binder_ty = idType binder
194 bndr_vars = varSetElems (idFreeVars binder)
197 %************************************************************************
199 \subsection[lintCoreExpr]{lintCoreExpr}
201 %************************************************************************
204 lintCoreExpr :: CoreExpr -> LintM Type
206 lintCoreExpr (Var var) = checkIdInScope var `seqL` returnL (idType var)
207 lintCoreExpr (Lit lit) = returnL (literalType lit)
209 lintCoreExpr (Note (Coerce to_ty from_ty) expr)
210 = lintCoreExpr expr `thenL` \ expr_ty ->
212 lintTy from_ty `seqL`
213 checkTys from_ty expr_ty (mkCoerceErr from_ty expr_ty) `seqL`
216 lintCoreExpr (Note other_note expr)
219 lintCoreExpr (Let (NonRec bndr rhs) body)
220 = lintSingleBinding NonRecursive (bndr,rhs) `seqL`
221 addLoc (BodyOfLetRec [bndr])
222 (addInScopeVars [bndr] (lintCoreExpr body))
224 lintCoreExpr (Let (Rec pairs) body)
225 = addInScopeVars bndrs $
226 mapL (lintSingleBinding Recursive) pairs `seqL`
227 addLoc (BodyOfLetRec bndrs) (lintCoreExpr body)
229 bndrs = map fst pairs
231 lintCoreExpr e@(App fun arg)
232 = lintCoreExpr fun `thenL` \ ty ->
236 lintCoreExpr (Lam var expr)
237 = addLoc (LambdaBodyOf var) $
239 checkL (not (isUnboxedTupleType (idType var))) (mkUnboxedTupleMsg var)
243 (addInScopeVars [var] $
244 lintCoreExpr expr `thenL` \ ty ->
246 returnL (mkPiType var ty))
248 lintCoreExpr e@(Case scrut var alts)
249 = -- Check the scrutinee
250 lintCoreExpr scrut `thenL` \ scrut_ty ->
253 lintBinder var `seqL`
255 -- If this is an unboxed tuple case, then the binder must be dead
257 checkL (if isUnboxedTupleType (idType var)
258 then isDeadBinder var
259 else True) (mkUnboxedTupleMsg var) `seqL`
262 checkTys (idType var) scrut_ty (mkScrutMsg var scrut_ty) `seqL`
264 addInScopeVars [var] (
266 -- Check the alternatives
267 checkCaseAlts e scrut_ty alts `seqL`
269 mapL (lintCoreAlt scrut_ty) alts `thenL` \ (alt_ty : alt_tys) ->
270 mapL (check alt_ty) alt_tys `seqL`
273 check alt_ty1 alt_ty2 = checkTys alt_ty1 alt_ty2 (mkCaseAltMsg e)
275 lintCoreExpr e@(Type ty)
276 = addErrL (mkStrangeTyMsg e)
279 %************************************************************************
281 \subsection[lintCoreArgs]{lintCoreArgs}
283 %************************************************************************
285 The basic version of these functions checks that the argument is a
286 subtype of the required type, as one would expect.
289 lintCoreArgs :: Type -> [CoreArg] -> LintM Type
290 lintCoreArgs = lintCoreArgs0 checkTys
292 lintCoreArg :: Type -> CoreArg -> LintM Type
293 lintCoreArg = lintCoreArg0 checkTys
296 The primitive version of these functions takes a check argument,
297 allowing a different comparison.
300 lintCoreArgs0 check_tys ty [] = returnL ty
301 lintCoreArgs0 check_tys ty (a : args)
302 = lintCoreArg0 check_tys ty a `thenL` \ res ->
303 lintCoreArgs0 check_tys res args
305 lintCoreArg0 check_tys ty a@(Type arg_ty)
306 = lintTy arg_ty `seqL`
309 lintCoreArg0 check_tys fun_ty arg
310 = -- Make sure function type matches argument
311 lintCoreExpr arg `thenL` \ arg_ty ->
313 err = mkAppMsg fun_ty arg_ty
315 case splitFunTy_maybe fun_ty of
316 Just (arg,res) -> check_tys arg arg_ty err `seqL`
323 = case splitForAllTy_maybe ty of
324 Nothing -> addErrL (mkTyAppMsg ty arg_ty)
327 if not (isTyVar tyvar) then addErrL (mkTyAppMsg ty arg_ty) else
329 tyvar_kind = tyVarKind tyvar
330 argty_kind = typeKind arg_ty
332 if argty_kind `hasMoreBoxityInfo` tyvar_kind
333 -- Arg type might be boxed for a function with an uncommitted
334 -- tyvar; notably this is used so that we can give
335 -- error :: forall a:*. String -> a
336 -- and then apply it to both boxed and unboxed types.
338 returnL (substTyWith [tyvar] [arg_ty] body)
340 addErrL (mkKindErrMsg tyvar arg_ty)
345 lintTyApps fun_ty (arg_ty : arg_tys)
346 = lintTyApp fun_ty arg_ty `thenL` \ fun_ty' ->
347 lintTyApps fun_ty' arg_tys
352 %************************************************************************
354 \subsection[lintCoreAlts]{lintCoreAlts}
356 %************************************************************************
359 checkCaseAlts :: CoreExpr -> Type -> [CoreAlt] -> LintM ()
360 -- a) Check that the alts are non-empty
361 -- b) Check that the DEFAULT comes first, if it exists
362 -- c) Check that there's a default for infinite types
363 -- NB: Algebraic cases are not necessarily exhaustive, because
364 -- the simplifer correctly eliminates case that can't
367 checkCaseAlts e ty []
368 = addErrL (mkNullAltsMsg e)
370 checkCaseAlts e ty alts
371 = checkL (all non_deflt con_alts) (mkNonDefltMsg e) `seqL`
372 checkL (isJust maybe_deflt || not is_infinite_ty)
373 (nonExhaustiveAltsMsg e)
375 (con_alts, maybe_deflt) = findDefault alts
377 non_deflt (DEFAULT, _, _) = False
380 is_infinite_ty = case splitTyConApp_maybe ty of
382 Just (tycon, tycon_arg_tys) -> isPrimTyCon tycon
386 lintCoreAlt :: Type -- Type of scrutinee
388 -> LintM Type -- Type of alternatives
390 lintCoreAlt scrut_ty alt@(DEFAULT, args, rhs)
391 = checkL (null args) (mkDefaultArgsMsg args) `seqL`
394 lintCoreAlt scrut_ty alt@(LitAlt lit, args, rhs)
395 = checkL (null args) (mkDefaultArgsMsg args) `seqL`
396 checkTys lit_ty scrut_ty
397 (mkBadPatMsg lit_ty scrut_ty) `seqL`
400 lit_ty = literalType lit
402 lintCoreAlt scrut_ty alt@(DataAlt con, args, rhs)
403 = addLoc (CaseAlt alt) (
405 mapL (\arg -> checkL (not (isUnboxedTupleType (idType arg)))
406 (mkUnboxedTupleMsg arg)) args `seqL`
408 addInScopeVars args (
411 -- Scrutinee type must be a tycon applicn; checked by caller
412 -- This code is remarkably compact considering what it does!
413 -- NB: args must be in scope here so that the lintCoreArgs line works.
414 -- NB: relies on existential type args coming *after* ordinary type args
415 case splitTyConApp scrut_ty of { (tycon, tycon_arg_tys) ->
416 lintTyApps (dataConRepType con) tycon_arg_tys `thenL` \ con_type ->
417 lintCoreArgs con_type (map mk_arg args) `thenL` \ con_result_ty ->
418 checkTys con_result_ty scrut_ty (mkBadPatMsg con_result_ty scrut_ty)
425 mk_arg b | isTyVar b = Type (mkTyVarTy b)
427 | otherwise = pprPanic "lintCoreAlt:mk_arg " (ppr b)
430 %************************************************************************
432 \subsection[lint-types]{Types}
434 %************************************************************************
437 lintBinder :: Var -> LintM ()
439 -- ToDo: lint its type
440 -- ToDo: lint its rules
442 lintTy :: Type -> LintM ()
443 lintTy ty = mapL checkIdInScope (varSetElems (tyVarsOfType ty)) `seqL`
445 -- ToDo: check the kind structure of the type
449 %************************************************************************
451 \subsection[lint-monad]{The Lint monad}
453 %************************************************************************
456 type LintM a = [LintLocInfo] -- Locations
457 -> IdSet -- Local vars in scope
458 -> Bag Message -- Error messages so far
459 -> (Maybe a, Bag Message) -- Result and error messages (if any)
462 = RhsOf Id -- The variable bound
463 | LambdaBodyOf Id -- The lambda-binder
464 | BodyOfLetRec [Id] -- One of the binders
465 | CaseAlt CoreAlt -- Pattern of a case alternative
466 | AnExpr CoreExpr -- Some expression
467 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
471 initL :: LintM a -> Maybe Message {- errors -}
473 = case m [] emptyVarSet emptyBag of
474 (_, errs) | isEmptyBag errs -> Nothing
475 | otherwise -> Just (vcat (punctuate (text "") (bagToList errs)))
477 returnL :: a -> LintM a
478 returnL r loc scope errs = (Just r, errs)
481 nopL loc scope errs = (Nothing, errs)
483 thenL :: LintM a -> (a -> LintM b) -> LintM b
484 thenL m k loc scope errs
485 = case m loc scope errs of
486 (Just r, errs') -> k r loc scope errs'
487 (Nothing, errs') -> (Nothing, errs')
489 seqL :: LintM a -> LintM b -> LintM b
490 seqL m k loc scope errs
491 = case m loc scope errs of
492 (_, errs') -> k loc scope errs'
494 mapL :: (a -> LintM b) -> [a] -> LintM [b]
495 mapL f [] = returnL []
498 mapL f xs `thenL` \ rs ->
503 checkL :: Bool -> Message -> LintM ()
504 checkL True msg = nopL
505 checkL False msg = addErrL msg
507 addErrL :: Message -> LintM a
508 addErrL msg loc scope errs = (Nothing, addErr errs msg loc)
510 addErr :: Bag Message -> Message -> [LintLocInfo] -> Bag Message
511 addErr errs_so_far msg locs
512 = ASSERT( notNull locs )
513 errs_so_far `snocBag` mk_msg msg
515 (loc, cxt1) = dumpLoc (head locs)
516 cxts = [snd (dumpLoc loc) | loc <- locs]
517 context | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1
520 mk_msg msg = addErrLocHdrLine loc context msg
522 addLoc :: LintLocInfo -> LintM a -> LintM a
523 addLoc extra_loc m loc scope errs
524 = m (extra_loc:loc) scope errs
526 addInScopeVars :: [Var] -> LintM a -> LintM a
527 addInScopeVars ids m loc scope errs
528 = m loc (scope `unionVarSet` mkVarSet ids) errs
532 checkIdInScope :: Var -> LintM ()
534 = checkInScope (ptext SLIT("is out of scope")) id
536 checkBndrIdInScope :: Var -> Var -> LintM ()
537 checkBndrIdInScope binder id
538 = checkInScope msg id
540 msg = ptext SLIT("is out of scope inside info for") <+>
543 checkInScope :: SDoc -> Var -> LintM ()
544 checkInScope loc_msg var loc scope errs
545 | mustHaveLocalBinding var && not (var `elemVarSet` scope)
546 = (Nothing, addErr errs (hsep [ppr var, loc_msg]) loc)
548 = nopL loc scope errs
550 checkTys :: Type -> Type -> Message -> LintM ()
551 -- check ty2 is subtype of ty1 (ie, has same structure but usage
552 -- annotations need only be consistent, not equal)
554 | ty1 `eqType` ty2 = nopL
555 | otherwise = addErrL msg
559 %************************************************************************
561 \subsection{Error messages}
563 %************************************************************************
567 = (getSrcLoc v, brackets (ptext SLIT("RHS of") <+> pp_binders [v]))
569 dumpLoc (LambdaBodyOf b)
570 = (getSrcLoc b, brackets (ptext SLIT("in body of lambda with binder") <+> pp_binder b))
572 dumpLoc (BodyOfLetRec [])
573 = (noSrcLoc, brackets (ptext SLIT("In body of a letrec with no binders")))
575 dumpLoc (BodyOfLetRec bs@(_:_))
576 = ( getSrcLoc (head bs), brackets (ptext SLIT("in body of letrec with binders") <+> pp_binders bs))
579 = (noSrcLoc, text "In the expression:" <+> ppr e)
581 dumpLoc (CaseAlt (con, args, rhs))
582 = (noSrcLoc, text "In a case pattern:" <+> parens (ppr con <+> ppr args))
584 dumpLoc (ImportedUnfolding locn)
585 = (locn, brackets (ptext SLIT("in an imported unfolding")))
587 pp_binders :: [Var] -> SDoc
588 pp_binders bs = sep (punctuate comma (map pp_binder bs))
590 pp_binder :: Var -> SDoc
591 pp_binder b | isId b = hsep [ppr b, dcolon, ppr (idType b)]
592 | isTyVar b = hsep [ppr b, dcolon, ppr (tyVarKind b)]
596 ------------------------------------------------------
597 -- Messages for case expressions
599 mkNullAltsMsg :: CoreExpr -> Message
601 = hang (text "Case expression with no alternatives:")
604 mkDefaultArgsMsg :: [Var] -> Message
605 mkDefaultArgsMsg args
606 = hang (text "DEFAULT case with binders")
609 mkCaseAltMsg :: CoreExpr -> Message
611 = hang (text "Type of case alternatives not the same:")
614 mkScrutMsg :: Id -> Type -> Message
615 mkScrutMsg var scrut_ty
616 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
617 text "Result binder type:" <+> ppr (idType var),
618 text "Scrutinee type:" <+> ppr scrut_ty]
622 = hang (text "Case expression with DEFAULT not at the beginnning") 4 (ppr e)
624 nonExhaustiveAltsMsg :: CoreExpr -> Message
625 nonExhaustiveAltsMsg e
626 = hang (text "Case expression with non-exhaustive alternatives") 4 (ppr e)
628 mkBadPatMsg :: Type -> Type -> Message
629 mkBadPatMsg con_result_ty scrut_ty
631 text "In a case alternative, pattern result type doesn't match scrutinee type:",
632 text "Pattern result type:" <+> ppr con_result_ty,
633 text "Scrutinee type:" <+> ppr scrut_ty
636 ------------------------------------------------------
637 -- Other error messages
639 mkAppMsg :: Type -> Type -> Message
641 = vcat [ptext SLIT("Argument value doesn't match argument type:"),
642 hang (ptext SLIT("Fun type:")) 4 (ppr fun),
643 hang (ptext SLIT("Arg type:")) 4 (ppr arg)]
645 mkKindErrMsg :: TyVar -> Type -> Message
646 mkKindErrMsg tyvar arg_ty
647 = vcat [ptext SLIT("Kinds don't match in type application:"),
648 hang (ptext SLIT("Type variable:"))
649 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
650 hang (ptext SLIT("Arg type:"))
651 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
653 mkTyAppMsg :: Type -> Type -> Message
655 = vcat [text "Illegal type application:",
656 hang (ptext SLIT("Exp type:"))
657 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
658 hang (ptext SLIT("Arg type:"))
659 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
661 mkRhsMsg :: Id -> Type -> Message
664 [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
666 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
667 hsep [ptext SLIT("Rhs type:"), ppr ty]]
669 mkRhsPrimMsg :: Id -> CoreExpr -> Message
670 mkRhsPrimMsg binder rhs
671 = vcat [hsep [ptext SLIT("The type of this binder is primitive:"),
673 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]
676 mkUnboxedTupleMsg :: Id -> Message
677 mkUnboxedTupleMsg binder
678 = vcat [hsep [ptext SLIT("A variable has unboxed tuple type:"), ppr binder],
679 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]]
681 mkCoerceErr from_ty expr_ty
682 = vcat [ptext SLIT("From-type of Coerce differs from type of enclosed expression"),
683 ptext SLIT("From-type:") <+> ppr from_ty,
684 ptext SLIT("Type of enclosed expr:") <+> ppr expr_ty
688 = ptext SLIT("Type where expression expected:") <+> ppr e