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 ( mayHaveNoBinding )
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) = checkIdInScope var `seqL` returnL (idType var)
224 lintCoreExpr (Note (Coerce to_ty from_ty) expr)
225 = lintCoreExpr expr `thenL` \ expr_ty ->
227 lintTy from_ty `seqL`
228 checkTys from_ty (unUsgTy expr_ty) (mkCoerceErr from_ty expr_ty) `seqL`
231 lintCoreExpr (Note other_note expr)
234 lintCoreExpr (Let (NonRec bndr rhs) body)
235 = lintSingleBinding NonRecursive (bndr,rhs) `seqL`
236 addLoc (BodyOfLetRec [bndr])
237 (addInScopeVars [bndr] (lintCoreExpr body))
239 lintCoreExpr (Let (Rec pairs) body)
240 = addInScopeVars bndrs $
241 mapL (lintSingleBinding Recursive) pairs `seqL`
242 addLoc (BodyOfLetRec bndrs) (lintCoreExpr body)
244 bndrs = map fst pairs
246 lintCoreExpr e@(Con con args)
247 = addLoc (AnExpr e) $
248 checkL (conOkForApp con) (mkConAppMsg e) `seqL`
249 lintCoreArgs (conType con) args
251 lintCoreExpr e@(App fun arg)
252 = lintCoreExpr fun `thenL` \ ty ->
256 lintCoreExpr (Lam var expr)
257 = addLoc (LambdaBodyOf var) $
258 checkL (not (isUnboxedTupleType (idType var))) (mkUnboxedTupleMsg var)
260 (addInScopeVars [var] $
261 lintCoreExpr expr `thenL` \ ty ->
262 returnL (mkPiType var ty))
264 lintCoreExpr e@(Case scrut var alts)
265 = -- Check the scrutinee
266 lintCoreExpr scrut `thenL` \ scrut_ty ->
269 lintBinder var `seqL`
271 -- If this is an unboxed tuple case, then the binder must be dead
273 checkL (if isUnboxedTupleType (idType var)
274 then isDeadBinder var
275 else True) (mkUnboxedTupleMsg var) `seqL`
278 checkTys (idType var) scrut_ty (mkScrutMsg var scrut_ty) `seqL`
280 addInScopeVars [var] (
282 -- Check the alternatives
283 checkAllCasesCovered e scrut_ty alts `seqL`
284 mapL (lintCoreAlt scrut_ty) alts `thenL` \ (alt_ty : alt_tys) ->
285 mapL (check alt_ty) alt_tys `seqL`
288 check alt_ty1 alt_ty2 = checkTys alt_ty1 alt_ty2 (mkCaseAltMsg e)
290 lintCoreExpr e@(Type ty)
291 = addErrL (mkStrangeTyMsg e)
294 %************************************************************************
296 \subsection[lintCoreArgs]{lintCoreArgs}
298 %************************************************************************
300 The boolean argument indicates whether we should flag type
301 applications to primitive types as being errors.
304 lintCoreArgs :: Type -> [CoreArg] -> LintM Type
306 lintCoreArgs ty [] = returnL ty
307 lintCoreArgs ty (a : args)
308 = lintCoreArg ty a `thenL` \ res ->
309 lintCoreArgs res args
313 lintCoreArg :: Type -> CoreArg -> LintM Type
315 lintCoreArg ty a@(Type arg_ty)
316 = lintTy arg_ty `seqL`
319 lintCoreArg fun_ty arg
320 = -- Make sure function type matches argument
321 lintCoreExpr arg `thenL` \ arg_ty ->
322 case (splitFunTy_maybe fun_ty) of
323 Just (arg,res) | (arg_ty == arg) -> returnL res
324 _ -> addErrL (mkAppMsg fun_ty arg_ty)
329 = case splitForAllTy_maybe ty of
330 Nothing -> addErrL (mkTyAppMsg ty arg_ty)
334 tyvar_kind = tyVarKind tyvar
335 argty_kind = typeKind arg_ty
337 if argty_kind `hasMoreBoxityInfo` tyvar_kind
338 -- Arg type might be boxed for a function with an uncommitted
339 -- tyvar; notably this is used so that we can give
340 -- error :: forall a:*. String -> a
341 -- and then apply it to both boxed and unboxed types.
343 returnL (substTy (mkTyVarSubst [tyvar] [arg_ty]) body)
345 addErrL (mkKindErrMsg tyvar arg_ty)
350 lintTyApps fun_ty (arg_ty : arg_tys)
351 = lintTyApp fun_ty arg_ty `thenL` \ fun_ty' ->
352 lintTyApps fun_ty' arg_tys
357 %************************************************************************
359 \subsection[lintCoreAlts]{lintCoreAlts}
361 %************************************************************************
364 checkAllCasesCovered e ty [] = addErrL (mkNullAltsMsg e)
366 checkAllCasesCovered e ty [(DEFAULT,_,_)] = nopL
368 checkAllCasesCovered e scrut_ty alts
369 = case splitTyConApp_maybe scrut_ty of {
370 Nothing -> addErrL (badAltsMsg e);
371 Just (tycon, tycon_arg_tys) ->
373 if isPrimTyCon tycon then
374 checkL (hasDefault alts) (nonExhaustiveAltsMsg e)
378 -- Algebraic cases are not necessarily exhaustive, because
379 -- the simplifer correctly eliminates case that can't
381 -- This code just emits a message to say so
383 missing_cons = filter not_in_alts (tyConDataCons tycon)
384 not_in_alts con = all (not_in_alt con) alts
385 not_in_alt con (DataCon con', _, _) = con /= con'
386 not_in_alt con other = True
388 case_bndr = case e of { Case _ bndr alts -> bndr }
390 if not (hasDefault alts || null missing_cons) then
391 pprTrace "Exciting (but not a problem)! Non-exhaustive case:"
392 (ppr case_bndr <+> ppr missing_cons)
399 hasDefault [] = False
400 hasDefault ((DEFAULT,_,_) : alts) = True
401 hasDefault (alt : alts) = hasDefault alts
405 lintCoreAlt :: Type -- Type of scrutinee
407 -> LintM Type -- Type of alternatives
409 lintCoreAlt scrut_ty alt@(DEFAULT, args, rhs)
410 = checkL (null args) (mkDefaultArgsMsg args) `seqL`
413 lintCoreAlt scrut_ty alt@(con, args, rhs)
414 = addLoc (CaseAlt alt) (
416 checkL (conOkForAlt con) (mkConAltMsg con) `seqL`
418 mapL (\arg -> checkL (not (isUnboxedTupleType (idType arg)))
419 (mkUnboxedTupleMsg arg)) args `seqL`
421 addInScopeVars args (
424 -- Scrutinee type must be a tycon applicn; checked by caller
425 -- This code is remarkably compact considering what it does!
426 -- NB: args must be in scope here so that the lintCoreArgs line works.
427 case splitTyConApp_maybe scrut_ty of { Just (tycon, tycon_arg_tys) ->
428 lintTyApps (conType con) tycon_arg_tys `thenL` \ con_type ->
429 lintCoreArgs con_type (map mk_arg args) `thenL` \ con_result_ty ->
430 checkTys con_result_ty scrut_ty (mkBadPatMsg con_result_ty scrut_ty)
437 mk_arg b | isTyVar b = Type (mkTyVarTy b)
441 %************************************************************************
443 \subsection[lint-types]{Types}
445 %************************************************************************
448 lintBinder :: IdOrTyVar -> LintM ()
450 -- ToDo: lint its type
452 lintTy :: Type -> LintM ()
453 lintTy ty = mapL checkIdInScope (varSetElems (tyVarsOfType ty)) `seqL`
455 -- ToDo: check the kind structure of the type
459 %************************************************************************
461 \subsection[lint-monad]{The Lint monad}
463 %************************************************************************
466 type LintM a = [LintLocInfo] -- Locations
467 -> IdSet -- Local vars in scope
468 -> Bag ErrMsg -- Error messages so far
469 -> (Maybe a, Bag ErrMsg) -- Result and error messages (if any)
472 = RhsOf Id -- The variable bound
473 | LambdaBodyOf Id -- The lambda-binder
474 | BodyOfLetRec [Id] -- One of the binders
475 | CaseAlt CoreAlt -- Pattern of a case alternative
476 | AnExpr CoreExpr -- Some expression
477 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
481 initL :: LintM a -> Maybe Message
483 = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
484 if isEmptyBag errs then
487 Just (pprBagOfErrors errs)
490 returnL :: a -> LintM a
491 returnL r loc scope errs = (Just r, errs)
494 nopL loc scope errs = (Nothing, errs)
496 thenL :: LintM a -> (a -> LintM b) -> LintM b
497 thenL m k loc scope errs
498 = case m loc scope errs of
499 (Just r, errs') -> k r loc scope errs'
500 (Nothing, errs') -> (Nothing, errs')
502 seqL :: LintM a -> LintM b -> LintM b
503 seqL m k loc scope errs
504 = case m loc scope errs of
505 (_, errs') -> k loc scope errs'
507 mapL :: (a -> LintM b) -> [a] -> LintM [b]
508 mapL f [] = returnL []
511 mapL f xs `thenL` \ rs ->
516 checkL :: Bool -> Message -> LintM ()
517 checkL True msg loc scope errs = (Nothing, errs)
518 checkL False msg loc scope errs = (Nothing, addErr errs msg loc)
520 addErrL :: Message -> LintM a
521 addErrL msg loc scope errs = (Nothing, addErr errs msg loc)
523 addErr :: Bag ErrMsg -> Message -> [LintLocInfo] -> Bag ErrMsg
525 addErr errs_so_far msg locs
526 = ASSERT (not (null locs))
527 errs_so_far `snocBag` mk_msg msg
529 (loc, cxt1) = dumpLoc (head locs)
530 cxts = [snd (dumpLoc loc) | loc <- locs]
531 context | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1
535 | isNoSrcLoc loc = (loc, hang context 4 msg)
536 | otherwise = addErrLocHdrLine loc context msg
538 addLoc :: LintLocInfo -> LintM a -> LintM a
539 addLoc extra_loc m loc scope errs
540 = m (extra_loc:loc) scope errs
542 addInScopeVars :: [IdOrTyVar] -> LintM a -> LintM a
543 addInScopeVars ids m loc scope errs
544 = m loc (scope `unionVarSet` mkVarSet ids) errs
548 checkIdInScope :: IdOrTyVar -> LintM ()
550 = checkInScope (ptext SLIT("is out of scope")) id
552 checkBndrIdInScope :: IdOrTyVar -> IdOrTyVar -> LintM ()
553 checkBndrIdInScope binder id
554 = checkInScope msg id
556 msg = ptext SLIT("is out of scope inside info for") <+>
559 checkInScope :: SDoc -> IdOrTyVar -> LintM ()
560 checkInScope loc_msg var loc scope errs
561 | isLocallyDefined var
562 && not (var `elemVarSet` scope)
563 && not (isId var && mayHaveNoBinding var)
564 -- Micro-hack here... Class decls generate applications of their
565 -- dictionary constructor, but don't generate a binding for the
566 -- constructor (since it would never be used). After a single round
567 -- of simplification, these dictionary constructors have been
568 -- inlined (from their UnfoldInfo) to CoCons. Just between
569 -- desugaring and simplfication, though, they appear as naked, unbound
570 -- variables as the function in an application.
571 -- The hack here simply doesn't check for out-of-scope-ness for
572 -- data constructors (at least, in a function position).
573 -- Ditto primitive Ids
574 = (Nothing, addErr errs (hsep [ppr var, loc_msg]) loc)
578 checkTys :: Type -> Type -> Message -> LintM ()
579 checkTys ty1 ty2 msg loc scope errs
580 | ty1 == ty2 = (Nothing, errs)
581 | otherwise = (Nothing, addErr errs msg loc)
585 %************************************************************************
587 \subsection{Error messages}
589 %************************************************************************
593 = (getSrcLoc v, brackets (ptext SLIT("RHS of") <+> pp_binders [v]))
595 dumpLoc (LambdaBodyOf b)
596 = (getSrcLoc b, brackets (ptext SLIT("in body of lambda with binder") <+> pp_binder b))
598 dumpLoc (BodyOfLetRec bs)
599 = ( getSrcLoc (head bs), brackets (ptext SLIT("in body of letrec with binders") <+> pp_binders bs))
602 = (noSrcLoc, text "In the expression:" <+> ppr e)
604 dumpLoc (CaseAlt (con, args, rhs))
605 = (noSrcLoc, text "In a case pattern:" <+> parens (ppr con <+> ppr args))
607 dumpLoc (ImportedUnfolding locn)
608 = (locn, brackets (ptext SLIT("in an imported unfolding")))
610 pp_binders :: [Id] -> SDoc
611 pp_binders bs = sep (punctuate comma (map pp_binder bs))
613 pp_binder :: Id -> SDoc
614 pp_binder b = hsep [ppr b, dcolon, ppr (idType b)]
618 ------------------------------------------------------
619 -- Messages for case expressions
621 mkConAppMsg :: CoreExpr -> Message
623 = hang (text "Application of newtype constructor:")
626 mkConAltMsg :: Con -> Message
628 = text "PrimOp in case pattern:" <+> ppr con
630 mkNullAltsMsg :: CoreExpr -> Message
632 = hang (text "Case expression with no alternatives:")
635 mkDefaultArgsMsg :: [IdOrTyVar] -> Message
636 mkDefaultArgsMsg args
637 = hang (text "DEFAULT case with binders")
640 mkCaseAltMsg :: CoreExpr -> Message
642 = hang (text "Type of case alternatives not the same:")
645 mkScrutMsg :: Id -> Type -> Message
646 mkScrutMsg var scrut_ty
647 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
648 text "Result binder type:" <+> ppr (idType var),
649 text "Scrutinee type:" <+> ppr scrut_ty]
651 badAltsMsg :: CoreExpr -> Message
653 = hang (text "Case statement scrutinee is not a data type:")
656 nonExhaustiveAltsMsg :: CoreExpr -> Message
657 nonExhaustiveAltsMsg e
658 = hang (text "Case expression with non-exhaustive alternatives")
661 mkBadPatMsg :: Type -> Type -> Message
662 mkBadPatMsg con_result_ty scrut_ty
664 text "In a case alternative, pattern result type doesn't match scrutinee type:",
665 text "Pattern result type:" <+> ppr con_result_ty,
666 text "Scrutinee type:" <+> ppr scrut_ty
669 ------------------------------------------------------
670 -- Other error messages
672 mkAppMsg :: Type -> Type -> Message
674 = vcat [ptext SLIT("Argument value doesn't match argument type:"),
675 hang (ptext SLIT("Fun type:")) 4 (ppr fun),
676 hang (ptext SLIT("Arg type:")) 4 (ppr arg)]
678 mkKindErrMsg :: TyVar -> Type -> Message
679 mkKindErrMsg tyvar arg_ty
680 = vcat [ptext SLIT("Kinds don't match in type application:"),
681 hang (ptext SLIT("Type variable:"))
682 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
683 hang (ptext SLIT("Arg type:"))
684 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
686 mkTyAppMsg :: Type -> Type -> Message
688 = vcat [text "Illegal type application:",
689 hang (ptext SLIT("Exp type:"))
690 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
691 hang (ptext SLIT("Arg type:"))
692 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
694 mkRhsMsg :: Id -> Type -> Message
697 [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
699 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
700 hsep [ptext SLIT("Rhs type:"), ppr ty]]
702 mkRhsPrimMsg :: Id -> CoreExpr -> Message
703 mkRhsPrimMsg binder rhs
704 = vcat [hsep [ptext SLIT("The type of this binder is primitive:"),
706 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]
709 mkUnboxedTupleMsg :: Id -> Message
710 mkUnboxedTupleMsg binder
711 = vcat [hsep [ptext SLIT("A variable has unboxed tuple type:"), ppr binder],
712 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]]
714 mkCoerceErr from_ty expr_ty
715 = vcat [ptext SLIT("From-type of Coerce differs from type of enclosed expression"),
716 ptext SLIT("From-type:") <+> ppr from_ty,
717 ptext SLIT("Type of enclosed expr:") <+> ppr expr_ty
721 = ptext SLIT("Type where expression expected:") <+> ppr e