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 )
19 import CoreUtils ( idFreeVars )
22 import Const ( Con(..), DataCon, conType, conOkForApp, conOkForAlt )
23 import Id ( isConstantId, idMustBeINLINEd )
24 import Var ( IdOrTyVar, Id, TyVar, idType, tyVarKind, isTyVar, isId )
26 import VarEnv ( mkVarEnv )
27 import Name ( isLocallyDefined, getSrcLoc )
29 import ErrUtils ( doIfSet, dumpIfSet, ghcExit, Message,
30 ErrMsg, addErrLocHdrLine, pprBagOfErrors )
31 import PrimRep ( PrimRep(..) )
32 import SrcLoc ( SrcLoc, noSrcLoc, isNoSrcLoc )
33 import Type ( Type, Kind, tyVarsOfType,
34 splitFunTy_maybe, mkPiType, mkTyVarTy,
35 splitForAllTy_maybe, splitTyConApp_maybe,
36 isUnLiftedType, typeKind, substTy,
37 splitAlgTyConApp_maybe,
41 import TyCon ( TyCon, isPrimTyCon, tyConDataCons )
44 infixr 9 `thenL`, `seqL`
47 %************************************************************************
49 \subsection{Start and end pass}
51 %************************************************************************
53 @beginPass@ and @endPass@ don't really belong here, but it makes a convenient
54 place for them. They print out stuff before and after core passes,
55 and do Core Lint when necessary.
58 beginPass :: String -> IO ()
61 = hPutStr stderr ("*** " ++ pass_name ++ "\n")
66 endPass :: String -> Bool -> [CoreBind] -> IO [CoreBind]
67 endPass pass_name dump_flag binds
69 -- Report verbosely, if required
70 dumpIfSet dump_flag pass_name
71 (pprCoreBindings binds)
74 lintCoreBindings pass_name binds
80 %************************************************************************
82 \subsection[lintCoreBindings]{@lintCoreBindings@: Top-level interface}
84 %************************************************************************
86 Checks that a set of core bindings is well-formed. The PprStyle and String
87 just control what we print in the event of an error. The Bool value
88 indicates whether we have done any specialisation yet (in which case we do
93 (b) Out-of-scope type variables
94 (c) Out-of-scope local variables
97 If we have done specialisation the we check that there are
98 (a) No top-level bindings of primitive (unboxed type)
103 -- Things are *not* OK if:
105 -- * Unsaturated type app before specialisation has been done;
107 -- * Oversaturated type app after specialisation (eta reduction
108 -- may well be happening...);
111 lintCoreBindings :: String -> [CoreBind] -> IO ()
113 lintCoreBindings whoDunnit binds
114 | not opt_DoCoreLinting
117 lintCoreBindings whoDunnit binds
118 = case (initL (lint_binds binds)) of
119 Nothing -> doIfSet opt_D_show_passes
120 (hPutStr stderr ("*** Core Linted result of " ++ whoDunnit ++ "\n"))
122 Just bad_news -> printDump (display bad_news) >>
125 lint_binds [] = returnL ()
126 lint_binds (bind:binds)
127 = lintCoreBinding bind `thenL` \binders ->
128 addInScopeVars binders (lint_binds binds)
132 text ("*** Core Lint Errors: in result of " ++ whoDunnit ++ " ***"),
134 ptext SLIT("*** Offending Program ***"),
135 pprCoreBindings binds,
136 ptext SLIT("*** End of Offense ***")
140 %************************************************************************
142 \subsection[lintUnfolding]{lintUnfolding}
144 %************************************************************************
146 We use this to check all unfoldings that come in from interfaces
147 (it is very painful to catch errors otherwise):
150 lintUnfolding :: SrcLoc
151 -> [IdOrTyVar] -- Treat these as in scope
155 lintUnfolding locn vars expr
156 | not opt_DoCoreLinting
161 initL (addLoc (ImportedUnfolding locn) $
162 addInScopeVars vars $
167 pprTrace "WARNING: Discarded bad unfolding from interface:\n"
169 ptext SLIT("*** Bad unfolding ***"),
171 ptext SLIT("*** End unfolding ***")])
175 %************************************************************************
177 \subsection[lintCoreBinding]{lintCoreBinding}
179 %************************************************************************
181 Check a core binding, returning the list of variables bound.
184 lintCoreBinding :: CoreBind -> LintM [Id]
186 lintCoreBinding (NonRec binder rhs)
187 = lintSingleBinding (binder,rhs) `seqL` returnL [binder]
189 lintCoreBinding (Rec pairs)
190 = addInScopeVars binders (
191 mapL lintSingleBinding pairs `seqL` returnL binders
194 binders = map fst pairs
196 lintSingleBinding (binder,rhs)
197 = addLoc (RhsOf binder) $
200 lintCoreExpr rhs `thenL` \ ty ->
202 -- Check match to RHS type
203 lintBinder binder `seqL`
204 checkTys binder_ty ty (mkRhsMsg binder ty) `seqL`
206 -- Check (not isUnLiftedType) (also checks for bogus unboxed tuples)
207 checkL (not (isUnLiftedType binder_ty))
208 (mkRhsPrimMsg binder rhs) `seqL`
210 -- Check whether binder's specialisations contain any out-of-scope variables
211 mapL (checkBndrIdInScope binder) bndr_vars `seqL`
214 -- We should check the unfolding, if any, but this is tricky because
215 -- the unfolding is a SimplifiableCoreExpr. Give up for now.
217 binder_ty = idType binder
218 bndr_vars = varSetElems (idFreeVars binder)
221 %************************************************************************
223 \subsection[lintCoreExpr]{lintCoreExpr}
225 %************************************************************************
228 lintCoreExpr :: CoreExpr -> LintM Type
230 lintCoreExpr (Var var)
231 | isConstantId var = returnL (idType var)
232 -- Micro-hack here... Class decls generate applications of their
233 -- dictionary constructor, but don't generate a binding for the
234 -- constructor (since it would never be used). After a single round
235 -- of simplification, these dictionary constructors have been
236 -- inlined (from their UnfoldInfo) to CoCons. Just between
237 -- desugaring and simplfication, though, they appear as naked, unbound
238 -- variables as the function in an application.
239 -- The hack here simply doesn't check for out-of-scope-ness for
240 -- data constructors (at least, in a function position).
241 -- Ditto primitive Ids
243 | otherwise = checkIdInScope var `seqL` returnL (idType var)
245 lintCoreExpr (Note (Coerce to_ty from_ty) expr)
246 = lintCoreExpr expr `thenL` \ expr_ty ->
248 lintTy from_ty `seqL`
249 checkTys from_ty expr_ty (mkCoerceErr from_ty expr_ty) `seqL`
252 lintCoreExpr (Note other_note expr)
255 lintCoreExpr (Let binds body)
256 = lintCoreBinding binds `thenL` \binders ->
257 if (null binders) then
258 lintCoreExpr body -- Can't add a new source location
260 addLoc (BodyOfLetRec binders)
261 (addInScopeVars binders (lintCoreExpr body))
263 lintCoreExpr e@(Con con args)
264 = addLoc (AnExpr e) $
265 checkL (conOkForApp con) (mkConAppMsg e) `seqL`
266 lintCoreArgs (conType con) args
268 lintCoreExpr e@(App fun arg)
269 = lintCoreExpr fun `thenL` \ ty ->
273 lintCoreExpr (Lam var expr)
274 = addLoc (LambdaBodyOf var) $
275 checkL (not (isUnboxedTupleType (idType var))) (mkUnboxedTupleMsg var)
277 (addInScopeVars [var] $
278 lintCoreExpr expr `thenL` \ ty ->
279 returnL (mkPiType var ty))
281 lintCoreExpr e@(Case scrut var alts)
282 = -- Check the scrutinee
283 lintCoreExpr scrut `thenL` \ scrut_ty ->
286 lintBinder var `seqL`
288 -- If this is an unboxed tuple case, then the binder must be dead
290 checkL (if isUnboxedTupleType (idType var)
291 then isDeadBinder var
292 else True) (mkUnboxedTupleMsg var) `seqL`
295 checkTys (idType var) scrut_ty (mkScrutMsg var scrut_ty) `seqL`
297 addInScopeVars [var] (
299 -- Check the alternatives
300 checkAllCasesCovered e scrut_ty alts `seqL`
301 mapL (lintCoreAlt scrut_ty) alts `thenL` \ (alt_ty : alt_tys) ->
302 mapL (check alt_ty) alt_tys `seqL`
305 check alt_ty1 alt_ty2 = checkTys alt_ty1 alt_ty2 (mkCaseAltMsg e)
307 lintCoreExpr e@(Type ty)
308 = addErrL (mkStrangeTyMsg e)
311 %************************************************************************
313 \subsection[lintCoreArgs]{lintCoreArgs}
315 %************************************************************************
317 The boolean argument indicates whether we should flag type
318 applications to primitive types as being errors.
321 lintCoreArgs :: Type -> [CoreArg] -> LintM Type
323 lintCoreArgs ty [] = returnL ty
324 lintCoreArgs ty (a : args)
325 = lintCoreArg ty a `thenL` \ res ->
326 lintCoreArgs res args
330 lintCoreArg :: Type -> CoreArg -> LintM Type
332 lintCoreArg ty a@(Type arg_ty)
333 = lintTy arg_ty `seqL`
336 lintCoreArg fun_ty arg
337 = -- Make sure function type matches argument
338 lintCoreExpr arg `thenL` \ arg_ty ->
339 case (splitFunTy_maybe fun_ty) of
340 Just (arg,res) | (arg_ty == arg) -> returnL res
341 _ -> addErrL (mkAppMsg fun_ty arg_ty)
346 = case splitForAllTy_maybe ty of
347 Nothing -> addErrL (mkTyAppMsg ty arg_ty)
351 tyvar_kind = tyVarKind tyvar
352 argty_kind = typeKind arg_ty
354 if argty_kind `hasMoreBoxityInfo` tyvar_kind
355 -- Arg type might be boxed for a function with an uncommitted
356 -- tyvar; notably this is used so that we can give
357 -- error :: forall a:*. String -> a
358 -- and then apply it to both boxed and unboxed types.
360 returnL (substTy (mkVarEnv [(tyvar,arg_ty)]) body)
362 addErrL (mkKindErrMsg tyvar arg_ty)
367 lintTyApps fun_ty (arg_ty : arg_tys)
368 = lintTyApp fun_ty arg_ty `thenL` \ fun_ty' ->
369 lintTyApps fun_ty' arg_tys
374 %************************************************************************
376 \subsection[lintCoreAlts]{lintCoreAlts}
378 %************************************************************************
381 checkAllCasesCovered e ty [] = addErrL (mkNullAltsMsg e)
383 checkAllCasesCovered e ty [(DEFAULT,_,_)] = nopL
385 checkAllCasesCovered e scrut_ty alts
386 = case splitTyConApp_maybe scrut_ty of {
387 Nothing -> addErrL (badAltsMsg e);
388 Just (tycon, tycon_arg_tys) ->
390 if isPrimTyCon tycon then
391 checkL (hasDefault alts) (nonExhaustiveAltsMsg e)
394 -- Algebraic cases are not necessarily exhaustive, because
395 -- the simplifer correctly eliminates case that can't
397 -- This code just emits a message to say so
399 missing_cons = filter not_in_alts (tyConDataCons tycon)
400 not_in_alts con = all (not_in_alt con) alts
401 not_in_alt con (DataCon con', _, _) = con /= con'
402 not_in_alt con other = True
404 case_bndr = case e of { Case _ bndr alts -> bndr }
406 if not (hasDefault alts || null missing_cons) then
407 pprTrace "Exciting (but not a problem)! Non-exhaustive case:"
408 (ppr case_bndr <+> ppr missing_cons)
414 hasDefault [] = False
415 hasDefault ((DEFAULT,_,_) : alts) = True
416 hasDefault (alt : alts) = hasDefault alts
420 lintCoreAlt :: Type -- Type of scrutinee
422 -> LintM Type -- Type of alternatives
424 lintCoreAlt scrut_ty alt@(DEFAULT, args, rhs)
425 = checkL (null args) (mkDefaultArgsMsg args) `seqL`
428 lintCoreAlt scrut_ty alt@(con, args, rhs)
429 = addLoc (CaseAlt alt) (
431 checkL (conOkForAlt con) (mkConAltMsg con) `seqL`
433 mapL (\arg -> checkL (not (isUnboxedTupleType (idType arg)))
434 (mkUnboxedTupleMsg arg)) args `seqL`
436 addInScopeVars args (
439 -- Scrutinee type must be a tycon applicn; checked by caller
440 -- This code is remarkably compact considering what it does!
441 -- NB: args must be in scope here so that the lintCoreArgs line works.
442 case splitTyConApp_maybe scrut_ty of { Just (tycon, tycon_arg_tys) ->
443 lintTyApps (conType con) tycon_arg_tys `thenL` \ con_type ->
444 lintCoreArgs con_type (map mk_arg args) `thenL` \ con_result_ty ->
445 checkTys con_result_ty scrut_ty (mkBadPatMsg con_result_ty scrut_ty)
452 mk_arg b | isTyVar b = Type (mkTyVarTy b)
456 %************************************************************************
458 \subsection[lint-types]{Types}
460 %************************************************************************
463 lintBinder :: IdOrTyVar -> LintM ()
465 -- ToDo: lint its type
467 lintTy :: Type -> LintM ()
468 lintTy ty = mapL checkIdInScope (varSetElems (tyVarsOfType ty)) `seqL`
470 -- ToDo: check the kind structure of the type
474 %************************************************************************
476 \subsection[lint-monad]{The Lint monad}
478 %************************************************************************
481 type LintM a = [LintLocInfo] -- Locations
482 -> IdSet -- Local vars in scope
483 -> Bag ErrMsg -- Error messages so far
484 -> (Maybe a, Bag ErrMsg) -- Result and error messages (if any)
487 = RhsOf Id -- The variable bound
488 | LambdaBodyOf Id -- The lambda-binder
489 | BodyOfLetRec [Id] -- One of the binders
490 | CaseAlt CoreAlt -- Pattern of a case alternative
491 | AnExpr CoreExpr -- Some expression
492 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
496 initL :: LintM a -> Maybe Message
498 = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
499 if isEmptyBag errs then
502 Just (pprBagOfErrors errs)
505 returnL :: a -> LintM a
506 returnL r loc scope errs = (Just r, errs)
509 nopL loc scope errs = (Nothing, errs)
511 thenL :: LintM a -> (a -> LintM b) -> LintM b
512 thenL m k loc scope errs
513 = case m loc scope errs of
514 (Just r, errs') -> k r loc scope errs'
515 (Nothing, errs') -> (Nothing, errs')
517 seqL :: LintM a -> LintM b -> LintM b
518 seqL m k loc scope errs
519 = case m loc scope errs of
520 (_, errs') -> k loc scope errs'
522 mapL :: (a -> LintM b) -> [a] -> LintM [b]
523 mapL f [] = returnL []
526 mapL f xs `thenL` \ rs ->
531 checkL :: Bool -> Message -> LintM ()
532 checkL True msg loc scope errs = (Nothing, errs)
533 checkL False msg loc scope errs = (Nothing, addErr errs msg loc)
535 addErrL :: Message -> LintM a
536 addErrL msg loc scope errs = (Nothing, addErr errs msg loc)
538 addErr :: Bag ErrMsg -> Message -> [LintLocInfo] -> Bag ErrMsg
540 addErr errs_so_far msg locs
541 = ASSERT (not (null locs))
542 errs_so_far `snocBag` mk_msg msg
544 (loc, pref) = dumpLoc (head locs)
547 | isNoSrcLoc loc = (loc, hang pref 4 msg)
548 | otherwise = addErrLocHdrLine loc pref msg
550 addLoc :: LintLocInfo -> LintM a -> LintM a
551 addLoc extra_loc m loc scope errs
552 = m (extra_loc:loc) scope errs
554 addInScopeVars :: [IdOrTyVar] -> LintM a -> LintM a
555 addInScopeVars ids m loc scope errs
556 = m loc (scope `unionVarSet` mkVarSet ids) errs
560 checkIdInScope :: IdOrTyVar -> LintM ()
562 = checkInScope (ptext SLIT("is out of scope")) id
564 checkBndrIdInScope :: IdOrTyVar -> IdOrTyVar -> LintM ()
565 checkBndrIdInScope binder id
566 = checkInScope msg id
568 msg = ptext SLIT("is out of scope inside info for") <+>
571 checkInScope :: SDoc -> IdOrTyVar -> LintM ()
572 checkInScope loc_msg var loc scope errs
573 | isLocallyDefined var
574 && not (var `elemVarSet` scope)
575 && not (isId var && idMustBeINLINEd var) -- Constructors and dict selectors
576 -- don't have bindings,
577 -- just MustInline prags
578 = (Nothing, addErr errs (hsep [ppr var, loc_msg]) loc)
582 checkTys :: Type -> Type -> Message -> LintM ()
583 checkTys ty1 ty2 msg loc scope errs
584 | ty1 == ty2 = (Nothing, errs)
585 | otherwise = (Nothing, addErr errs msg loc)
589 %************************************************************************
591 \subsection{Error messages}
593 %************************************************************************
597 = (getSrcLoc v, brackets (ptext SLIT("RHS of") <+> pp_binders [v]))
599 dumpLoc (LambdaBodyOf b)
600 = (getSrcLoc b, brackets (ptext SLIT("in body of lambda with binder") <+> pp_binder b))
602 dumpLoc (BodyOfLetRec bs)
603 = ( getSrcLoc (head bs), brackets (ptext SLIT("in body of letrec with binders") <+> pp_binders bs))
606 = (noSrcLoc, text "In the expression:" <+> ppr e)
608 dumpLoc (CaseAlt (con, args, rhs))
609 = (noSrcLoc, text "In a case pattern:" <+> parens (ppr con <+> ppr args))
611 dumpLoc (ImportedUnfolding locn)
612 = (locn, brackets (ptext SLIT("in an imported unfolding")))
614 pp_binders :: [Id] -> SDoc
615 pp_binders bs = sep (punctuate comma (map pp_binder bs))
617 pp_binder :: Id -> SDoc
618 pp_binder b = hsep [ppr b, dcolon, ppr (idType b)]
622 ------------------------------------------------------
623 -- Messages for case expressions
625 mkConAppMsg :: CoreExpr -> Message
627 = hang (text "Application of newtype constructor:")
630 mkConAltMsg :: Con -> Message
632 = text "PrimOp in case pattern:" <+> ppr con
634 mkNullAltsMsg :: CoreExpr -> Message
636 = hang (text "Case expression with no alternatives:")
639 mkDefaultArgsMsg :: [IdOrTyVar] -> Message
640 mkDefaultArgsMsg args
641 = hang (text "DEFAULT case with binders")
644 mkCaseAltMsg :: CoreExpr -> Message
646 = hang (text "Type of case alternatives not the same:")
649 mkScrutMsg :: Id -> Type -> Message
650 mkScrutMsg var scrut_ty
651 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
652 text "Result binder type:" <+> ppr (idType var),
653 text "Scrutinee type:" <+> ppr scrut_ty]
655 badAltsMsg :: CoreExpr -> Message
657 = hang (text "Case statement scrutinee is not a data type:")
660 nonExhaustiveAltsMsg :: CoreExpr -> Message
661 nonExhaustiveAltsMsg e
662 = hang (text "Case expression with non-exhaustive alternatives")
665 mkBadPatMsg :: Type -> Type -> Message
666 mkBadPatMsg con_result_ty scrut_ty
668 text "In a case alternative, pattern result type doesn't match scrutinee type:",
669 text "Pattern result type:" <+> ppr con_result_ty,
670 text "Scrutinee type:" <+> ppr scrut_ty
673 ------------------------------------------------------
674 -- Other error messages
676 mkAppMsg :: Type -> Type -> Message
678 = vcat [ptext SLIT("Argument value doesn't match argument type:"),
679 hang (ptext SLIT("Fun type:")) 4 (ppr fun),
680 hang (ptext SLIT("Arg type:")) 4 (ppr arg)]
682 mkKindErrMsg :: TyVar -> Type -> Message
683 mkKindErrMsg tyvar arg_ty
684 = vcat [ptext SLIT("Kinds don't match in type application:"),
685 hang (ptext SLIT("Type variable:"))
686 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
687 hang (ptext SLIT("Arg type:"))
688 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
690 mkTyAppMsg :: Type -> Type -> Message
692 = vcat [text "Illegal type application:",
693 hang (ptext SLIT("Exp type:"))
694 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
695 hang (ptext SLIT("Arg type:"))
696 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
698 mkRhsMsg :: Id -> Type -> Message
701 [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
703 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
704 hsep [ptext SLIT("Rhs type:"), ppr ty]]
706 mkRhsPrimMsg :: Id -> CoreExpr -> Message
707 mkRhsPrimMsg binder rhs
708 = vcat [hsep [ptext SLIT("The type of this binder is primitive:"),
710 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]
713 mkUnboxedTupleMsg :: Id -> Message
714 mkUnboxedTupleMsg binder
715 = vcat [hsep [ptext SLIT("A variable has unboxed tuple type:"), ppr binder],
716 hsep [ptext SLIT("Binder's type:"), ppr (idType binder)]]
718 mkCoerceErr from_ty expr_ty
719 = vcat [ptext SLIT("From-type of Coerce differs from type of enclosed expression"),
720 ptext SLIT("From-type:") <+> ppr from_ty,
721 ptext SLIT("Type of enclosed expr:") <+> ppr expr_ty
725 = ptext SLIT("Type where expression expected:") <+> ppr e