Remove some redundant definitions/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 TyCon
25 import Util
26 import SrcLoc
27 import Outputable
28 import FastString
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 ptext (sLit "*** Stg Lint ErrMsgs: in") <+>
68 text whodunnit <+> ptext (sLit "***"),
69 msg,
70 ptext (sLit "*** Offending Program ***"),
71 pprStgBindings binds,
72 ptext (sLit "*** 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 (StgRhsCon _ con args) = runMaybeT $ do
138 arg_tys <- mapM (MaybeT . lintStgArg) args
139 MaybeT $ checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys)
140 where
141 con_ty = dataConRepType con
142
143 lintStgExpr :: StgExpr -> LintM (Maybe Type) -- Just ty => type is exact
144
145 lintStgExpr (StgLit l) = return (Just (literalType l))
146
147 lintStgExpr e@(StgApp fun args) = runMaybeT $ do
148 fun_ty <- MaybeT $ lintStgVar fun
149 arg_tys <- mapM (MaybeT . lintStgArg) args
150 MaybeT $ checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e)
151
152 lintStgExpr e@(StgConApp con args) = runMaybeT $ do
153 arg_tys <- mapM (MaybeT . lintStgArg) args
154 MaybeT $ checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e)
155 where
156 con_ty = dataConRepType con
157
158 lintStgExpr e@(StgOpApp (StgPrimOp op) args _) = runMaybeT $ do
159 arg_tys <- mapM (MaybeT . lintStgArg) args
160 MaybeT $ checkFunApp op_ty arg_tys (mkFunAppMsg op_ty arg_tys e)
161 where
162 op_ty = primOpType op
163
164 lintStgExpr (StgOpApp _ args res_ty) = runMaybeT $ do
165 -- We don't have enough type information to check
166 -- the application for StgFCallOp and StgPrimCallOp; ToDo
167 _maybe_arg_tys <- mapM (MaybeT . lintStgArg) args
168 return res_ty
169
170 lintStgExpr (StgLam bndrs _) = do
171 addErrL (ptext (sLit "Unexpected StgLam") <+> ppr bndrs)
172 return Nothing
173
174 lintStgExpr (StgLet binds body) = do
175 binders <- lintStgBinds binds
176 addLoc (BodyOfLetRec binders) $
177 addInScopeVars binders $
178 lintStgExpr body
179
180 lintStgExpr (StgLetNoEscape _ _ binds body) = do
181 binders <- lintStgBinds binds
182 addLoc (BodyOfLetRec binders) $
183 addInScopeVars binders $
184 lintStgExpr body
185
186 lintStgExpr (StgTick _ expr) = lintStgExpr expr
187
188 lintStgExpr (StgCase scrut _ _ bndr _ alts_type alts) = runMaybeT $ do
189 _ <- MaybeT $ lintStgExpr scrut
190
191 in_scope <- MaybeT $ liftM Just $
192 case alts_type of
193 AlgAlt tc -> check_bndr tc >> return True
194 PrimAlt tc -> check_bndr tc >> return True
195 UbxTupAlt _ -> return False -- Binder is always dead in this case
196 PolyAlt -> return True
197
198 MaybeT $ addInScopeVars [bndr | in_scope] $
199 lintStgAlts alts scrut_ty
200 where
201 scrut_ty = idType bndr
202 UnaryRep scrut_rep = repType scrut_ty -- Not used if scrutinee is unboxed tuple
203 check_bndr tc = case tyConAppTyCon_maybe scrut_rep of
204 Just bndr_tc -> checkL (tc == bndr_tc) bad_bndr
205 Nothing -> addErrL bad_bndr
206 where
207 bad_bndr = mkDefltMsg bndr tc
208
209 lintStgAlts :: [StgAlt]
210 -> Type -- Type of scrutinee
211 -> LintM (Maybe Type) -- Just ty => type is accurage
212
213 lintStgAlts alts scrut_ty = do
214 maybe_result_tys <- mapM (lintAlt scrut_ty) alts
215
216 -- Check the result types
217 case catMaybes (maybe_result_tys) of
218 [] -> return Nothing
219
220 (first_ty:_tys) -> do -- mapM_ check tys
221 return (Just first_ty)
222 where
223 -- check ty = checkTys first_ty ty (mkCaseAltMsg alts)
224 -- We can't check that the alternatives have the
225 -- same type, because they don't, with unsafeCoerce#
226
227 lintAlt :: Type -> (AltCon, [Id], [Bool], StgExpr) -> LintM (Maybe Type)
228 lintAlt _ (DEFAULT, _, _, rhs)
229 = lintStgExpr rhs
230
231 lintAlt scrut_ty (LitAlt lit, _, _, rhs) = do
232 checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty)
233 lintStgExpr rhs
234
235 lintAlt scrut_ty (DataAlt con, args, _, rhs) = do
236 case splitTyConApp_maybe scrut_ty of
237 Just (tycon, tys_applied) | isAlgTyCon tycon &&
238 not (isNewTyCon tycon) -> do
239 let
240 cons = tyConDataCons tycon
241 arg_tys = dataConInstArgTys con tys_applied
242 -- This does not work for existential constructors
243
244 checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con)
245 checkL (length args == dataConRepArity con) (mkAlgAltMsg3 con args)
246 when (isVanillaDataCon con) $
247 mapM_ check (zipEqual "lintAlgAlt:stg" arg_tys args)
248 return ()
249 _ ->
250 addErrL (mkAltMsg1 scrut_ty)
251
252 addInScopeVars args $
253 lintStgExpr rhs
254 where
255 check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
256
257 -- elem: yes, the elem-list here can sometimes be long-ish,
258 -- but as it's use-once, probably not worth doing anything different
259 -- We give it its own copy, so it isn't overloaded.
260 elem _ [] = False
261 elem x (y:ys) = x==y || elem x ys
262
263 {-
264 ************************************************************************
265 * *
266 \subsection[lint-monad]{The Lint monad}
267 * *
268 ************************************************************************
269 -}
270
271 newtype LintM a = LintM
272 { unLintM :: [LintLocInfo] -- Locations
273 -> IdSet -- Local vars in scope
274 -> Bag MsgDoc -- Error messages so far
275 -> (a, Bag MsgDoc) -- Result and error messages (if any)
276 }
277
278 data LintLocInfo
279 = RhsOf Id -- The variable bound
280 | LambdaBodyOf [Id] -- The lambda-binder
281 | BodyOfLetRec [Id] -- One of the binders
282
283 dumpLoc :: LintLocInfo -> (SrcSpan, SDoc)
284 dumpLoc (RhsOf v) =
285 (srcLocSpan (getSrcLoc v), ptext (sLit " [RHS of ") <> pp_binders [v] <> char ']' )
286 dumpLoc (LambdaBodyOf bs) =
287 (srcLocSpan (getSrcLoc (head bs)), ptext (sLit " [in body of lambda with binders ") <> pp_binders bs <> char ']' )
288
289 dumpLoc (BodyOfLetRec bs) =
290 (srcLocSpan (getSrcLoc (head bs)), ptext (sLit " [in body of letrec with binders ") <> pp_binders bs <> char ']' )
291
292
293 pp_binders :: [Id] -> SDoc
294 pp_binders bs
295 = sep (punctuate comma (map pp_binder bs))
296 where
297 pp_binder b
298 = hsep [ppr b, dcolon, ppr (idType b)]
299
300 initL :: LintM a -> Maybe MsgDoc
301 initL (LintM m)
302 = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
303 if isEmptyBag errs then
304 Nothing
305 else
306 Just (vcat (punctuate blankLine (bagToList errs)))
307 }
308
309 instance Functor LintM where
310 fmap = liftM
311
312 instance Applicative LintM where
313 pure a = LintM $ \_loc _scope errs -> (a, errs)
314 (<*>) = ap
315 (*>) = thenL_
316
317 instance Monad LintM where
318 (>>=) = thenL
319 (>>) = (*>)
320
321 thenL :: LintM a -> (a -> LintM b) -> LintM b
322 thenL m k = LintM $ \loc scope errs
323 -> case unLintM m loc scope errs of
324 (r, errs') -> unLintM (k r) loc scope errs'
325
326 thenL_ :: LintM a -> LintM b -> LintM b
327 thenL_ m k = LintM $ \loc scope errs
328 -> case unLintM m loc scope errs of
329 (_, errs') -> unLintM k loc scope errs'
330
331 checkL :: Bool -> MsgDoc -> LintM ()
332 checkL True _ = return ()
333 checkL False msg = addErrL msg
334
335 addErrL :: MsgDoc -> LintM ()
336 addErrL msg = LintM $ \loc _scope errs -> ((), addErr errs msg loc)
337
338 addErr :: Bag MsgDoc -> MsgDoc -> [LintLocInfo] -> Bag MsgDoc
339 addErr errs_so_far msg locs
340 = errs_so_far `snocBag` mk_msg locs
341 where
342 mk_msg (loc:_) = let (l,hdr) = dumpLoc loc
343 in mkLocMessage SevWarning l (hdr $$ msg)
344 mk_msg [] = msg
345
346 addLoc :: LintLocInfo -> LintM a -> LintM a
347 addLoc extra_loc m = LintM $ \loc scope errs
348 -> unLintM m (extra_loc:loc) scope errs
349
350 addInScopeVars :: [Id] -> LintM a -> LintM a
351 addInScopeVars ids m = LintM $ \loc scope errs
352 -> -- We check if these "new" ids are already
353 -- in scope, i.e., we have *shadowing* going on.
354 -- For now, it's just a "trace"; we may make
355 -- a real error out of it...
356 let
357 new_set = mkVarSet ids
358 in
359 -- After adding -fliberate-case, Simon decided he likes shadowed
360 -- names after all. WDP 94/07
361 -- (if isEmptyVarSet shadowed
362 -- then id
363 -- else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $
364 unLintM m loc (scope `unionVarSet` new_set) errs
365
366 {-
367 Checking function applications: we only check that the type has the
368 right *number* of arrows, we don't actually compare the types. This
369 is because we can't expect the types to be equal - the type
370 applications and type lambdas that we use to calculate accurate types
371 have long since disappeared.
372 -}
373
374 checkFunApp :: Type -- The function type
375 -> [Type] -- The arg type(s)
376 -> MsgDoc -- Error message
377 -> LintM (Maybe Type) -- Just ty => result type is accurate
378
379 checkFunApp fun_ty arg_tys msg
380 = do { case mb_msg of
381 Just msg -> addErrL msg
382 Nothing -> return ()
383 ; return mb_ty }
384 where
385 (mb_ty, mb_msg) = cfa True fun_ty arg_tys
386
387 cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result?
388 , Maybe MsgDoc) -- Errors?
389
390 cfa accurate fun_ty [] -- Args have run out; that's fine
391 = (if accurate then Just fun_ty else Nothing, Nothing)
392
393 cfa accurate fun_ty arg_tys@(arg_ty':arg_tys')
394 | Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty
395 = if accurate && not (arg_ty `stgEqType` arg_ty')
396 then (Nothing, Just msg) -- Arg type mismatch
397 else cfa accurate res_ty arg_tys'
398
399 | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty
400 = cfa False fun_ty' arg_tys
401
402 | Just (tc,tc_args) <- splitTyConApp_maybe fun_ty
403 , isNewTyCon tc
404 = if length tc_args < tyConArity tc
405 then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg )
406 (Nothing, Nothing) -- This is odd, but I've seen it
407 else cfa False (newTyConInstRhs tc tc_args) arg_tys
408
409 | Just tc <- tyConAppTyCon_maybe fun_ty
410 , not (isTypeFamilyTyCon tc) -- Definite error
411 = (Nothing, Just msg) -- Too many args
412
413 | otherwise
414 = (Nothing, Nothing)
415
416 stgEqType :: Type -> Type -> Bool
417 -- Compare types, but crudely because we have discarded
418 -- both casts and type applications, so types might look
419 -- different but be the same. So reply "True" if in doubt.
420 -- "False" means that the types are definitely different.
421 --
422 -- Fundamentally this is a losing battle because of unsafeCoerce
423
424 stgEqType orig_ty1 orig_ty2
425 = gos (repType orig_ty1) (repType orig_ty2)
426 where
427 gos :: RepType -> RepType -> Bool
428 gos (UbxTupleRep tys1) (UbxTupleRep tys2)
429 = equalLength tys1 tys2 && and (zipWith go tys1 tys2)
430 gos (UnaryRep ty1) (UnaryRep ty2) = go ty1 ty2
431 gos _ _ = False
432
433 go :: UnaryType -> UnaryType -> Bool
434 go ty1 ty2
435 | Just (tc1, tc_args1) <- splitTyConApp_maybe ty1
436 , Just (tc2, tc_args2) <- splitTyConApp_maybe ty2
437 , let res = if tc1 == tc2
438 then equalLength tc_args1 tc_args2 && and (zipWith (gos `on` repType) tc_args1 tc_args2)
439 else -- TyCons don't match; but don't bleat if either is a
440 -- family TyCon because a coercion might have made it
441 -- equal to something else
442 (isFamilyTyCon tc1 || isFamilyTyCon tc2)
443 = if res then True
444 else
445 pprTrace "stgEqType: unequal" (vcat [ppr ty1, ppr ty2])
446 False
447
448 | otherwise = True -- Conservatively say "fine".
449 -- Type variables in particular
450
451 checkInScope :: Id -> LintM ()
452 checkInScope id = LintM $ \loc scope errs
453 -> if isLocalId id && not (id `elemVarSet` scope) then
454 ((), addErr errs (hsep [ppr id, ptext (sLit "is out of scope")]) loc)
455 else
456 ((), errs)
457
458 checkTys :: Type -> Type -> MsgDoc -> LintM ()
459 checkTys ty1 ty2 msg = LintM $ \loc _scope errs
460 -> if (ty1 `stgEqType` ty2)
461 then ((), errs)
462 else ((), addErr errs msg loc)
463
464 _mkCaseAltMsg :: [StgAlt] -> MsgDoc
465 _mkCaseAltMsg _alts
466 = ($$) (text "In some case alternatives, type of alternatives not all same:")
467 (Outputable.empty) -- LATER: ppr alts
468
469 mkDefltMsg :: Id -> TyCon -> MsgDoc
470 mkDefltMsg bndr tc
471 = ($$) (ptext (sLit "Binder of a case expression doesn't match type of scrutinee:"))
472 (ppr bndr $$ ppr (idType bndr) $$ ppr tc)
473
474 mkFunAppMsg :: Type -> [Type] -> StgExpr -> MsgDoc
475 mkFunAppMsg fun_ty arg_tys expr
476 = vcat [text "In a function application, function type doesn't match arg types:",
477 hang (ptext (sLit "Function type:")) 4 (ppr fun_ty),
478 hang (ptext (sLit "Arg types:")) 4 (vcat (map (ppr) arg_tys)),
479 hang (ptext (sLit "Expression:")) 4 (ppr expr)]
480
481 mkRhsConMsg :: Type -> [Type] -> MsgDoc
482 mkRhsConMsg fun_ty arg_tys
483 = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
484 hang (ptext (sLit "Constructor type:")) 4 (ppr fun_ty),
485 hang (ptext (sLit "Arg types:")) 4 (vcat (map (ppr) arg_tys))]
486
487 mkAltMsg1 :: Type -> MsgDoc
488 mkAltMsg1 ty
489 = ($$) (text "In a case expression, type of scrutinee does not match patterns")
490 (ppr ty)
491
492 mkAlgAltMsg2 :: Type -> DataCon -> MsgDoc
493 mkAlgAltMsg2 ty con
494 = vcat [
495 text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
496 ppr ty,
497 ppr con
498 ]
499
500 mkAlgAltMsg3 :: DataCon -> [Id] -> MsgDoc
501 mkAlgAltMsg3 con alts
502 = vcat [
503 text "In some algebraic case alternative, number of arguments doesn't match constructor:",
504 ppr con,
505 ppr alts
506 ]
507
508 mkAlgAltMsg4 :: Type -> Id -> MsgDoc
509 mkAlgAltMsg4 ty arg
510 = vcat [
511 text "In some algebraic case alternative, type of argument doesn't match data constructor:",
512 ppr ty,
513 ppr arg
514 ]
515
516 _mkRhsMsg :: Id -> Type -> MsgDoc
517 _mkRhsMsg binder ty
518 = vcat [hsep [ptext (sLit "The type of this binder doesn't match the type of its RHS:"),
519 ppr binder],
520 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)],
521 hsep [ptext (sLit "Rhs type:"), ppr ty]
522 ]
523
524 mkUnLiftedTyMsg :: Id -> StgRhs -> SDoc
525 mkUnLiftedTyMsg binder rhs
526 = (ptext (sLit "Let(rec) binder") <+> quotes (ppr binder) <+>
527 ptext (sLit "has unlifted type") <+> quotes (ppr (idType binder)))
528 $$
529 (ptext (sLit "RHS:") <+> ppr rhs)