b3f718241e25cdc42ffdf227beb34a7e701144c4
[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], 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 -> let
352 new_set = mkVarSet ids
353 in unLintM m loc (scope `unionVarSet` new_set) errs
354
355 {-
356 Checking function applications: we only check that the type has the
357 right *number* of arrows, we don't actually compare the types. This
358 is because we can't expect the types to be equal - the type
359 applications and type lambdas that we use to calculate accurate types
360 have long since disappeared.
361 -}
362
363 checkFunApp :: Type -- The function type
364 -> [Type] -- The arg type(s)
365 -> MsgDoc -- Error message
366 -> LintM (Maybe Type) -- Just ty => result type is accurate
367
368 checkFunApp fun_ty arg_tys msg
369 = do { case mb_msg of
370 Just msg -> addErrL msg
371 Nothing -> return ()
372 ; return mb_ty }
373 where
374 (mb_ty, mb_msg) = cfa True fun_ty arg_tys
375
376 cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result?
377 , Maybe MsgDoc) -- Errors?
378
379 cfa accurate fun_ty [] -- Args have run out; that's fine
380 = (if accurate then Just fun_ty else Nothing, Nothing)
381
382 cfa accurate fun_ty arg_tys@(arg_ty':arg_tys')
383 | Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty
384 = if accurate && not (arg_ty `stgEqType` arg_ty')
385 then (Nothing, Just msg) -- Arg type mismatch
386 else cfa accurate res_ty arg_tys'
387
388 | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty
389 = cfa False fun_ty' arg_tys
390
391 | Just (tc,tc_args) <- splitTyConApp_maybe fun_ty
392 , isNewTyCon tc
393 = if length tc_args < tyConArity tc
394 then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg )
395 (Nothing, Nothing) -- This is odd, but I've seen it
396 else cfa False (newTyConInstRhs tc tc_args) arg_tys
397
398 | Just tc <- tyConAppTyCon_maybe fun_ty
399 , not (isTypeFamilyTyCon tc) -- Definite error
400 = (Nothing, Just msg) -- Too many args
401
402 | otherwise
403 = (Nothing, Nothing)
404
405 stgEqType :: Type -> Type -> Bool
406 -- Compare types, but crudely because we have discarded
407 -- both casts and type applications, so types might look
408 -- different but be the same. So reply "True" if in doubt.
409 -- "False" means that the types are definitely different.
410 --
411 -- Fundamentally this is a losing battle because of unsafeCoerce
412
413 stgEqType orig_ty1 orig_ty2
414 = gos (repType orig_ty1) (repType orig_ty2)
415 where
416 gos :: RepType -> RepType -> Bool
417 gos (UbxTupleRep tys1) (UbxTupleRep tys2)
418 = equalLength tys1 tys2 && and (zipWith go tys1 tys2)
419 gos (UnaryRep ty1) (UnaryRep ty2) = go ty1 ty2
420 gos _ _ = False
421
422 go :: UnaryType -> UnaryType -> Bool
423 go ty1 ty2
424 | Just (tc1, tc_args1) <- splitTyConApp_maybe ty1
425 , Just (tc2, tc_args2) <- splitTyConApp_maybe ty2
426 , let res = if tc1 == tc2
427 then equalLength tc_args1 tc_args2 && and (zipWith (gos `on` repType) tc_args1 tc_args2)
428 else -- TyCons don't match; but don't bleat if either is a
429 -- family TyCon because a coercion might have made it
430 -- equal to something else
431 (isFamilyTyCon tc1 || isFamilyTyCon tc2)
432 = if res then True
433 else
434 pprTrace "stgEqType: unequal" (vcat [ppr ty1, ppr ty2])
435 False
436
437 | otherwise = True -- Conservatively say "fine".
438 -- Type variables in particular
439
440 checkInScope :: Id -> LintM ()
441 checkInScope id = LintM $ \loc scope errs
442 -> if isLocalId id && not (id `elemVarSet` scope) then
443 ((), addErr errs (hsep [ppr id, text "is out of scope"]) loc)
444 else
445 ((), errs)
446
447 checkTys :: Type -> Type -> MsgDoc -> LintM ()
448 checkTys ty1 ty2 msg = LintM $ \loc _scope errs
449 -> if (ty1 `stgEqType` ty2)
450 then ((), errs)
451 else ((), addErr errs msg loc)
452
453 _mkCaseAltMsg :: [StgAlt] -> MsgDoc
454 _mkCaseAltMsg _alts
455 = ($$) (text "In some case alternatives, type of alternatives not all same:")
456 (Outputable.empty) -- LATER: ppr alts
457
458 mkDefltMsg :: Id -> TyCon -> MsgDoc
459 mkDefltMsg bndr tc
460 = ($$) (text "Binder of a case expression doesn't match type of scrutinee:")
461 (ppr bndr $$ ppr (idType bndr) $$ ppr tc)
462
463 mkFunAppMsg :: Type -> [Type] -> StgExpr -> MsgDoc
464 mkFunAppMsg fun_ty arg_tys expr
465 = vcat [text "In a function application, function type doesn't match arg types:",
466 hang (text "Function type:") 4 (ppr fun_ty),
467 hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys)),
468 hang (text "Expression:") 4 (ppr expr)]
469
470 mkRhsConMsg :: Type -> [Type] -> MsgDoc
471 mkRhsConMsg fun_ty arg_tys
472 = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
473 hang (text "Constructor type:") 4 (ppr fun_ty),
474 hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys))]
475
476 mkAltMsg1 :: Type -> MsgDoc
477 mkAltMsg1 ty
478 = ($$) (text "In a case expression, type of scrutinee does not match patterns")
479 (ppr ty)
480
481 mkAlgAltMsg2 :: Type -> DataCon -> MsgDoc
482 mkAlgAltMsg2 ty con
483 = vcat [
484 text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
485 ppr ty,
486 ppr con
487 ]
488
489 mkAlgAltMsg3 :: DataCon -> [Id] -> MsgDoc
490 mkAlgAltMsg3 con alts
491 = vcat [
492 text "In some algebraic case alternative, number of arguments doesn't match constructor:",
493 ppr con,
494 ppr alts
495 ]
496
497 mkAlgAltMsg4 :: Type -> Id -> MsgDoc
498 mkAlgAltMsg4 ty arg
499 = vcat [
500 text "In some algebraic case alternative, type of argument doesn't match data constructor:",
501 ppr ty,
502 ppr arg
503 ]
504
505 _mkRhsMsg :: Id -> Type -> MsgDoc
506 _mkRhsMsg binder ty
507 = vcat [hsep [text "The type of this binder doesn't match the type of its RHS:",
508 ppr binder],
509 hsep [text "Binder's type:", ppr (idType binder)],
510 hsep [text "Rhs type:", ppr ty]
511 ]
512
513 mkUnliftedTyMsg :: Id -> StgRhs -> SDoc
514 mkUnliftedTyMsg binder rhs
515 = (text "Let(rec) binder" <+> quotes (ppr binder) <+>
516 text "has unlifted type" <+> quotes (ppr (idType binder)))
517 $$
518 (text "RHS:" <+> ppr rhs)