2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1995
4 \section[CoreLint]{A ``lint'' pass to check for Core correctness}
7 #include "HsVersions.h"
19 import Kind ( Kind{-instance-} )
20 import Literal ( literalType, Literal{-instance-} )
21 import Id ( idType, isBottomingId,
22 getInstantiatedDataConSig, GenId{-instances-}
24 import Outputable ( Outputable(..) )
26 import PprStyle ( PprStyle(..) )
27 import PprType ( GenType, GenTyVar, TyCon )
29 import PrimOp ( primOpType, PrimOp(..) )
30 import PrimRep ( PrimRep(..) )
31 import SrcLoc ( SrcLoc )
32 import Type ( mkFunTy,getFunTy_maybe,mkForAllTy,getForAllTy_maybe,
33 isPrimType,getTypeKind,instantiateTy,
34 mkForAllUsageTy,getForAllUsageTy,instantiateUsage,
35 maybeAppDataTyCon, eqTy )
36 import TyCon ( isPrimTyCon,isVisibleDataTyCon )
37 import TyVar ( getTyVarKind, GenTyVar{-instances-} )
38 import UniqSet ( emptyUniqSet, mkUniqSet, intersectUniqSets,
39 unionUniqSets, elementOfUniqSet, UniqSet(..) )
40 import Unique ( Unique )
41 import Usage ( GenUsage )
42 import Util ( zipEqual, pprTrace, pprPanic, assertPanic, panic )
44 infixr 9 `thenL`, `seqL`, `thenMaybeL`, `seqMaybeL`
47 %************************************************************************
49 \subsection[lintCoreBindings]{@lintCoreBindings@: Top-level interface}
51 %************************************************************************
53 Checks that a set of core bindings is well-formed. The PprStyle and String
54 just control what we print in the event of an error. The Bool value
55 indicates whether we have done any specialisation yet (in which case we do
60 (b) Out-of-scope type variables
61 (c) Out-of-scope local variables
64 If we have done specialisation the we check that there are
65 (a) No top-level bindings of primitive (unboxed type)
70 -- Things are *not* OK if:
72 -- * Unsaturated type app before specialisation has been done;
74 -- * Oversaturated type app after specialisation (eta reduction
75 -- may well be happening...);
77 -- Note: checkTyApp is usually followed by a call to checkSpecTyApp.
82 :: PprStyle -> String -> Bool -> [CoreBinding] -> [CoreBinding]
84 lintCoreBindings sty whoDunnit spec_done binds
85 = case (initL (lint_binds binds) spec_done) of
88 pprPanic "" (ppAboves [
89 ppStr ("*** Core Lint Errors: in " ++ whoDunnit ++ " ***"),
91 ppStr "*** Offending Program ***",
93 (map (pprCoreBinding sty (pprBigCoreBinder sty) (pprTypedCoreBinder sty) (ppr sty))
95 ppStr "*** End of Offense ***"
98 lint_binds [] = returnL ()
99 lint_binds (bind:binds)
100 = lintCoreBinding bind `thenL` \binders ->
101 addInScopeVars binders (lint_binds binds)
104 %************************************************************************
106 \subsection[lintUnfolding]{lintUnfolding}
108 %************************************************************************
110 We use this to check all unfoldings that come in from interfaces
111 (it is very painful to catch errors otherwise):
114 lintUnfolding :: SrcLoc -> CoreExpr -> Maybe CoreExpr
116 lintUnfolding locn expr
118 (initL (addLoc (ImportedUnfolding locn) (lintCoreExpr expr))
119 True{-pretend spec done-})
123 pprTrace "WARNING: Discarded bad unfolding from interface:\n"
124 (ppAboves [msg PprForUser,
125 ppStr "*** Bad unfolding ***",
127 ppStr "*** End unfolding ***"])
131 %************************************************************************
133 \subsection[lintCoreBinding]{lintCoreBinding}
135 %************************************************************************
137 Check a core binding, returning the list of variables bound.
140 lintCoreBinding :: CoreBinding -> LintM [Id]
142 lintCoreBinding (NonRec binder rhs)
143 = lintSingleBinding (binder,rhs) `seqL` returnL [binder]
145 lintCoreBinding (Rec pairs)
146 = addInScopeVars binders (
147 mapL lintSingleBinding pairs `seqL` returnL binders
150 binders = [b | (b,_) <- pairs]
152 lintSingleBinding (binder,rhs)
153 = addLoc (RhsOf binder) (
158 -- Check match to RHS type
160 Nothing -> returnL ()
161 Just ty -> checkTys (idType binder) ty (mkRhsMsg binder ty))
164 -- Check (not isPrimType)
165 checkIfSpecDoneL (not (isPrimType (idType binder)))
166 (mkRhsPrimMsg binder rhs)
168 -- We should check the unfolding, if any, but this is tricky because
169 -- the unfolding is a SimplifiableCoreExpr. Give up for now.
173 %************************************************************************
175 \subsection[lintCoreExpr]{lintCoreExpr}
177 %************************************************************************
180 lintCoreExpr :: CoreExpr -> LintM (Maybe Type) -- Nothing if error found
182 lintCoreExpr (Var var) = checkInScope var `seqL` returnL (Just (idType var))
183 lintCoreExpr (Lit lit) = returnL (Just (literalType lit))
184 lintCoreExpr (SCC _ expr) = lintCoreExpr expr
186 lintCoreExpr (Let binds body)
187 = lintCoreBinding binds `thenL` \binders ->
188 if (null binders) then
189 lintCoreExpr body -- Can't add a new source location
191 addLoc (BodyOfLetRec binders)
192 (addInScopeVars binders (lintCoreExpr body))
194 lintCoreExpr e@(Con con args)
195 = lintCoreArgs False e (idType con) args
196 -- Note: we don't check for primitive types in these arguments
198 lintCoreExpr e@(Prim op args)
199 = lintCoreArgs True e (primOpType op) args
200 -- Note: we do check for primitive types in these arguments
202 lintCoreExpr e@(App fun@(Var v) arg) | isBottomingId v
203 = lintCoreExpr fun `thenMaybeL` \ ty -> lintCoreArg False e ty arg
204 -- Note: we don't check for primitive types in argument to 'error'
206 lintCoreExpr e@(App fun arg)
207 = lintCoreExpr fun `thenMaybeL` \ty -> lintCoreArg True e ty arg
208 -- Note: we do check for primitive types in this argument
210 lintCoreExpr (Lam (ValBinder var) expr)
211 = addLoc (LambdaBodyOf var)
212 (addInScopeVars [var]
213 (lintCoreExpr expr `thenMaybeL` \ty ->
214 returnL (Just (mkFunTy (idType var) ty))))
216 lintCoreExpr (Lam (TyBinder tyvar) expr)
217 = lintCoreExpr expr `thenMaybeL` \ty ->
218 returnL (Just(mkForAllTy tyvar ty))
219 -- TODO: Should add in-scope type variable at this point
221 lintCoreExpr e@(Case scrut alts)
222 = lintCoreExpr scrut `thenMaybeL` \ty ->
223 -- Check that it is a data type
224 case maybeAppDataTyCon ty of
225 Nothing -> addErrL (mkCaseDataConMsg e) `seqL` returnL Nothing
226 Just(tycon, _, _) -> lintCoreAlts alts ty tycon
229 %************************************************************************
231 \subsection[lintCoreArgs]{lintCoreArgs}
233 %************************************************************************
235 The boolean argument indicates whether we should flag type
236 applications to primitive types as being errors.
239 lintCoreArgs :: Bool -> CoreExpr -> Type -> [CoreArg] -> LintM (Maybe Type)
241 lintCoreArgs _ _ ty [] = returnL (Just ty)
242 lintCoreArgs checkTyApp e ty (a : args)
243 = lintCoreArg checkTyApp e ty a `thenMaybeL` \ res ->
244 lintCoreArgs checkTyApp e res args
247 %************************************************************************
249 \subsection[lintCoreArg]{lintCoreArg}
251 %************************************************************************
254 lintCoreArg :: Bool -> CoreExpr -> Type -> CoreArg -> LintM (Maybe Type)
256 lintCoreArg _ e ty (LitArg lit)
257 = -- Make sure function type matches argument
258 case (getFunTy_maybe ty) of
259 Just (arg,res) | (literalType lit `eqTy` arg) -> returnL(Just res)
260 _ -> addErrL (mkAppMsg ty (literalType lit) e) `seqL` returnL Nothing
262 lintCoreArg _ e ty (VarArg v)
263 = -- Make sure variable is bound
264 checkInScope v `seqL`
265 -- Make sure function type matches argument
266 case (getFunTy_maybe ty) of
267 Just (arg,res) | (idType v `eqTy` arg) -> returnL(Just res)
268 _ -> addErrL (mkAppMsg ty (idType v) e) `seqL` returnL Nothing
270 lintCoreArg checkTyApp e ty a@(TyArg arg_ty)
271 = -- TODO: Check that ty is well-kinded and has no unbound tyvars
272 checkIfSpecDoneL (not (isPrimType arg_ty)) (mkSpecTyAppMsg a)
274 case (getForAllTy_maybe ty) of
275 Just (tyvar,body) | (getTyVarKind tyvar == getTypeKind arg_ty) ->
276 returnL(Just(instantiateTy [(tyvar,arg_ty)] body))
277 _ -> addErrL (mkTyAppMsg ty arg_ty e) `seqL` returnL Nothing
279 lintCoreArg _ e ty (UsageArg u)
280 = -- TODO: Check that usage has no unbound usage variables
281 case (getForAllUsageTy ty) of
282 Just (uvar,bounds,body) ->
283 -- TODO Check argument satisfies bounds
284 returnL(Just(panic "lintCoreArg:instantiateUsage uvar u body"))
285 _ -> addErrL (mkUsageAppMsg ty u e) `seqL` returnL Nothing
288 %************************************************************************
290 \subsection[lintCoreAlts]{lintCoreAlts}
292 %************************************************************************
295 lintCoreAlts :: CoreCaseAlts
296 -> Type -- Type of scrutinee
297 -> TyCon -- TyCon pinned on the case
298 -> LintM (Maybe Type) -- Type of alternatives
300 lintCoreAlts (AlgAlts alts deflt) ty tycon
301 = panic "CoreLint.lintCoreAlts"
303 WDP: can't tell what type DNT wants here
304 = -- Check tycon is not a primitive tycon
305 addErrIfL (isPrimTyCon tycon) (mkCasePrimMsg tycon)
307 -- Check we have a non-abstract data tycon
308 addErrIfL (not (isVisibleDataTyCon tycon)) (mkCaseAbstractMsg tycon)
311 `thenL` \maybe_deflt_ty ->
312 mapL (lintAlgAlt ty tycon) alts
313 `thenL` \maybe_alt_tys ->
314 returnL (maybe_deflt_ty : maybe_alt_tys)
316 lintCoreAlts (PrimAlts alts deflt) ty tycon
317 = -- Check tycon is a primitive tycon
318 addErrIfL (not (isPrimTyCon tycon)) (mkCaseNotPrimMsg tycon)
320 mapL (lintPrimAlt ty) alts
321 `thenL` \maybe_alt_tys ->
323 `thenL` \maybe_deflt_ty ->
324 returnL (maybe_deflt_ty : maybe_alt_tys)
325 -- Check the result types
328 `thenL` \ maybe_result_tys ->
329 case catMaybes (maybe_result_tys) of
330 [] -> returnL Nothing
332 (first_ty:tys) -> mapL check tys `seqL`
333 returnL (Just first_ty)
335 check ty = checkTys first_ty ty (mkCaseAltMsg alts)
338 lintAlgAlt scrut_ty (con,args,rhs)
339 = (case maybeAppDataTyCon scrut_ty of
341 addErrL (mkAlgAltMsg1 scrut_ty)
342 Just (tycon, tys_applied, cons) ->
344 (_, arg_tys, _) = getInstantiatedDataConSig con tys_applied
346 checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con) `seqL`
347 checkL (length arg_tys == length args) (mkAlgAltMsg3 con args)
349 mapL check (arg_tys `zipEqual` args) `seqL`
352 addInScopeVars args (
356 check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
358 -- elem: yes, the elem-list here can sometimes be long-ish,
359 -- but as it's use-once, probably not worth doing anything different
360 -- We give it its own copy, so it isn't overloaded.
362 elem x (y:ys) = x==y || elem x ys
364 lintPrimAlt ty alt@(lit,rhs)
365 = checkTys (literalType lit) ty (mkPrimAltMsg alt) `seqL`
368 lintDeflt NoDefault _ = returnL Nothing
369 lintDeflt deflt@(BindDefault binder rhs) ty
370 = checkTys (idType binder) ty (mkDefltMsg deflt) `seqL`
371 addInScopeVars [binder] (lintCoreExpr rhs)
374 %************************************************************************
376 \subsection[lint-monad]{The Lint monad}
378 %************************************************************************
381 type LintM a = Bool -- True <=> specialisation has been done
382 -> [LintLocInfo] -- Locations
383 -> UniqSet Id -- Local vars in scope
384 -> Bag ErrMsg -- Error messages so far
385 -> (a, Bag ErrMsg) -- Result and error messages (if any)
387 type ErrMsg = PprStyle -> Pretty
390 = RhsOf Id -- The variable bound
391 | LambdaBodyOf Id -- The lambda-binder
392 | BodyOfLetRec [Id] -- One of the binders
393 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
395 instance Outputable LintLocInfo where
397 = ppBesides [ppr sty (getSrcLoc v), ppStr ": [RHS of ", pp_binders sty [v], ppStr "]"]
399 ppr sty (LambdaBodyOf b)
400 = ppBesides [ppr sty (getSrcLoc b),
401 ppStr ": [in body of lambda with binder ", pp_binder sty b, ppStr "]"]
403 ppr sty (BodyOfLetRec bs)
404 = ppBesides [ppr sty (getSrcLoc (head bs)),
405 ppStr ": [in body of letrec with binders ", pp_binders sty bs, ppStr "]"]
407 ppr sty (ImportedUnfolding locn)
408 = ppBeside (ppr sty locn) (ppStr ": [in an imported unfolding]")
410 pp_binders :: PprStyle -> [Id] -> Pretty
411 pp_binders sty bs = ppInterleave ppComma (map (pp_binder sty) bs)
413 pp_binder :: PprStyle -> Id -> Pretty
414 pp_binder sty b = ppCat [ppr sty b, ppStr "::", ppr sty (idType b)]
418 initL :: LintM a -> Bool -> Maybe ErrMsg
420 = case (m spec_done [] emptyUniqSet emptyBag) of { (_, errs) ->
421 if isEmptyBag errs then
425 ppAboves [ msg sty | msg <- bagToList errs ]
429 returnL :: a -> LintM a
430 returnL r spec loc scope errs = (r, errs)
432 thenL :: LintM a -> (a -> LintM b) -> LintM b
433 thenL m k spec loc scope errs
434 = case m spec loc scope errs of
435 (r, errs') -> k r spec loc scope errs'
437 seqL :: LintM a -> LintM b -> LintM b
438 seqL m k spec loc scope errs
439 = case m spec loc scope errs of
440 (_, errs') -> k spec loc scope errs'
442 thenMaybeL :: LintM (Maybe a) -> (a -> LintM (Maybe b)) -> LintM (Maybe b)
443 thenMaybeL m k spec loc scope errs
444 = case m spec loc scope errs of
445 (Nothing, errs2) -> (Nothing, errs2)
446 (Just r, errs2) -> k r spec loc scope errs2
448 seqMaybeL :: LintM (Maybe a) -> LintM (Maybe b) -> LintM (Maybe b)
449 seqMaybeL m k spec loc scope errs
450 = case m spec loc scope errs of
451 (Nothing, errs2) -> (Nothing, errs2)
452 (Just _, errs2) -> k spec loc scope errs2
454 mapL :: (a -> LintM b) -> [a] -> LintM [b]
455 mapL f [] = returnL []
458 mapL f xs `thenL` \ rs ->
461 mapMaybeL :: (a -> LintM (Maybe b)) -> [a] -> LintM (Maybe [b])
462 -- Returns Nothing if anything fails
463 mapMaybeL f [] = returnL (Just [])
465 = f x `thenMaybeL` \ r ->
466 mapMaybeL f xs `thenMaybeL` \ rs ->
467 returnL (Just (r:rs))
471 checkL :: Bool -> ErrMsg -> LintM ()
472 checkL True msg spec loc scope errs = ((), errs)
473 checkL False msg spec loc scope errs = ((), addErr errs msg loc)
475 checkIfSpecDoneL :: Bool -> ErrMsg -> LintM ()
476 checkIfSpecDoneL True msg spec loc scope errs = ((), errs)
477 checkIfSpecDoneL False msg True loc scope errs = ((), addErr errs msg loc)
478 checkIfSpecDoneL False msg False loc scope errs = ((), errs)
481 = if pred then addErrL spec else returnL ()
483 addErrL :: ErrMsg -> LintM ()
484 addErrL msg spec loc scope errs = ((), addErr errs msg loc)
486 addErr :: Bag ErrMsg -> ErrMsg -> [LintLocInfo] -> Bag ErrMsg
488 addErr errs_so_far msg locs
489 = ASSERT (not (null locs))
490 errs_so_far `snocBag` ( \ sty ->
491 ppHang (ppr sty (head locs)) 4 (msg sty)
494 addLoc :: LintLocInfo -> LintM a -> LintM a
495 addLoc extra_loc m spec loc scope errs
496 = m spec (extra_loc:loc) scope errs
498 addInScopeVars :: [Id] -> LintM a -> LintM a
499 addInScopeVars ids m spec loc scope errs
500 = -- We check if these "new" ids are already
501 -- in scope, i.e., we have *shadowing* going on.
502 -- For now, it's just a "trace"; we may make
503 -- a real error out of it...
505 new_set = mkUniqSet ids
507 shadowed = scope `intersectUniqSets` new_set
509 -- After adding -fliberate-case, Simon decided he likes shadowed
510 -- names after all. WDP 94/07
511 -- (if isEmptyUniqSet shadowed
513 -- else pprTrace "Shadowed vars:" (ppr PprDebug (uniqSetToList shadowed))) (
514 m spec loc (scope `unionUniqSets` new_set) errs
519 checkInScope :: Id -> LintM ()
520 checkInScope id spec loc scope errs
521 = if isLocallyDefined id && not (id `elementOfUniqSet` scope) then
522 ((),addErr errs (\sty -> ppCat [ppr sty id,ppStr "is out of scope"]) loc)
526 checkTys :: Type -> Type -> ErrMsg -> LintM ()
527 checkTys ty1 ty2 msg spec loc scope errs
528 = if ty1 `eqTy` ty2 then ((), errs) else ((), addErr errs msg loc)
532 mkCaseAltMsg :: CoreCaseAlts -> ErrMsg
533 mkCaseAltMsg alts sty
534 = ppAbove (ppStr "Type of case alternatives not the same:")
537 mkCaseDataConMsg :: CoreExpr -> ErrMsg
538 mkCaseDataConMsg expr sty
539 = ppAbove (ppStr "A case scrutinee not of data constructor type:")
542 mkCaseNotPrimMsg :: TyCon -> ErrMsg
543 mkCaseNotPrimMsg tycon sty
544 = ppAbove (ppStr "A primitive case on a non-primitive type:")
547 mkCasePrimMsg :: TyCon -> ErrMsg
548 mkCasePrimMsg tycon sty
549 = ppAbove (ppStr "An algebraic case on a primitive type:")
552 mkCaseAbstractMsg :: TyCon -> ErrMsg
553 mkCaseAbstractMsg tycon sty
554 = ppAbove (ppStr "An algebraic case on an abstract type:")
557 mkDefltMsg :: CoreCaseDefault -> ErrMsg
559 = ppAbove (ppStr "Binder in case default doesn't match type of scrutinee:")
562 mkAppMsg :: Type -> Type -> CoreExpr -> ErrMsg
563 mkAppMsg fun arg expr sty
564 = ppAboves [ppStr "Argument values doesn't match argument type:",
565 ppHang (ppStr "Fun type:") 4 (ppr sty fun),
566 ppHang (ppStr "Arg type:") 4 (ppr sty arg),
567 ppHang (ppStr "Expression:") 4 (pp_expr sty expr)]
569 mkTyAppMsg :: Type -> Type -> CoreExpr -> ErrMsg
570 mkTyAppMsg ty arg expr sty
573 = ppAboves [ppStr "Illegal type application:",
574 ppHang (ppStr "Exp type:") 4 (ppr sty exp),
575 ppHang (ppStr "Arg type:") 4 (ppr sty arg),
576 ppHang (ppStr "Expression:") 4 (pp_expr sty expr)]
579 mkUsageAppMsg :: Type -> Usage -> CoreExpr -> ErrMsg
580 mkUsageAppMsg ty u expr sty
581 = ppAboves [ppStr "Illegal usage application:",
582 ppHang (ppStr "Exp type:") 4 (ppr sty ty),
583 ppHang (ppStr "Usage exp:") 4 (ppr sty u),
584 ppHang (ppStr "Expression:") 4 (pp_expr sty expr)]
586 mkAlgAltMsg1 :: Type -> ErrMsg
588 = ppAbove (ppStr "In some case statement, type of scrutinee is not a data type:")
591 mkAlgAltMsg2 :: Type -> Id -> ErrMsg
592 mkAlgAltMsg2 ty con sty
594 ppStr "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
599 mkAlgAltMsg3 :: Id -> [Id] -> ErrMsg
600 mkAlgAltMsg3 con alts sty
602 ppStr "In some algebraic case alternative, number of arguments doesn't match constructor:",
607 mkAlgAltMsg4 :: Type -> Id -> ErrMsg
608 mkAlgAltMsg4 ty arg sty
610 ppStr "In some algebraic case alternative, type of argument doesn't match data constructor:",
615 mkPrimAltMsg :: (Literal, CoreExpr) -> ErrMsg
618 (ppStr "In a primitive case alternative, type of literal doesn't match type of scrutinee:")
621 mkRhsMsg :: Id -> Type -> ErrMsg
622 mkRhsMsg binder ty sty
624 [ppCat [ppStr "The type of this binder doesn't match the type of its RHS:",
626 ppCat [ppStr "Binder's type:", ppr sty (idType binder)],
627 ppCat [ppStr "Rhs type:", ppr sty ty]]
629 mkRhsPrimMsg :: Id -> CoreExpr -> ErrMsg
630 mkRhsPrimMsg binder rhs sty
631 = ppAboves [ppCat [ppStr "The type of this binder is primitive:",
633 ppCat [ppStr "Binder's type:", ppr sty (idType binder)]
636 mkSpecTyAppMsg :: CoreArg -> ErrMsg
637 mkSpecTyAppMsg arg sty
639 (ppStr "Unboxed types in a type application (after specialisation):")
642 pp_expr :: PprStyle -> CoreExpr -> Pretty
644 = pprCoreExpr sty (pprBigCoreBinder sty) (pprTypedCoreBinder sty) (pprTypedCoreBinder sty) expr