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