Remove unused LiveVars and SRT fields of StgCase
[ghc.git] / compiler / stgSyn / StgLint.hs
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3
4 \section[StgLint]{A ``lint'' pass to check for Stg correctness}
5 -}
6
7 {-# LANGUAGE CPP #-}
8
9 module StgLint ( lintStgBindings ) where
10
11 import StgSyn
12
13 import Bag ( Bag, emptyBag, isEmptyBag, snocBag, bagToList )
14 import Id ( Id, idType, isLocalId )
15 import VarSet
16 import DataCon
17 import CoreSyn ( AltCon(..) )
18 import PrimOp ( primOpType )
19 import Literal ( literalType )
20 import Maybes
21 import Name ( getSrcLoc )
22 import ErrUtils ( MsgDoc, Severity(..), mkLocMessage )
23 import Type
24 import TyCon
25 import Util
26 import SrcLoc
27 import Outputable
28 import Control.Monad
29 import Data.Function
30
31 #include "HsVersions.h"
32
33 {-
34 Checks for
35 (a) *some* type errors
36 (b) locally-defined variables used but not defined
37
38
39 Note: unless -dverbose-stg is on, display of lint errors will result
40 in "panic: bOGUS_LVs".
41
42 WARNING:
43 ~~~~~~~~
44
45 This module has suffered bit-rot; it is likely to yield lint errors
46 for Stg code that is currently perfectly acceptable for code
47 generation. Solution: don't use it! (KSW 2000-05).
48
49
50 ************************************************************************
51 * *
52 \subsection{``lint'' for various constructs}
53 * *
54 ************************************************************************
55
56 @lintStgBindings@ is the top-level interface function.
57 -}
58
59 lintStgBindings :: String -> [StgBinding] -> [StgBinding]
60
61 lintStgBindings whodunnit binds
62 = {-# SCC "StgLint" #-}
63 case (initL (lint_binds binds)) of
64 Nothing -> binds
65 Just msg -> pprPanic "" (vcat [
66 text "*** Stg Lint ErrMsgs: in" <+>
67 text whodunnit <+> text "***",
68 msg,
69 text "*** Offending Program ***",
70 pprStgBindings binds,
71 text "*** End of Offense ***"])
72 where
73 lint_binds :: [StgBinding] -> LintM ()
74
75 lint_binds [] = return ()
76 lint_binds (bind:binds) = do
77 binders <- lintStgBinds bind
78 addInScopeVars binders $
79 lint_binds binds
80
81 lintStgArg :: StgArg -> LintM (Maybe Type)
82 lintStgArg (StgLitArg lit) = return (Just (literalType lit))
83 lintStgArg (StgVarArg v) = lintStgVar v
84
85 lintStgVar :: Id -> LintM (Maybe Kind)
86 lintStgVar v = do checkInScope v
87 return (Just (idType v))
88
89 lintStgBinds :: StgBinding -> LintM [Id] -- Returns the binders
90 lintStgBinds (StgNonRec binder rhs) = do
91 lint_binds_help (binder,rhs)
92 return [binder]
93
94 lintStgBinds (StgRec pairs)
95 = addInScopeVars binders $ do
96 mapM_ lint_binds_help pairs
97 return binders
98 where
99 binders = [b | (b,_) <- pairs]
100
101 lint_binds_help :: (Id, StgRhs) -> LintM ()
102 lint_binds_help (binder, rhs)
103 = addLoc (RhsOf binder) $ do
104 -- Check the rhs
105 _maybe_rhs_ty <- lintStgRhs rhs
106
107 -- Check binder doesn't have unlifted type
108 checkL (not (isUnliftedType binder_ty))
109 (mkUnliftedTyMsg binder rhs)
110
111 -- Check match to RHS type
112 -- Actually we *can't* check the RHS type, because
113 -- unsafeCoerce means it really might not match at all
114 -- notably; eg x::Int = (error @Bool "urk") |> unsafeCoerce...
115 -- case maybe_rhs_ty of
116 -- Nothing -> return ()
117 -- Just rhs_ty -> checkTys binder_ty
118 -- rhs_ty
119 --- (mkRhsMsg binder rhs_ty)
120
121 return ()
122 where
123 binder_ty = idType binder
124
125 lintStgRhs :: StgRhs -> LintM (Maybe Type) -- Just ty => type is exact
126
127 lintStgRhs (StgRhsClosure _ _ _ _ [] expr)
128 = lintStgExpr expr
129
130 lintStgRhs (StgRhsClosure _ _ _ _ binders expr)
131 = addLoc (LambdaBodyOf binders) $
132 addInScopeVars binders $ runMaybeT $ do
133 body_ty <- MaybeT $ lintStgExpr expr
134 return (mkFunTys (map idType binders) body_ty)
135
136 lintStgRhs (StgRhsCon _ con args) = runMaybeT $ do
137 arg_tys <- mapM (MaybeT . lintStgArg) args
138 MaybeT $ checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys)
139 where
140 con_ty = dataConRepType con
141
142 lintStgExpr :: StgExpr -> LintM (Maybe Type) -- Just ty => type is exact
143
144 lintStgExpr (StgLit l) = return (Just (literalType l))
145
146 lintStgExpr e@(StgApp fun args) = runMaybeT $ do
147 fun_ty <- MaybeT $ lintStgVar fun
148 arg_tys <- mapM (MaybeT . lintStgArg) args
149 MaybeT $ checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e)
150
151 lintStgExpr e@(StgConApp con args) = runMaybeT $ do
152 arg_tys <- mapM (MaybeT . lintStgArg) args
153 MaybeT $ checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e)
154 where
155 con_ty = dataConRepType con
156
157 lintStgExpr e@(StgOpApp (StgPrimOp op) args _) = runMaybeT $ do
158 arg_tys <- mapM (MaybeT . lintStgArg) args
159 MaybeT $ checkFunApp op_ty arg_tys (mkFunAppMsg op_ty arg_tys e)
160 where
161 op_ty = primOpType op
162
163 lintStgExpr (StgOpApp _ args res_ty) = runMaybeT $ do
164 -- We don't have enough type information to check
165 -- the application for StgFCallOp and StgPrimCallOp; ToDo
166 _maybe_arg_tys <- mapM (MaybeT . lintStgArg) args
167 return res_ty
168
169 lintStgExpr (StgLam bndrs _) = do
170 addErrL (text "Unexpected StgLam" <+> ppr bndrs)
171 return Nothing
172
173 lintStgExpr (StgLet binds body) = do
174 binders <- lintStgBinds binds
175 addLoc (BodyOfLetRec binders) $
176 addInScopeVars binders $
177 lintStgExpr body
178
179 lintStgExpr (StgLetNoEscape binds body) = do
180 binders <- lintStgBinds binds
181 addLoc (BodyOfLetRec binders) $
182 addInScopeVars binders $
183 lintStgExpr body
184
185 lintStgExpr (StgTick _ expr) = lintStgExpr expr
186
187 lintStgExpr (StgCase scrut bndr alts_type alts) = runMaybeT $ do
188 _ <- MaybeT $ lintStgExpr scrut
189
190 in_scope <- MaybeT $ liftM Just $
191 case alts_type of
192 AlgAlt tc -> check_bndr tc >> return True
193 PrimAlt tc -> check_bndr tc >> return True
194 UbxTupAlt _ -> return False -- Binder is always dead in this case
195 PolyAlt -> return True
196
197 MaybeT $ addInScopeVars [bndr | in_scope] $
198 lintStgAlts alts scrut_ty
199 where
200 scrut_ty = idType bndr
201 UnaryRep scrut_rep = repType scrut_ty -- Not used if scrutinee is unboxed tuple
202 check_bndr tc = case tyConAppTyCon_maybe scrut_rep of
203 Just bndr_tc -> checkL (tc == bndr_tc) bad_bndr
204 Nothing -> addErrL bad_bndr
205 where
206 bad_bndr = mkDefltMsg bndr tc
207
208 lintStgAlts :: [StgAlt]
209 -> Type -- Type of scrutinee
210 -> LintM (Maybe Type) -- Just ty => type is accurage
211
212 lintStgAlts alts scrut_ty = do
213 maybe_result_tys <- mapM (lintAlt scrut_ty) alts
214
215 -- Check the result types
216 case catMaybes (maybe_result_tys) of
217 [] -> return Nothing
218
219 (first_ty:_tys) -> do -- mapM_ check tys
220 return (Just first_ty)
221 where
222 -- check ty = checkTys first_ty ty (mkCaseAltMsg alts)
223 -- We can't check that the alternatives have the
224 -- same type, because they don't, with unsafeCoerce#
225
226 lintAlt :: Type -> (AltCon, [Id], [Bool], StgExpr) -> LintM (Maybe Type)
227 lintAlt _ (DEFAULT, _, _, rhs)
228 = lintStgExpr rhs
229
230 lintAlt scrut_ty (LitAlt lit, _, _, rhs) = do
231 checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty)
232 lintStgExpr rhs
233
234 lintAlt scrut_ty (DataAlt con, args, _, rhs) = do
235 case splitTyConApp_maybe scrut_ty of
236 Just (tycon, tys_applied) | isAlgTyCon tycon &&
237 not (isNewTyCon tycon) -> do
238 let
239 cons = tyConDataCons tycon
240 arg_tys = dataConInstArgTys con tys_applied
241 -- This does not work for existential constructors
242
243 checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con)
244 checkL (length args == dataConRepArity con) (mkAlgAltMsg3 con args)
245 when (isVanillaDataCon con) $
246 mapM_ check (zipEqual "lintAlgAlt:stg" arg_tys args)
247 return ()
248 _ ->
249 addErrL (mkAltMsg1 scrut_ty)
250
251 addInScopeVars args $
252 lintStgExpr rhs
253 where
254 check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
255
256 -- elem: yes, the elem-list here can sometimes be long-ish,
257 -- but as it's use-once, probably not worth doing anything different
258 -- We give it its own copy, so it isn't overloaded.
259 elem _ [] = False
260 elem x (y:ys) = x==y || elem x ys
261
262 {-
263 ************************************************************************
264 * *
265 \subsection[lint-monad]{The Lint monad}
266 * *
267 ************************************************************************
268 -}
269
270 newtype LintM a = LintM
271 { unLintM :: [LintLocInfo] -- Locations
272 -> IdSet -- Local vars in scope
273 -> Bag MsgDoc -- Error messages so far
274 -> (a, Bag MsgDoc) -- Result and error messages (if any)
275 }
276
277 data LintLocInfo
278 = RhsOf Id -- The variable bound
279 | LambdaBodyOf [Id] -- The lambda-binder
280 | BodyOfLetRec [Id] -- One of the binders
281
282 dumpLoc :: LintLocInfo -> (SrcSpan, SDoc)
283 dumpLoc (RhsOf v) =
284 (srcLocSpan (getSrcLoc v), text " [RHS of " <> pp_binders [v] <> char ']' )
285 dumpLoc (LambdaBodyOf bs) =
286 (srcLocSpan (getSrcLoc (head bs)), text " [in body of lambda with binders " <> pp_binders bs <> char ']' )
287
288 dumpLoc (BodyOfLetRec bs) =
289 (srcLocSpan (getSrcLoc (head bs)), text " [in body of letrec with binders " <> pp_binders bs <> char ']' )
290
291
292 pp_binders :: [Id] -> SDoc
293 pp_binders bs
294 = sep (punctuate comma (map pp_binder bs))
295 where
296 pp_binder b
297 = hsep [ppr b, dcolon, ppr (idType b)]
298
299 initL :: LintM a -> Maybe MsgDoc
300 initL (LintM m)
301 = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
302 if isEmptyBag errs then
303 Nothing
304 else
305 Just (vcat (punctuate blankLine (bagToList errs)))
306 }
307
308 instance Functor LintM where
309 fmap = liftM
310
311 instance Applicative LintM where
312 pure a = LintM $ \_loc _scope errs -> (a, errs)
313 (<*>) = ap
314 (*>) = thenL_
315
316 instance Monad LintM where
317 (>>=) = thenL
318 (>>) = (*>)
319
320 thenL :: LintM a -> (a -> LintM b) -> LintM b
321 thenL m k = LintM $ \loc scope errs
322 -> case unLintM m loc scope errs of
323 (r, errs') -> unLintM (k r) loc scope errs'
324
325 thenL_ :: LintM a -> LintM b -> LintM b
326 thenL_ m k = LintM $ \loc scope errs
327 -> case unLintM m loc scope errs of
328 (_, errs') -> unLintM k loc scope errs'
329
330 checkL :: Bool -> MsgDoc -> LintM ()
331 checkL True _ = return ()
332 checkL False msg = addErrL msg
333
334 addErrL :: MsgDoc -> LintM ()
335 addErrL msg = LintM $ \loc _scope errs -> ((), addErr errs msg loc)
336
337 addErr :: Bag MsgDoc -> MsgDoc -> [LintLocInfo] -> Bag MsgDoc
338 addErr errs_so_far msg locs
339 = errs_so_far `snocBag` mk_msg locs
340 where
341 mk_msg (loc:_) = let (l,hdr) = dumpLoc loc
342 in mkLocMessage SevWarning l (hdr $$ msg)
343 mk_msg [] = msg
344
345 addLoc :: LintLocInfo -> LintM a -> LintM a
346 addLoc extra_loc m = LintM $ \loc scope errs
347 -> unLintM m (extra_loc:loc) scope errs
348
349 addInScopeVars :: [Id] -> LintM a -> LintM a
350 addInScopeVars ids m = LintM $ \loc scope errs
351 -> -- We check if these "new" ids are already
352 -- in scope, i.e., we have *shadowing* going on.
353 -- For now, it's just a "trace"; we may make
354 -- a real error out of it...
355 let
356 new_set = mkVarSet ids
357 in
358 -- After adding -fliberate-case, Simon decided he likes shadowed
359 -- names after all. WDP 94/07
360 -- (if isEmptyVarSet shadowed
361 -- then id
362 -- else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $
363 unLintM m loc (scope `unionVarSet` new_set) errs
364
365 {-
366 Checking function applications: we only check that the type has the
367 right *number* of arrows, we don't actually compare the types. This
368 is because we can't expect the types to be equal - the type
369 applications and type lambdas that we use to calculate accurate types
370 have long since disappeared.
371 -}
372
373 checkFunApp :: Type -- The function type
374 -> [Type] -- The arg type(s)
375 -> MsgDoc -- Error message
376 -> LintM (Maybe Type) -- Just ty => result type is accurate
377
378 checkFunApp fun_ty arg_tys msg
379 = do { case mb_msg of
380 Just msg -> addErrL msg
381 Nothing -> return ()
382 ; return mb_ty }
383 where
384 (mb_ty, mb_msg) = cfa True fun_ty arg_tys
385
386 cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result?
387 , Maybe MsgDoc) -- Errors?
388
389 cfa accurate fun_ty [] -- Args have run out; that's fine
390 = (if accurate then Just fun_ty else Nothing, Nothing)
391
392 cfa accurate fun_ty arg_tys@(arg_ty':arg_tys')
393 | Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty
394 = if accurate && not (arg_ty `stgEqType` arg_ty')
395 then (Nothing, Just msg) -- Arg type mismatch
396 else cfa accurate res_ty arg_tys'
397
398 | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty
399 = cfa False fun_ty' arg_tys
400
401 | Just (tc,tc_args) <- splitTyConApp_maybe fun_ty
402 , isNewTyCon tc
403 = if length tc_args < tyConArity tc
404 then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg )
405 (Nothing, Nothing) -- This is odd, but I've seen it
406 else cfa False (newTyConInstRhs tc tc_args) arg_tys
407
408 | Just tc <- tyConAppTyCon_maybe fun_ty
409 , not (isTypeFamilyTyCon tc) -- Definite error
410 = (Nothing, Just msg) -- Too many args
411
412 | otherwise
413 = (Nothing, Nothing)
414
415 stgEqType :: Type -> Type -> Bool
416 -- Compare types, but crudely because we have discarded
417 -- both casts and type applications, so types might look
418 -- different but be the same. So reply "True" if in doubt.
419 -- "False" means that the types are definitely different.
420 --
421 -- Fundamentally this is a losing battle because of unsafeCoerce
422
423 stgEqType orig_ty1 orig_ty2
424 = gos (repType orig_ty1) (repType orig_ty2)
425 where
426 gos :: RepType -> RepType -> Bool
427 gos (UbxTupleRep tys1) (UbxTupleRep tys2)
428 = equalLength tys1 tys2 && and (zipWith go tys1 tys2)
429 gos (UnaryRep ty1) (UnaryRep ty2) = go ty1 ty2
430 gos _ _ = False
431
432 go :: UnaryType -> UnaryType -> Bool
433 go ty1 ty2
434 | Just (tc1, tc_args1) <- splitTyConApp_maybe ty1
435 , Just (tc2, tc_args2) <- splitTyConApp_maybe ty2
436 , let res = if tc1 == tc2
437 then equalLength tc_args1 tc_args2 && and (zipWith (gos `on` repType) tc_args1 tc_args2)
438 else -- TyCons don't match; but don't bleat if either is a
439 -- family TyCon because a coercion might have made it
440 -- equal to something else
441 (isFamilyTyCon tc1 || isFamilyTyCon tc2)
442 = if res then True
443 else
444 pprTrace "stgEqType: unequal" (vcat [ppr ty1, ppr ty2])
445 False
446
447 | otherwise = True -- Conservatively say "fine".
448 -- Type variables in particular
449
450 checkInScope :: Id -> LintM ()
451 checkInScope id = LintM $ \loc scope errs
452 -> if isLocalId id && not (id `elemVarSet` scope) then
453 ((), addErr errs (hsep [ppr id, text "is out of scope"]) loc)
454 else
455 ((), errs)
456
457 checkTys :: Type -> Type -> MsgDoc -> LintM ()
458 checkTys ty1 ty2 msg = LintM $ \loc _scope errs
459 -> if (ty1 `stgEqType` ty2)
460 then ((), errs)
461 else ((), addErr errs msg loc)
462
463 _mkCaseAltMsg :: [StgAlt] -> MsgDoc
464 _mkCaseAltMsg _alts
465 = ($$) (text "In some case alternatives, type of alternatives not all same:")
466 (Outputable.empty) -- LATER: ppr alts
467
468 mkDefltMsg :: Id -> TyCon -> MsgDoc
469 mkDefltMsg bndr tc
470 = ($$) (text "Binder of a case expression doesn't match type of scrutinee:")
471 (ppr bndr $$ ppr (idType bndr) $$ ppr tc)
472
473 mkFunAppMsg :: Type -> [Type] -> StgExpr -> MsgDoc
474 mkFunAppMsg fun_ty arg_tys expr
475 = vcat [text "In a function application, function type doesn't match arg types:",
476 hang (text "Function type:") 4 (ppr fun_ty),
477 hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys)),
478 hang (text "Expression:") 4 (ppr expr)]
479
480 mkRhsConMsg :: Type -> [Type] -> MsgDoc
481 mkRhsConMsg fun_ty arg_tys
482 = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
483 hang (text "Constructor type:") 4 (ppr fun_ty),
484 hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys))]
485
486 mkAltMsg1 :: Type -> MsgDoc
487 mkAltMsg1 ty
488 = ($$) (text "In a case expression, type of scrutinee does not match patterns")
489 (ppr ty)
490
491 mkAlgAltMsg2 :: Type -> DataCon -> MsgDoc
492 mkAlgAltMsg2 ty con
493 = vcat [
494 text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
495 ppr ty,
496 ppr con
497 ]
498
499 mkAlgAltMsg3 :: DataCon -> [Id] -> MsgDoc
500 mkAlgAltMsg3 con alts
501 = vcat [
502 text "In some algebraic case alternative, number of arguments doesn't match constructor:",
503 ppr con,
504 ppr alts
505 ]
506
507 mkAlgAltMsg4 :: Type -> Id -> MsgDoc
508 mkAlgAltMsg4 ty arg
509 = vcat [
510 text "In some algebraic case alternative, type of argument doesn't match data constructor:",
511 ppr ty,
512 ppr arg
513 ]
514
515 _mkRhsMsg :: Id -> Type -> MsgDoc
516 _mkRhsMsg binder ty
517 = vcat [hsep [text "The type of this binder doesn't match the type of its RHS:",
518 ppr binder],
519 hsep [text "Binder's type:", ppr (idType binder)],
520 hsep [text "Rhs type:", ppr ty]
521 ]
522
523 mkUnliftedTyMsg :: Id -> StgRhs -> SDoc
524 mkUnliftedTyMsg binder rhs
525 = (text "Let(rec) binder" <+> quotes (ppr binder) <+>
526 text "has unlifted type" <+> quotes (ppr (idType binder)))
527 $$
528 (text "RHS:" <+> ppr rhs)