e31e7ae0156dc84252187446d93eae2031c8340d
[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 (tyConPrimRep tc) >> return True
200 PrimAlt rep -> check_bndr [rep] >> 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 scrut_reps = typePrimRep scrut_ty
209 check_bndr reps = checkL (scrut_reps == reps) bad_bndr
210 where
211 bad_bndr = mkDefltMsg bndr reps
212
213 lintStgAlts :: [StgAlt]
214 -> Type -- Type of scrutinee
215 -> LintM (Maybe Type) -- Just ty => type is accurage
216
217 lintStgAlts alts scrut_ty = do
218 maybe_result_tys <- mapM (lintAlt scrut_ty) alts
219
220 -- Check the result types
221 case catMaybes (maybe_result_tys) of
222 [] -> return Nothing
223
224 (first_ty:_tys) -> do -- mapM_ check tys
225 return (Just first_ty)
226 where
227 -- check ty = checkTys first_ty ty (mkCaseAltMsg alts)
228 -- We can't check that the alternatives have the
229 -- same type, because they don't, with unsafeCoerce#
230
231 lintAlt :: Type -> (AltCon, [Id], StgExpr) -> LintM (Maybe Type)
232 lintAlt _ (DEFAULT, _, rhs)
233 = lintStgExpr rhs
234
235 lintAlt scrut_ty (LitAlt lit, _, rhs) = do
236 checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty)
237 lintStgExpr rhs
238
239 lintAlt scrut_ty (DataAlt con, args, rhs) = do
240 case splitTyConApp_maybe scrut_ty of
241 Just (tycon, tys_applied) | isAlgTyCon tycon &&
242 not (isNewTyCon tycon) -> do
243 let
244 cons = tyConDataCons tycon
245 arg_tys = dataConInstArgTys con tys_applied
246 -- This does not work for existential constructors
247
248 checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con)
249 checkL (length args == dataConRepArity con) (mkAlgAltMsg3 con args)
250 when (isVanillaDataCon con) $
251 mapM_ check (zipEqual "lintAlgAlt:stg" arg_tys args)
252 return ()
253 _ ->
254 addErrL (mkAltMsg1 scrut_ty)
255
256 addInScopeVars args $
257 lintStgExpr rhs
258 where
259 check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
260
261 -- elem: yes, the elem-list here can sometimes be long-ish,
262 -- but as it's use-once, probably not worth doing anything different
263 -- We give it its own copy, so it isn't overloaded.
264 elem _ [] = False
265 elem x (y:ys) = x==y || elem x ys
266
267 {-
268 ************************************************************************
269 * *
270 \subsection[lint-monad]{The Lint monad}
271 * *
272 ************************************************************************
273 -}
274
275 newtype LintM a = LintM
276 { unLintM :: [LintLocInfo] -- Locations
277 -> IdSet -- Local vars in scope
278 -> Bag MsgDoc -- Error messages so far
279 -> (a, Bag MsgDoc) -- Result and error messages (if any)
280 }
281
282 data LintLocInfo
283 = RhsOf Id -- The variable bound
284 | LambdaBodyOf [Id] -- The lambda-binder
285 | BodyOfLetRec [Id] -- One of the binders
286
287 dumpLoc :: LintLocInfo -> (SrcSpan, SDoc)
288 dumpLoc (RhsOf v) =
289 (srcLocSpan (getSrcLoc v), text " [RHS of " <> pp_binders [v] <> char ']' )
290 dumpLoc (LambdaBodyOf bs) =
291 (srcLocSpan (getSrcLoc (head bs)), text " [in body of lambda with binders " <> pp_binders bs <> char ']' )
292
293 dumpLoc (BodyOfLetRec bs) =
294 (srcLocSpan (getSrcLoc (head bs)), text " [in body of letrec with binders " <> pp_binders bs <> char ']' )
295
296
297 pp_binders :: [Id] -> SDoc
298 pp_binders bs
299 = sep (punctuate comma (map pp_binder bs))
300 where
301 pp_binder b
302 = hsep [ppr b, dcolon, ppr (idType b)]
303
304 initL :: LintM a -> Maybe MsgDoc
305 initL (LintM m)
306 = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
307 if isEmptyBag errs then
308 Nothing
309 else
310 Just (vcat (punctuate blankLine (bagToList errs)))
311 }
312
313 instance Functor LintM where
314 fmap = liftM
315
316 instance Applicative LintM where
317 pure a = LintM $ \_loc _scope errs -> (a, errs)
318 (<*>) = ap
319 (*>) = thenL_
320
321 instance Monad LintM where
322 (>>=) = thenL
323 (>>) = (*>)
324
325 thenL :: LintM a -> (a -> LintM b) -> LintM b
326 thenL m k = LintM $ \loc scope errs
327 -> case unLintM m loc scope errs of
328 (r, errs') -> unLintM (k r) loc scope errs'
329
330 thenL_ :: LintM a -> LintM b -> LintM b
331 thenL_ m k = LintM $ \loc scope errs
332 -> case unLintM m loc scope errs of
333 (_, errs') -> unLintM k loc scope errs'
334
335 checkL :: Bool -> MsgDoc -> LintM ()
336 checkL True _ = return ()
337 checkL False msg = addErrL msg
338
339 addErrL :: MsgDoc -> LintM ()
340 addErrL msg = LintM $ \loc _scope errs -> ((), addErr errs msg loc)
341
342 addErr :: Bag MsgDoc -> MsgDoc -> [LintLocInfo] -> Bag MsgDoc
343 addErr errs_so_far msg locs
344 = errs_so_far `snocBag` mk_msg locs
345 where
346 mk_msg (loc:_) = let (l,hdr) = dumpLoc loc
347 in mkLocMessage SevWarning l (hdr $$ msg)
348 mk_msg [] = msg
349
350 addLoc :: LintLocInfo -> LintM a -> LintM a
351 addLoc extra_loc m = LintM $ \loc scope errs
352 -> unLintM m (extra_loc:loc) scope errs
353
354 addInScopeVars :: [Id] -> LintM a -> LintM a
355 addInScopeVars ids m = LintM $ \loc scope errs
356 -> let
357 new_set = mkVarSet ids
358 in unLintM m loc (scope `unionVarSet` new_set) errs
359
360 {-
361 Checking function applications: we only check that the type has the
362 right *number* of arrows, we don't actually compare the types. This
363 is because we can't expect the types to be equal - the type
364 applications and type lambdas that we use to calculate accurate types
365 have long since disappeared.
366 -}
367
368 checkFunApp :: Type -- The function type
369 -> [Type] -- The arg type(s)
370 -> MsgDoc -- Error message
371 -> LintM (Maybe Type) -- Just ty => result type is accurate
372
373 checkFunApp fun_ty arg_tys msg
374 = do { case mb_msg of
375 Just msg -> addErrL msg
376 Nothing -> return ()
377 ; return mb_ty }
378 where
379 (mb_ty, mb_msg) = cfa True fun_ty arg_tys
380
381 cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result?
382 , Maybe MsgDoc) -- Errors?
383
384 cfa accurate fun_ty [] -- Args have run out; that's fine
385 = (if accurate then Just fun_ty else Nothing, Nothing)
386
387 cfa accurate fun_ty arg_tys@(arg_ty':arg_tys')
388 | Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty
389 = if accurate && not (arg_ty `stgEqType` arg_ty')
390 then (Nothing, Just msg) -- Arg type mismatch
391 else cfa accurate res_ty arg_tys'
392
393 | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty
394 = cfa False fun_ty' arg_tys
395
396 | Just (tc,tc_args) <- splitTyConApp_maybe fun_ty
397 , isNewTyCon tc
398 = if length tc_args < tyConArity tc
399 then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg )
400 (Nothing, Nothing) -- This is odd, but I've seen it
401 else cfa False (newTyConInstRhs tc tc_args) arg_tys
402
403 | Just tc <- tyConAppTyCon_maybe fun_ty
404 , not (isTypeFamilyTyCon tc) -- Definite error
405 = (Nothing, Just msg) -- Too many args
406
407 | otherwise
408 = (Nothing, Nothing)
409
410 stgEqType :: Type -> Type -> Bool
411 -- Compare types, but crudely because we have discarded
412 -- both casts and type applications, so types might look
413 -- different but be the same. So reply "True" if in doubt.
414 -- "False" means that the types are definitely different.
415 --
416 -- Fundamentally this is a losing battle because of unsafeCoerce
417
418 stgEqType orig_ty1 orig_ty2
419 = gos (typePrimRep orig_ty1) (typePrimRep orig_ty2)
420 where
421 gos :: [PrimRep] -> [PrimRep] -> Bool
422 gos [_] [_] = go orig_ty1 orig_ty2
423 gos reps1 reps2 = reps1 == reps2
424
425 go :: UnaryType -> UnaryType -> Bool
426 go ty1 ty2
427 | Just (tc1, tc_args1) <- splitTyConApp_maybe ty1
428 , Just (tc2, tc_args2) <- splitTyConApp_maybe ty2
429 , let res = if tc1 == tc2
430 then equalLength tc_args1 tc_args2 && and (zipWith (gos `on` typePrimRep) tc_args1 tc_args2)
431 else -- TyCons don't match; but don't bleat if either is a
432 -- family TyCon because a coercion might have made it
433 -- equal to something else
434 (isFamilyTyCon tc1 || isFamilyTyCon tc2)
435 = if res then True
436 else
437 pprTrace "stgEqType: unequal" (vcat [ppr ty1, ppr ty2])
438 False
439
440 | otherwise = True -- Conservatively say "fine".
441 -- Type variables in particular
442
443 checkInScope :: Id -> LintM ()
444 checkInScope id = LintM $ \loc scope errs
445 -> if isLocalId id && not (id `elemVarSet` scope) then
446 ((), addErr errs (hsep [ppr id, text "is out of scope"]) loc)
447 else
448 ((), errs)
449
450 checkTys :: Type -> Type -> MsgDoc -> LintM ()
451 checkTys ty1 ty2 msg = LintM $ \loc _scope errs
452 -> if (ty1 `stgEqType` ty2)
453 then ((), errs)
454 else ((), addErr errs msg loc)
455
456 _mkCaseAltMsg :: [StgAlt] -> MsgDoc
457 _mkCaseAltMsg _alts
458 = ($$) (text "In some case alternatives, type of alternatives not all same:")
459 (Outputable.empty) -- LATER: ppr alts
460
461 mkDefltMsg :: Id -> [PrimRep] -> MsgDoc
462 mkDefltMsg bndr reps
463 = ($$) (text "Binder of a case expression doesn't match representation of scrutinee:")
464 (ppr bndr $$ ppr (idType bndr) $$ ppr reps)
465
466 mkFunAppMsg :: Type -> [Type] -> StgExpr -> MsgDoc
467 mkFunAppMsg fun_ty arg_tys expr
468 = vcat [text "In a function application, function type doesn't match arg types:",
469 hang (text "Function type:") 4 (ppr fun_ty),
470 hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys)),
471 hang (text "Expression:") 4 (ppr expr)]
472
473 mkRhsConMsg :: Type -> [Type] -> MsgDoc
474 mkRhsConMsg fun_ty arg_tys
475 = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
476 hang (text "Constructor type:") 4 (ppr fun_ty),
477 hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys))]
478
479 mkAltMsg1 :: Type -> MsgDoc
480 mkAltMsg1 ty
481 = ($$) (text "In a case expression, type of scrutinee does not match patterns")
482 (ppr ty)
483
484 mkAlgAltMsg2 :: Type -> DataCon -> MsgDoc
485 mkAlgAltMsg2 ty con
486 = vcat [
487 text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
488 ppr ty,
489 ppr con
490 ]
491
492 mkAlgAltMsg3 :: DataCon -> [Id] -> MsgDoc
493 mkAlgAltMsg3 con alts
494 = vcat [
495 text "In some algebraic case alternative, number of arguments doesn't match constructor:",
496 ppr con,
497 ppr alts
498 ]
499
500 mkAlgAltMsg4 :: Type -> Id -> MsgDoc
501 mkAlgAltMsg4 ty arg
502 = vcat [
503 text "In some algebraic case alternative, type of argument doesn't match data constructor:",
504 ppr ty,
505 ppr arg
506 ]
507
508 _mkRhsMsg :: Id -> Type -> MsgDoc
509 _mkRhsMsg binder ty
510 = vcat [hsep [text "The type of this binder doesn't match the type of its RHS:",
511 ppr binder],
512 hsep [text "Binder's type:", ppr (idType binder)],
513 hsep [text "Rhs type:", ppr ty]
514 ]
515
516 mkUnliftedTyMsg :: Id -> StgRhs -> SDoc
517 mkUnliftedTyMsg binder rhs
518 = (text "Let(rec) binder" <+> quotes (ppr binder) <+>
519 text "has unlifted type" <+> quotes (ppr (idType binder)))
520 $$
521 (text "RHS:" <+> ppr rhs)