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, 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,
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 = hPutStr stderr ("*** " ++ pass_name ++ "\n")
68 endPass :: String -> Bool -> [CoreBind] -> IO [CoreBind]
69 endPass pass_name dump_flag binds
71 -- Report verbosely, if required
72 dumpIfSet dump_flag pass_name
73 (pprCoreBindings binds)
76 lintCoreBindings pass_name binds
82 %************************************************************************
84 \subsection[lintCoreBindings]{@lintCoreBindings@: Top-level interface}
86 %************************************************************************
88 Checks that a set of core bindings is well-formed. The PprStyle and String
89 just control what we print in the event of an error. The Bool value
90 indicates whether we have done any specialisation yet (in which case we do
95 (b) Out-of-scope type variables
96 (c) Out-of-scope local variables
99 If we have done specialisation the we check that there are
100 (a) No top-level bindings of primitive (unboxed type)
105 -- Things are *not* OK if:
107 -- * Unsaturated type app before specialisation has been done;
109 -- * Oversaturated type app after specialisation (eta reduction
110 -- may well be happening...);
113 lintCoreBindings :: String -> [CoreBind] -> IO ()
115 lintCoreBindings whoDunnit binds
116 | not opt_DoCoreLinting
119 lintCoreBindings whoDunnit binds
120 = case (initL (lint_binds binds)) of
121 Nothing -> doIfSet opt_D_show_passes
122 (hPutStr stderr ("*** Core Linted result of " ++ whoDunnit ++ "\n"))
124 Just bad_news -> printDump (display bad_news) >>
127 -- Put all the top-level binders in scope at the start
128 -- This is because transformation rules can bring something
129 -- into use 'unexpectedly'
130 lint_binds binds = addInScopeVars (bindersOfBinds binds) $
133 lint_bind (Rec prs) = mapL (lintSingleBinding Recursive) prs `seqL`
135 lint_bind (NonRec bndr rhs) = lintSingleBinding NonRecursive (bndr,rhs)
139 text ("*** Core Lint Errors: in result of " ++ whoDunnit ++ " ***"),
141 ptext SLIT("*** Offending Program ***"),
142 pprCoreBindings binds,
143 ptext SLIT("*** End of Offense ***")
147 %************************************************************************
149 \subsection[lintUnfolding]{lintUnfolding}
151 %************************************************************************
153 We use this to check all unfoldings that come in from interfaces
154 (it is very painful to catch errors otherwise):
157 lintUnfolding :: SrcLoc
158 -> [IdOrTyVar] -- Treat these as in scope
160 -> Maybe Message -- Nothing => OK
162 lintUnfolding locn vars expr
163 | not opt_DoCoreLinting
167 = initL (addLoc (ImportedUnfolding locn) $
168 addInScopeVars vars $
172 %************************************************************************
174 \subsection[lintCoreBinding]{lintCoreBinding}
176 %************************************************************************
178 Check a core binding, returning the list of variables bound.
181 lintSingleBinding rec_flag (binder,rhs)
182 = addLoc (RhsOf binder) $
185 lintCoreExpr rhs `thenL` \ ty ->
187 -- Check match to RHS type
188 lintBinder binder `seqL`
189 checkTys binder_ty ty (mkRhsMsg binder ty) `seqL`
191 -- Check (not isUnLiftedType) (also checks for bogus unboxed tuples)
192 checkL (not (isUnLiftedType binder_ty) || (isNonRec rec_flag && exprOkForSpeculation rhs))
193 (mkRhsPrimMsg binder rhs) `seqL`
195 -- Check whether binder's specialisations contain any out-of-scope variables
196 mapL (checkBndrIdInScope binder) bndr_vars `seqL`
199 -- We should check the unfolding, if any, but this is tricky because
200 -- the unfolding is a SimplifiableCoreExpr. Give up for now.
202 binder_ty = idType binder
203 bndr_vars = varSetElems (idFreeVars binder)
206 %************************************************************************
208 \subsection[lintCoreExpr]{lintCoreExpr}
210 %************************************************************************
213 lintCoreExpr :: CoreExpr -> LintM Type
215 lintCoreExpr (Var var)
216 | isConstantId var = returnL (idType var)
217 -- Micro-hack here... Class decls generate applications of their
218 -- dictionary constructor, but don't generate a binding for the
219 -- constructor (since it would never be used). After a single round
220 -- of simplification, these dictionary constructors have been
221 -- inlined (from their UnfoldInfo) to CoCons. Just between
222 -- desugaring and simplfication, though, they appear as naked, unbound
223 -- variables as the function in an application.
224 -- The hack here simply doesn't check for out-of-scope-ness for
225 -- data constructors (at least, in a function position).
226 -- Ditto primitive Ids
228 | otherwise = checkIdInScope var `seqL` returnL (idType var)
230 lintCoreExpr (Note (Coerce to_ty from_ty) expr)
231 = lintCoreExpr expr `thenL` \ expr_ty ->
233 lintTy from_ty `seqL`
234 checkTys from_ty expr_ty (mkCoerceErr from_ty expr_ty) `seqL`
237 lintCoreExpr (Note other_note expr)
240 lintCoreExpr (Let (NonRec bndr rhs) body)
241 = lintSingleBinding NonRecursive (bndr,rhs) `seqL`
242 addLoc (BodyOfLetRec [bndr])
243 (addInScopeVars [bndr] (lintCoreExpr body))
245 lintCoreExpr (Let (Rec pairs) body)
246 = addInScopeVars bndrs $
247 mapL (lintSingleBinding Recursive) pairs `seqL`
248 addLoc (BodyOfLetRec bndrs) (lintCoreExpr body)
250 bndrs = map fst pairs
252 lintCoreExpr e@(Con con args)
253 = addLoc (AnExpr e) $
254 checkL (conOkForApp con) (mkConAppMsg e) `seqL`
255 lintCoreArgs (conType con) args
257 lintCoreExpr e@(App fun arg)
258 = lintCoreExpr fun `thenL` \ ty ->
262 lintCoreExpr (Lam var expr)
263 = addLoc (LambdaBodyOf var) $
264 checkL (not (isUnboxedTupleType (idType var))) (mkUnboxedTupleMsg var)
266 (addInScopeVars [var] $
267 lintCoreExpr expr `thenL` \ ty ->
268 returnL (mkPiType var ty))
270 lintCoreExpr e@(Case scrut var alts)
271 = -- Check the scrutinee
272 lintCoreExpr scrut `thenL` \ scrut_ty ->
275 lintBinder var `seqL`
277 -- If this is an unboxed tuple case, then the binder must be dead
279 checkL (if isUnboxedTupleType (idType var)
280 then isDeadBinder var
281 else True) (mkUnboxedTupleMsg var) `seqL`
284 checkTys (idType var) scrut_ty (mkScrutMsg var scrut_ty) `seqL`
286 addInScopeVars [var] (
288 -- Check the alternatives
289 checkAllCasesCovered e scrut_ty alts `seqL`
290 mapL (lintCoreAlt scrut_ty) alts `thenL` \ (alt_ty : alt_tys) ->
291 mapL (check alt_ty) alt_tys `seqL`
294 check alt_ty1 alt_ty2 = checkTys alt_ty1 alt_ty2 (mkCaseAltMsg e)
296 lintCoreExpr e@(Type ty)
297 = addErrL (mkStrangeTyMsg e)
300 %************************************************************************
302 \subsection[lintCoreArgs]{lintCoreArgs}
304 %************************************************************************
306 The boolean argument indicates whether we should flag type
307 applications to primitive types as being errors.
310 lintCoreArgs :: Type -> [CoreArg] -> LintM Type
312 lintCoreArgs ty [] = returnL ty
313 lintCoreArgs ty (a : args)
314 = lintCoreArg ty a `thenL` \ res ->
315 lintCoreArgs res args
319 lintCoreArg :: Type -> CoreArg -> LintM Type
321 lintCoreArg ty a@(Type arg_ty)
322 = lintTy arg_ty `seqL`
325 lintCoreArg fun_ty arg
326 = -- Make sure function type matches argument
327 lintCoreExpr arg `thenL` \ arg_ty ->
328 case (splitFunTy_maybe fun_ty) of
329 Just (arg,res) | (arg_ty == arg) -> returnL res
330 _ -> addErrL (mkAppMsg fun_ty arg_ty)
335 = case splitForAllTy_maybe ty of
336 Nothing -> addErrL (mkTyAppMsg ty arg_ty)
340 tyvar_kind = tyVarKind tyvar
341 argty_kind = typeKind arg_ty
343 if argty_kind `hasMoreBoxityInfo` tyvar_kind
344 -- Arg type might be boxed for a function with an uncommitted
345 -- tyvar; notably this is used so that we can give
346 -- error :: forall a:*. String -> a
347 -- and then apply it to both boxed and unboxed types.
349 returnL (substTy (mkTyVarSubst [tyvar] [arg_ty]) body)
351 addErrL (mkKindErrMsg tyvar arg_ty)
356 lintTyApps fun_ty (arg_ty : arg_tys)
357 = lintTyApp fun_ty arg_ty `thenL` \ fun_ty' ->
358 lintTyApps fun_ty' arg_tys
363 %************************************************************************
365 \subsection[lintCoreAlts]{lintCoreAlts}
367 %************************************************************************
370 checkAllCasesCovered e ty [] = addErrL (mkNullAltsMsg e)
372 checkAllCasesCovered e ty [(DEFAULT,_,_)] = nopL
374 checkAllCasesCovered e scrut_ty alts
375 = case splitTyConApp_maybe scrut_ty of {
376 Nothing -> addErrL (badAltsMsg e);
377 Just (tycon, tycon_arg_tys) ->
379 if isPrimTyCon tycon then
380 checkL (hasDefault alts) (nonExhaustiveAltsMsg e)
384 -- Algebraic cases are not necessarily exhaustive, because
385 -- the simplifer correctly eliminates case that can't
387 -- This code just emits a message to say so
389 missing_cons = filter not_in_alts (tyConDataCons tycon)
390 not_in_alts con = all (not_in_alt con) alts
391 not_in_alt con (DataCon con', _, _) = con /= con'
392 not_in_alt con other = True
394 case_bndr = case e of { Case _ bndr alts -> bndr }
396 if not (hasDefault alts || null missing_cons) then
397 pprTrace "Exciting (but not a problem)! Non-exhaustive case:"
398 (ppr case_bndr <+> ppr missing_cons)
405 hasDefault [] = False
406 hasDefault ((DEFAULT,_,_) : alts) = True
407 hasDefault (alt : alts) = hasDefault alts
411 lintCoreAlt :: Type -- Type of scrutinee
413 -> LintM Type -- Type of alternatives
415 lintCoreAlt scrut_ty alt@(DEFAULT, args, rhs)
416 = checkL (null args) (mkDefaultArgsMsg args) `seqL`
419 lintCoreAlt scrut_ty alt@(con, args, rhs)
420 = addLoc (CaseAlt alt) (
422 checkL (conOkForAlt con) (mkConAltMsg con) `seqL`
424 mapL (\arg -> checkL (not (isUnboxedTupleType (idType arg)))
425 (mkUnboxedTupleMsg arg)) args `seqL`
427 addInScopeVars args (
430 -- Scrutinee type must be a tycon applicn; checked by caller
431 -- This code is remarkably compact considering what it does!
432 -- NB: args must be in scope here so that the lintCoreArgs line works.
433 case splitTyConApp_maybe scrut_ty of { Just (tycon, tycon_arg_tys) ->
434 lintTyApps (conType con) tycon_arg_tys `thenL` \ con_type ->
435 lintCoreArgs con_type (map mk_arg args) `thenL` \ con_result_ty ->
436 checkTys con_result_ty scrut_ty (mkBadPatMsg con_result_ty scrut_ty)
443 mk_arg b | isTyVar b = Type (mkTyVarTy b)
447 %************************************************************************
449 \subsection[lint-types]{Types}
451 %************************************************************************
454 lintBinder :: IdOrTyVar -> LintM ()
456 -- ToDo: lint its type
458 lintTy :: Type -> LintM ()
459 lintTy ty = mapL checkIdInScope (varSetElems (tyVarsOfType ty)) `seqL`
461 -- ToDo: check the kind structure of the type
465 %************************************************************************
467 \subsection[lint-monad]{The Lint monad}
469 %************************************************************************
472 type LintM a = [LintLocInfo] -- Locations
473 -> IdSet -- Local vars in scope
474 -> Bag ErrMsg -- Error messages so far
475 -> (Maybe a, Bag ErrMsg) -- Result and error messages (if any)
478 = RhsOf Id -- The variable bound
479 | LambdaBodyOf Id -- The lambda-binder
480 | BodyOfLetRec [Id] -- One of the binders
481 | CaseAlt CoreAlt -- Pattern of a case alternative
482 | AnExpr CoreExpr -- Some expression
483 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
487 initL :: LintM a -> Maybe Message
489 = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
490 if isEmptyBag errs then
493 Just (pprBagOfErrors errs)
496 returnL :: a -> LintM a
497 returnL r loc scope errs = (Just r, errs)
500 nopL loc scope errs = (Nothing, errs)
502 thenL :: LintM a -> (a -> LintM b) -> LintM b
503 thenL m k loc scope errs
504 = case m loc scope errs of
505 (Just r, errs') -> k r loc scope errs'
506 (Nothing, errs') -> (Nothing, errs')
508 seqL :: LintM a -> LintM b -> LintM b
509 seqL m k loc scope errs
510 = case m loc scope errs of
511 (_, errs') -> k loc scope errs'
513 mapL :: (a -> LintM b) -> [a] -> LintM [b]
514 mapL f [] = returnL []
517 mapL f xs `thenL` \ rs ->
522 checkL :: Bool -> Message -> LintM ()
523 checkL True msg loc scope errs = (Nothing, errs)
524 checkL False msg loc scope errs = (Nothing, addErr errs msg loc)
526 addErrL :: Message -> LintM a
527 addErrL msg loc scope errs = (Nothing, addErr errs msg loc)
529 addErr :: Bag ErrMsg -> Message -> [LintLocInfo] -> Bag ErrMsg
531 addErr errs_so_far msg locs
532 = ASSERT (not (null locs))
533 errs_so_far `snocBag` mk_msg msg
535 (loc, cxt1) = dumpLoc (head locs)
536 cxts = [snd (dumpLoc loc) | loc <- locs]
537 context | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1
541 | isNoSrcLoc loc = (loc, hang context 4 msg)
542 | otherwise = addErrLocHdrLine loc context msg
544 addLoc :: LintLocInfo -> LintM a -> LintM a
545 addLoc extra_loc m loc scope errs
546 = m (extra_loc:loc) scope errs
548 addInScopeVars :: [IdOrTyVar] -> LintM a -> LintM a
549 addInScopeVars ids m loc scope errs
550 = m loc (scope `unionVarSet` mkVarSet ids) errs
554 checkIdInScope :: IdOrTyVar -> LintM ()
556 = checkInScope (ptext SLIT("is out of scope")) id
558 checkBndrIdInScope :: IdOrTyVar -> IdOrTyVar -> LintM ()
559 checkBndrIdInScope binder id
560 = checkInScope msg id
562 msg = ptext SLIT("is out of scope inside info for") <+>
565 checkInScope :: SDoc -> IdOrTyVar -> LintM ()
566 checkInScope loc_msg var loc scope errs
567 | isLocallyDefined var
568 && not (var `elemVarSet` scope)
569 && not (isId var && idMustBeINLINEd var) -- Constructors and dict selectors
570 -- don't have bindings,
571 -- just MustInline prags
572 = (Nothing, addErr errs (hsep [ppr var, loc_msg]) loc)
576 checkTys :: Type -> Type -> Message -> LintM ()
577 checkTys ty1 ty2 msg loc scope errs
578 | ty1 == ty2 = (Nothing, errs)
579 | otherwise = (Nothing, addErr errs msg loc)
583 %************************************************************************
585 \subsection{Error messages}
587 %************************************************************************
591 = (getSrcLoc v, brackets (ptext SLIT("RHS of") <+> pp_binders [v]))
593 dumpLoc (LambdaBodyOf b)
594 = (getSrcLoc b, brackets (ptext SLIT("in body of lambda with binder") <+> pp_binder b))
596 dumpLoc (BodyOfLetRec bs)
597 = ( getSrcLoc (head bs), brackets (ptext SLIT("in body of letrec with binders") <+> pp_binders bs))
600 = (noSrcLoc, text "In the expression:" <+> ppr e)
602 dumpLoc (CaseAlt (con, args, rhs))
603 = (noSrcLoc, text "In a case pattern:" <+> parens (ppr con <+> ppr args))
605 dumpLoc (ImportedUnfolding locn)
606 = (locn, brackets (ptext SLIT("in an imported unfolding")))
608 pp_binders :: [Id] -> SDoc
609 pp_binders bs = sep (punctuate comma (map pp_binder bs))
611 pp_binder :: Id -> SDoc
612 pp_binder b = hsep [ppr b, dcolon, ppr (idType b)]
616 ------------------------------------------------------
617 -- Messages for case expressions
619 mkConAppMsg :: CoreExpr -> Message
621 = hang (text "Application of newtype constructor:")
624 mkConAltMsg :: Con -> Message
626 = text "PrimOp in case pattern:" <+> ppr con
628 mkNullAltsMsg :: CoreExpr -> Message
630 = hang (text "Case expression with no alternatives:")
633 mkDefaultArgsMsg :: [IdOrTyVar] -> Message
634 mkDefaultArgsMsg args
635 = hang (text "DEFAULT case with binders")
638 mkCaseAltMsg :: CoreExpr -> Message
640 = hang (text "Type of case alternatives not the same:")
643 mkScrutMsg :: Id -> Type -> Message
644 mkScrutMsg var scrut_ty
645 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
646 text "Result binder type:" <+> ppr (idType var),
647 text "Scrutinee type:" <+> ppr scrut_ty]
649 badAltsMsg :: CoreExpr -> Message
651 = hang (text "Case statement scrutinee is not a data type:")
654 nonExhaustiveAltsMsg :: CoreExpr -> Message
655 nonExhaustiveAltsMsg e
656 = hang (text "Case expression with non-exhaustive alternatives")
659 mkBadPatMsg :: Type -> Type -> Message
660 mkBadPatMsg con_result_ty scrut_ty
662 text "In a case alternative, pattern result type doesn't match scrutinee type:",
663 text "Pattern result type:" <+> ppr con_result_ty,
664 text "Scrutinee type:" <+> ppr scrut_ty
667 ------------------------------------------------------
668 -- Other error messages
670 mkAppMsg :: Type -> Type -> Message
672 = vcat [ptext SLIT("Argument value doesn't match argument type:"),
673 hang (ptext SLIT("Fun type:")) 4 (ppr fun),
674 hang (ptext SLIT("Arg type:")) 4 (ppr arg)]
676 mkKindErrMsg :: TyVar -> Type -> Message
677 mkKindErrMsg tyvar arg_ty
678 = vcat [ptext SLIT("Kinds don't match in type application:"),
679 hang (ptext SLIT("Type variable:"))
680 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
681 hang (ptext SLIT("Arg type:"))
682 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
684 mkTyAppMsg :: Type -> Type -> Message
686 = vcat [text "Illegal type application:",
687 hang (ptext SLIT("Exp type:"))
688 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
689 hang (ptext SLIT("Arg type:"))
690 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
692 mkRhsMsg :: Id -> Type -> Message
695 [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
697 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
698 hsep [ptext SLIT("Rhs type:"), ppr ty]]
700 mkRhsPrimMsg :: Id -> CoreExpr -> Message
701 mkRhsPrimMsg binder rhs
702 = vcat [hsep [ptext SLIT("The type of this binder is primitive:"),
704 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]
707 mkUnboxedTupleMsg :: Id -> Message
708 mkUnboxedTupleMsg binder
709 = vcat [hsep [ptext SLIT("A variable has unboxed tuple type:"), ppr binder],
710 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]]
712 mkCoerceErr from_ty expr_ty
713 = vcat [ptext SLIT("From-type of Coerce differs from type of enclosed expression"),
714 ptext SLIT("From-type:") <+> ppr from_ty,
715 ptext SLIT("Type of enclosed expr:") <+> ppr expr_ty
719 = ptext SLIT("Type where expression expected:") <+> ppr e