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"
15 import IO ( hPutStr, hPutStrLn, stderr )
17 import CmdLineOpts ( opt_D_show_passes, opt_DoCoreLinting, opt_PprStyle_Debug )
19 import CoreFVs ( idFreeVars )
20 import CoreUtils ( exprOkForSpeculation )
23 import Const ( Con(..), DataCon, conType, conOkForApp, conOkForAlt )
24 import Id ( isConstantId, idMustBeINLINEd )
25 import Var ( IdOrTyVar, Id, TyVar, idType, tyVarKind, isTyVar, isId )
27 import Subst ( mkTyVarSubst, substTy )
28 import Name ( isLocallyDefined, getSrcLoc )
30 import ErrUtils ( doIfSet, dumpIfSet, ghcExit, Message,
31 ErrMsg, addErrLocHdrLine, pprBagOfErrors )
32 import PrimRep ( PrimRep(..) )
33 import SrcLoc ( SrcLoc, noSrcLoc, isNoSrcLoc )
34 import Type ( Type, Kind, tyVarsOfType,
35 splitFunTy_maybe, mkPiType, mkTyVarTy, unUsgTy,
36 splitForAllTy_maybe, splitTyConApp_maybe,
37 isUnLiftedType, typeKind,
38 splitAlgTyConApp_maybe,
42 import TyCon ( TyCon, isPrimTyCon, tyConDataCons )
43 import BasicTypes ( RecFlag(..), isNonRec )
46 infixr 9 `thenL`, `seqL`
49 %************************************************************************
51 \subsection{Start and end pass}
53 %************************************************************************
55 @beginPass@ and @endPass@ don't really belong here, but it makes a convenient
56 place for them. They print out stuff before and after core passes,
57 and do Core Lint when necessary.
60 beginPass :: String -> IO ()
63 = hPutStrLn stderr ("*** " ++ pass_name)
68 endPass :: String -> Bool -> [CoreBind] -> IO [CoreBind]
69 endPass pass_name dump_flag binds
71 -- Report result size if required
72 -- This has the side effect of forcing the intermediate to be evaluated
73 if opt_D_show_passes then
74 hPutStrLn stderr (" Result size = " ++ show (coreBindsSize binds))
78 -- Report verbosely, if required
79 dumpIfSet dump_flag pass_name
80 (pprCoreBindings binds)
83 lintCoreBindings pass_name binds
89 %************************************************************************
91 \subsection[lintCoreBindings]{@lintCoreBindings@: Top-level interface}
93 %************************************************************************
95 Checks that a set of core bindings is well-formed. The PprStyle and String
96 just control what we print in the event of an error. The Bool value
97 indicates whether we have done any specialisation yet (in which case we do
102 (b) Out-of-scope type variables
103 (c) Out-of-scope local variables
106 If we have done specialisation the we check that there are
107 (a) No top-level bindings of primitive (unboxed type)
112 -- Things are *not* OK if:
114 -- * Unsaturated type app before specialisation has been done;
116 -- * Oversaturated type app after specialisation (eta reduction
117 -- may well be happening...);
120 lintCoreBindings :: String -> [CoreBind] -> IO ()
122 lintCoreBindings whoDunnit binds
123 | not opt_DoCoreLinting
126 lintCoreBindings whoDunnit binds
127 = case (initL (lint_binds binds)) of
128 Nothing -> doIfSet opt_D_show_passes
129 (hPutStr stderr ("*** Core Linted result of " ++ whoDunnit ++ "\n"))
131 Just bad_news -> printDump (display bad_news) >>
134 -- Put all the top-level binders in scope at the start
135 -- This is because transformation rules can bring something
136 -- into use 'unexpectedly'
137 lint_binds binds = addInScopeVars (bindersOfBinds binds) $
140 lint_bind (Rec prs) = mapL (lintSingleBinding Recursive) prs `seqL`
142 lint_bind (NonRec bndr rhs) = lintSingleBinding NonRecursive (bndr,rhs)
146 text ("*** Core Lint Errors: in result of " ++ whoDunnit ++ " ***"),
148 ptext SLIT("*** Offending Program ***"),
149 pprCoreBindings binds,
150 ptext SLIT("*** End of Offense ***")
154 %************************************************************************
156 \subsection[lintUnfolding]{lintUnfolding}
158 %************************************************************************
160 We use this to check all unfoldings that come in from interfaces
161 (it is very painful to catch errors otherwise):
164 lintUnfolding :: SrcLoc
165 -> [IdOrTyVar] -- Treat these as in scope
167 -> Maybe Message -- Nothing => OK
169 lintUnfolding locn vars expr
170 | not opt_DoCoreLinting
174 = initL (addLoc (ImportedUnfolding locn) $
175 addInScopeVars vars $
179 %************************************************************************
181 \subsection[lintCoreBinding]{lintCoreBinding}
183 %************************************************************************
185 Check a core binding, returning the list of variables bound.
188 lintSingleBinding rec_flag (binder,rhs)
189 = addLoc (RhsOf binder) $
192 lintCoreExpr rhs `thenL` \ ty ->
194 -- Check match to RHS type
195 lintBinder binder `seqL`
196 checkTys binder_ty ty (mkRhsMsg binder ty) `seqL`
198 -- Check (not isUnLiftedType) (also checks for bogus unboxed tuples)
199 checkL (not (isUnLiftedType binder_ty) || (isNonRec rec_flag && exprOkForSpeculation rhs))
200 (mkRhsPrimMsg binder rhs) `seqL`
202 -- Check whether binder's specialisations contain any out-of-scope variables
203 mapL (checkBndrIdInScope binder) bndr_vars `seqL`
206 -- We should check the unfolding, if any, but this is tricky because
207 -- the unfolding is a SimplifiableCoreExpr. Give up for now.
209 binder_ty = idType binder
210 bndr_vars = varSetElems (idFreeVars binder)
213 %************************************************************************
215 \subsection[lintCoreExpr]{lintCoreExpr}
217 %************************************************************************
220 lintCoreExpr :: CoreExpr -> LintM Type
222 lintCoreExpr (Var var)
223 | isConstantId var = returnL (idType var)
224 -- Micro-hack here... Class decls generate applications of their
225 -- dictionary constructor, but don't generate a binding for the
226 -- constructor (since it would never be used). After a single round
227 -- of simplification, these dictionary constructors have been
228 -- inlined (from their UnfoldInfo) to CoCons. Just between
229 -- desugaring and simplfication, though, they appear as naked, unbound
230 -- variables as the function in an application.
231 -- The hack here simply doesn't check for out-of-scope-ness for
232 -- data constructors (at least, in a function position).
233 -- Ditto primitive Ids
235 | otherwise = checkIdInScope var `seqL` returnL (idType var)
237 lintCoreExpr (Note (Coerce to_ty from_ty) expr)
238 = lintCoreExpr expr `thenL` \ expr_ty ->
240 lintTy from_ty `seqL`
241 checkTys from_ty (unUsgTy expr_ty) (mkCoerceErr from_ty expr_ty) `seqL`
244 lintCoreExpr (Note other_note expr)
247 lintCoreExpr (Let (NonRec bndr rhs) body)
248 = lintSingleBinding NonRecursive (bndr,rhs) `seqL`
249 addLoc (BodyOfLetRec [bndr])
250 (addInScopeVars [bndr] (lintCoreExpr body))
252 lintCoreExpr (Let (Rec pairs) body)
253 = addInScopeVars bndrs $
254 mapL (lintSingleBinding Recursive) pairs `seqL`
255 addLoc (BodyOfLetRec bndrs) (lintCoreExpr body)
257 bndrs = map fst pairs
259 lintCoreExpr e@(Con con args)
260 = addLoc (AnExpr e) $
261 checkL (conOkForApp con) (mkConAppMsg e) `seqL`
262 lintCoreArgs (conType con) args
264 lintCoreExpr e@(App fun arg)
265 = lintCoreExpr fun `thenL` \ ty ->
269 lintCoreExpr (Lam var expr)
270 = addLoc (LambdaBodyOf var) $
271 checkL (not (isUnboxedTupleType (idType var))) (mkUnboxedTupleMsg var)
273 (addInScopeVars [var] $
274 lintCoreExpr expr `thenL` \ ty ->
275 returnL (mkPiType var ty))
277 lintCoreExpr e@(Case scrut var alts)
278 = -- Check the scrutinee
279 lintCoreExpr scrut `thenL` \ scrut_ty ->
282 lintBinder var `seqL`
284 -- If this is an unboxed tuple case, then the binder must be dead
286 checkL (if isUnboxedTupleType (idType var)
287 then isDeadBinder var
288 else True) (mkUnboxedTupleMsg var) `seqL`
291 checkTys (idType var) scrut_ty (mkScrutMsg var scrut_ty) `seqL`
293 addInScopeVars [var] (
295 -- Check the alternatives
296 checkAllCasesCovered e scrut_ty alts `seqL`
297 mapL (lintCoreAlt scrut_ty) alts `thenL` \ (alt_ty : alt_tys) ->
298 mapL (check alt_ty) alt_tys `seqL`
301 check alt_ty1 alt_ty2 = checkTys alt_ty1 alt_ty2 (mkCaseAltMsg e)
303 lintCoreExpr e@(Type ty)
304 = addErrL (mkStrangeTyMsg e)
307 %************************************************************************
309 \subsection[lintCoreArgs]{lintCoreArgs}
311 %************************************************************************
313 The boolean argument indicates whether we should flag type
314 applications to primitive types as being errors.
317 lintCoreArgs :: Type -> [CoreArg] -> LintM Type
319 lintCoreArgs ty [] = returnL ty
320 lintCoreArgs ty (a : args)
321 = lintCoreArg ty a `thenL` \ res ->
322 lintCoreArgs res args
326 lintCoreArg :: Type -> CoreArg -> LintM Type
328 lintCoreArg ty a@(Type arg_ty)
329 = lintTy arg_ty `seqL`
332 lintCoreArg fun_ty arg
333 = -- Make sure function type matches argument
334 lintCoreExpr arg `thenL` \ arg_ty ->
335 case (splitFunTy_maybe fun_ty) of
336 Just (arg,res) | (arg_ty == arg) -> returnL res
337 _ -> addErrL (mkAppMsg fun_ty arg_ty)
342 = case splitForAllTy_maybe ty of
343 Nothing -> addErrL (mkTyAppMsg ty arg_ty)
347 tyvar_kind = tyVarKind tyvar
348 argty_kind = typeKind arg_ty
350 if argty_kind `hasMoreBoxityInfo` tyvar_kind
351 -- Arg type might be boxed for a function with an uncommitted
352 -- tyvar; notably this is used so that we can give
353 -- error :: forall a:*. String -> a
354 -- and then apply it to both boxed and unboxed types.
356 returnL (substTy (mkTyVarSubst [tyvar] [arg_ty]) body)
358 addErrL (mkKindErrMsg tyvar arg_ty)
363 lintTyApps fun_ty (arg_ty : arg_tys)
364 = lintTyApp fun_ty arg_ty `thenL` \ fun_ty' ->
365 lintTyApps fun_ty' arg_tys
370 %************************************************************************
372 \subsection[lintCoreAlts]{lintCoreAlts}
374 %************************************************************************
377 checkAllCasesCovered e ty [] = addErrL (mkNullAltsMsg e)
379 checkAllCasesCovered e ty [(DEFAULT,_,_)] = nopL
381 checkAllCasesCovered e scrut_ty alts
382 = case splitTyConApp_maybe scrut_ty of {
383 Nothing -> addErrL (badAltsMsg e);
384 Just (tycon, tycon_arg_tys) ->
386 if isPrimTyCon tycon then
387 checkL (hasDefault alts) (nonExhaustiveAltsMsg e)
391 -- Algebraic cases are not necessarily exhaustive, because
392 -- the simplifer correctly eliminates case that can't
394 -- This code just emits a message to say so
396 missing_cons = filter not_in_alts (tyConDataCons tycon)
397 not_in_alts con = all (not_in_alt con) alts
398 not_in_alt con (DataCon con', _, _) = con /= con'
399 not_in_alt con other = True
401 case_bndr = case e of { Case _ bndr alts -> bndr }
403 if not (hasDefault alts || null missing_cons) then
404 pprTrace "Exciting (but not a problem)! Non-exhaustive case:"
405 (ppr case_bndr <+> ppr missing_cons)
412 hasDefault [] = False
413 hasDefault ((DEFAULT,_,_) : alts) = True
414 hasDefault (alt : alts) = hasDefault alts
418 lintCoreAlt :: Type -- Type of scrutinee
420 -> LintM Type -- Type of alternatives
422 lintCoreAlt scrut_ty alt@(DEFAULT, args, rhs)
423 = checkL (null args) (mkDefaultArgsMsg args) `seqL`
426 lintCoreAlt scrut_ty alt@(con, args, rhs)
427 = addLoc (CaseAlt alt) (
429 checkL (conOkForAlt con) (mkConAltMsg con) `seqL`
431 mapL (\arg -> checkL (not (isUnboxedTupleType (idType arg)))
432 (mkUnboxedTupleMsg arg)) args `seqL`
434 addInScopeVars args (
437 -- Scrutinee type must be a tycon applicn; checked by caller
438 -- This code is remarkably compact considering what it does!
439 -- NB: args must be in scope here so that the lintCoreArgs line works.
440 case splitTyConApp_maybe scrut_ty of { Just (tycon, tycon_arg_tys) ->
441 lintTyApps (conType con) tycon_arg_tys `thenL` \ con_type ->
442 lintCoreArgs con_type (map mk_arg args) `thenL` \ con_result_ty ->
443 checkTys con_result_ty scrut_ty (mkBadPatMsg con_result_ty scrut_ty)
450 mk_arg b | isTyVar b = Type (mkTyVarTy b)
454 %************************************************************************
456 \subsection[lint-types]{Types}
458 %************************************************************************
461 lintBinder :: IdOrTyVar -> LintM ()
463 -- ToDo: lint its type
465 lintTy :: Type -> LintM ()
466 lintTy ty = mapL checkIdInScope (varSetElems (tyVarsOfType ty)) `seqL`
468 -- ToDo: check the kind structure of the type
472 %************************************************************************
474 \subsection[lint-monad]{The Lint monad}
476 %************************************************************************
479 type LintM a = [LintLocInfo] -- Locations
480 -> IdSet -- Local vars in scope
481 -> Bag ErrMsg -- Error messages so far
482 -> (Maybe a, Bag ErrMsg) -- Result and error messages (if any)
485 = RhsOf Id -- The variable bound
486 | LambdaBodyOf Id -- The lambda-binder
487 | BodyOfLetRec [Id] -- One of the binders
488 | CaseAlt CoreAlt -- Pattern of a case alternative
489 | AnExpr CoreExpr -- Some expression
490 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
494 initL :: LintM a -> Maybe Message
496 = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
497 if isEmptyBag errs then
500 Just (pprBagOfErrors errs)
503 returnL :: a -> LintM a
504 returnL r loc scope errs = (Just r, errs)
507 nopL loc scope errs = (Nothing, errs)
509 thenL :: LintM a -> (a -> LintM b) -> LintM b
510 thenL m k loc scope errs
511 = case m loc scope errs of
512 (Just r, errs') -> k r loc scope errs'
513 (Nothing, errs') -> (Nothing, errs')
515 seqL :: LintM a -> LintM b -> LintM b
516 seqL m k loc scope errs
517 = case m loc scope errs of
518 (_, errs') -> k loc scope errs'
520 mapL :: (a -> LintM b) -> [a] -> LintM [b]
521 mapL f [] = returnL []
524 mapL f xs `thenL` \ rs ->
529 checkL :: Bool -> Message -> LintM ()
530 checkL True msg loc scope errs = (Nothing, errs)
531 checkL False msg loc scope errs = (Nothing, addErr errs msg loc)
533 addErrL :: Message -> LintM a
534 addErrL msg loc scope errs = (Nothing, addErr errs msg loc)
536 addErr :: Bag ErrMsg -> Message -> [LintLocInfo] -> Bag ErrMsg
538 addErr errs_so_far msg locs
539 = ASSERT (not (null locs))
540 errs_so_far `snocBag` mk_msg msg
542 (loc, cxt1) = dumpLoc (head locs)
543 cxts = [snd (dumpLoc loc) | loc <- locs]
544 context | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1
548 | isNoSrcLoc loc = (loc, hang context 4 msg)
549 | otherwise = addErrLocHdrLine loc context msg
551 addLoc :: LintLocInfo -> LintM a -> LintM a
552 addLoc extra_loc m loc scope errs
553 = m (extra_loc:loc) scope errs
555 addInScopeVars :: [IdOrTyVar] -> LintM a -> LintM a
556 addInScopeVars ids m loc scope errs
557 = m loc (scope `unionVarSet` mkVarSet ids) errs
561 checkIdInScope :: IdOrTyVar -> LintM ()
563 = checkInScope (ptext SLIT("is out of scope")) id
565 checkBndrIdInScope :: IdOrTyVar -> IdOrTyVar -> LintM ()
566 checkBndrIdInScope binder id
567 = checkInScope msg id
569 msg = ptext SLIT("is out of scope inside info for") <+>
572 checkInScope :: SDoc -> IdOrTyVar -> LintM ()
573 checkInScope loc_msg var loc scope errs
574 | isLocallyDefined var
575 && not (var `elemVarSet` scope)
576 && not (isId var && idMustBeINLINEd var) -- Constructors and dict selectors
577 -- don't have bindings,
578 -- just MustInline prags
579 = (Nothing, addErr errs (hsep [ppr var, loc_msg]) loc)
583 checkTys :: Type -> Type -> Message -> LintM ()
584 checkTys ty1 ty2 msg loc scope errs
585 | ty1 == ty2 = (Nothing, errs)
586 | otherwise = (Nothing, addErr errs msg loc)
590 %************************************************************************
592 \subsection{Error messages}
594 %************************************************************************
598 = (getSrcLoc v, brackets (ptext SLIT("RHS of") <+> pp_binders [v]))
600 dumpLoc (LambdaBodyOf b)
601 = (getSrcLoc b, brackets (ptext SLIT("in body of lambda with binder") <+> pp_binder b))
603 dumpLoc (BodyOfLetRec bs)
604 = ( getSrcLoc (head bs), brackets (ptext SLIT("in body of letrec with binders") <+> pp_binders bs))
607 = (noSrcLoc, text "In the expression:" <+> ppr e)
609 dumpLoc (CaseAlt (con, args, rhs))
610 = (noSrcLoc, text "In a case pattern:" <+> parens (ppr con <+> ppr args))
612 dumpLoc (ImportedUnfolding locn)
613 = (locn, brackets (ptext SLIT("in an imported unfolding")))
615 pp_binders :: [Id] -> SDoc
616 pp_binders bs = sep (punctuate comma (map pp_binder bs))
618 pp_binder :: Id -> SDoc
619 pp_binder b = hsep [ppr b, dcolon, ppr (idType b)]
623 ------------------------------------------------------
624 -- Messages for case expressions
626 mkConAppMsg :: CoreExpr -> Message
628 = hang (text "Application of newtype constructor:")
631 mkConAltMsg :: Con -> Message
633 = text "PrimOp in case pattern:" <+> ppr con
635 mkNullAltsMsg :: CoreExpr -> Message
637 = hang (text "Case expression with no alternatives:")
640 mkDefaultArgsMsg :: [IdOrTyVar] -> Message
641 mkDefaultArgsMsg args
642 = hang (text "DEFAULT case with binders")
645 mkCaseAltMsg :: CoreExpr -> Message
647 = hang (text "Type of case alternatives not the same:")
650 mkScrutMsg :: Id -> Type -> Message
651 mkScrutMsg var scrut_ty
652 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
653 text "Result binder type:" <+> ppr (idType var),
654 text "Scrutinee type:" <+> ppr scrut_ty]
656 badAltsMsg :: CoreExpr -> Message
658 = hang (text "Case statement scrutinee is not a data type:")
661 nonExhaustiveAltsMsg :: CoreExpr -> Message
662 nonExhaustiveAltsMsg e
663 = hang (text "Case expression with non-exhaustive alternatives")
666 mkBadPatMsg :: Type -> Type -> Message
667 mkBadPatMsg con_result_ty scrut_ty
669 text "In a case alternative, pattern result type doesn't match scrutinee type:",
670 text "Pattern result type:" <+> ppr con_result_ty,
671 text "Scrutinee type:" <+> ppr scrut_ty
674 ------------------------------------------------------
675 -- Other error messages
677 mkAppMsg :: Type -> Type -> Message
679 = vcat [ptext SLIT("Argument value doesn't match argument type:"),
680 hang (ptext SLIT("Fun type:")) 4 (ppr fun),
681 hang (ptext SLIT("Arg type:")) 4 (ppr arg)]
683 mkKindErrMsg :: TyVar -> Type -> Message
684 mkKindErrMsg tyvar arg_ty
685 = vcat [ptext SLIT("Kinds don't match in type application:"),
686 hang (ptext SLIT("Type variable:"))
687 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
688 hang (ptext SLIT("Arg type:"))
689 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
691 mkTyAppMsg :: Type -> Type -> Message
693 = vcat [text "Illegal type application:",
694 hang (ptext SLIT("Exp type:"))
695 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
696 hang (ptext SLIT("Arg type:"))
697 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
699 mkRhsMsg :: Id -> Type -> Message
702 [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
704 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
705 hsep [ptext SLIT("Rhs type:"), ppr ty]]
707 mkRhsPrimMsg :: Id -> CoreExpr -> Message
708 mkRhsPrimMsg binder rhs
709 = vcat [hsep [ptext SLIT("The type of this binder is primitive:"),
711 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]
714 mkUnboxedTupleMsg :: Id -> Message
715 mkUnboxedTupleMsg binder
716 = vcat [hsep [ptext SLIT("A variable has unboxed tuple type:"), ppr binder],
717 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]]
719 mkCoerceErr from_ty expr_ty
720 = vcat [ptext SLIT("From-type of Coerce differs from type of enclosed expression"),
721 ptext SLIT("From-type:") <+> ppr from_ty,
722 ptext SLIT("Type of enclosed expr:") <+> ppr expr_ty
726 = ptext SLIT("Type where expression expected:") <+> ppr e