Drop pre-AMP compatibility CPP conditionals
[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 return = pure
319 (>>=) = thenL
320 (>>) = (*>)
321
322 thenL :: LintM a -> (a -> LintM b) -> LintM b
323 thenL m k = LintM $ \loc scope errs
324 -> case unLintM m loc scope errs of
325 (r, errs') -> unLintM (k r) loc scope errs'
326
327 thenL_ :: LintM a -> LintM b -> LintM b
328 thenL_ m k = LintM $ \loc scope errs
329 -> case unLintM m loc scope errs of
330 (_, errs') -> unLintM k loc scope errs'
331
332 checkL :: Bool -> MsgDoc -> LintM ()
333 checkL True _ = return ()
334 checkL False msg = addErrL msg
335
336 addErrL :: MsgDoc -> LintM ()
337 addErrL msg = LintM $ \loc _scope errs -> ((), addErr errs msg loc)
338
339 addErr :: Bag MsgDoc -> MsgDoc -> [LintLocInfo] -> Bag MsgDoc
340 addErr errs_so_far msg locs
341 = errs_so_far `snocBag` mk_msg locs
342 where
343 mk_msg (loc:_) = let (l,hdr) = dumpLoc loc
344 in mkLocMessage SevWarning l (hdr $$ msg)
345 mk_msg [] = msg
346
347 addLoc :: LintLocInfo -> LintM a -> LintM a
348 addLoc extra_loc m = LintM $ \loc scope errs
349 -> unLintM m (extra_loc:loc) scope errs
350
351 addInScopeVars :: [Id] -> LintM a -> LintM a
352 addInScopeVars ids m = LintM $ \loc scope errs
353 -> -- We check if these "new" ids are already
354 -- in scope, i.e., we have *shadowing* going on.
355 -- For now, it's just a "trace"; we may make
356 -- a real error out of it...
357 let
358 new_set = mkVarSet ids
359 in
360 -- After adding -fliberate-case, Simon decided he likes shadowed
361 -- names after all. WDP 94/07
362 -- (if isEmptyVarSet shadowed
363 -- then id
364 -- else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $
365 unLintM m loc (scope `unionVarSet` new_set) errs
366
367 {-
368 Checking function applications: we only check that the type has the
369 right *number* of arrows, we don't actually compare the types. This
370 is because we can't expect the types to be equal - the type
371 applications and type lambdas that we use to calculate accurate types
372 have long since disappeared.
373 -}
374
375 checkFunApp :: Type -- The function type
376 -> [Type] -- The arg type(s)
377 -> MsgDoc -- Error message
378 -> LintM (Maybe Type) -- Just ty => result type is accurate
379
380 checkFunApp fun_ty arg_tys msg
381 = do { case mb_msg of
382 Just msg -> addErrL msg
383 Nothing -> return ()
384 ; return mb_ty }
385 where
386 (mb_ty, mb_msg) = cfa True fun_ty arg_tys
387
388 cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result?
389 , Maybe MsgDoc) -- Errors?
390
391 cfa accurate fun_ty [] -- Args have run out; that's fine
392 = (if accurate then Just fun_ty else Nothing, Nothing)
393
394 cfa accurate fun_ty arg_tys@(arg_ty':arg_tys')
395 | Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty
396 = if accurate && not (arg_ty `stgEqType` arg_ty')
397 then (Nothing, Just msg) -- Arg type mismatch
398 else cfa accurate res_ty arg_tys'
399
400 | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty
401 = cfa False fun_ty' arg_tys
402
403 | Just (tc,tc_args) <- splitTyConApp_maybe fun_ty
404 , isNewTyCon tc
405 = if length tc_args < tyConArity tc
406 then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg )
407 (Nothing, Nothing) -- This is odd, but I've seen it
408 else cfa False (newTyConInstRhs tc tc_args) arg_tys
409
410 | Just tc <- tyConAppTyCon_maybe fun_ty
411 , not (isTypeFamilyTyCon tc) -- Definite error
412 = (Nothing, Just msg) -- Too many args
413
414 | otherwise
415 = (Nothing, Nothing)
416
417 stgEqType :: Type -> Type -> Bool
418 -- Compare types, but crudely because we have discarded
419 -- both casts and type applications, so types might look
420 -- different but be the same. So reply "True" if in doubt.
421 -- "False" means that the types are definitely different.
422 --
423 -- Fundamentally this is a losing battle because of unsafeCoerce
424
425 stgEqType orig_ty1 orig_ty2
426 = gos (repType orig_ty1) (repType orig_ty2)
427 where
428 gos :: RepType -> RepType -> Bool
429 gos (UbxTupleRep tys1) (UbxTupleRep tys2)
430 = equalLength tys1 tys2 && and (zipWith go tys1 tys2)
431 gos (UnaryRep ty1) (UnaryRep ty2) = go ty1 ty2
432 gos _ _ = False
433
434 go :: UnaryType -> UnaryType -> Bool
435 go ty1 ty2
436 | Just (tc1, tc_args1) <- splitTyConApp_maybe ty1
437 , Just (tc2, tc_args2) <- splitTyConApp_maybe ty2
438 , let res = if tc1 == tc2
439 then equalLength tc_args1 tc_args2 && and (zipWith (gos `on` repType) tc_args1 tc_args2)
440 else -- TyCons don't match; but don't bleat if either is a
441 -- family TyCon because a coercion might have made it
442 -- equal to something else
443 (isFamilyTyCon tc1 || isFamilyTyCon tc2)
444 = if res then True
445 else
446 pprTrace "stgEqType: unequal" (vcat [ppr ty1, ppr ty2])
447 False
448
449 | otherwise = True -- Conservatively say "fine".
450 -- Type variables in particular
451
452 checkInScope :: Id -> LintM ()
453 checkInScope id = LintM $ \loc scope errs
454 -> if isLocalId id && not (id `elemVarSet` scope) then
455 ((), addErr errs (hsep [ppr id, ptext (sLit "is out of scope")]) loc)
456 else
457 ((), errs)
458
459 checkTys :: Type -> Type -> MsgDoc -> LintM ()
460 checkTys ty1 ty2 msg = LintM $ \loc _scope errs
461 -> if (ty1 `stgEqType` ty2)
462 then ((), errs)
463 else ((), addErr errs msg loc)
464
465 _mkCaseAltMsg :: [StgAlt] -> MsgDoc
466 _mkCaseAltMsg _alts
467 = ($$) (text "In some case alternatives, type of alternatives not all same:")
468 (Outputable.empty) -- LATER: ppr alts
469
470 mkDefltMsg :: Id -> TyCon -> MsgDoc
471 mkDefltMsg bndr tc
472 = ($$) (ptext (sLit "Binder of a case expression doesn't match type of scrutinee:"))
473 (ppr bndr $$ ppr (idType bndr) $$ ppr tc)
474
475 mkFunAppMsg :: Type -> [Type] -> StgExpr -> MsgDoc
476 mkFunAppMsg fun_ty arg_tys expr
477 = vcat [text "In a function application, function type doesn't match arg types:",
478 hang (ptext (sLit "Function type:")) 4 (ppr fun_ty),
479 hang (ptext (sLit "Arg types:")) 4 (vcat (map (ppr) arg_tys)),
480 hang (ptext (sLit "Expression:")) 4 (ppr expr)]
481
482 mkRhsConMsg :: Type -> [Type] -> MsgDoc
483 mkRhsConMsg fun_ty arg_tys
484 = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
485 hang (ptext (sLit "Constructor type:")) 4 (ppr fun_ty),
486 hang (ptext (sLit "Arg types:")) 4 (vcat (map (ppr) arg_tys))]
487
488 mkAltMsg1 :: Type -> MsgDoc
489 mkAltMsg1 ty
490 = ($$) (text "In a case expression, type of scrutinee does not match patterns")
491 (ppr ty)
492
493 mkAlgAltMsg2 :: Type -> DataCon -> MsgDoc
494 mkAlgAltMsg2 ty con
495 = vcat [
496 text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
497 ppr ty,
498 ppr con
499 ]
500
501 mkAlgAltMsg3 :: DataCon -> [Id] -> MsgDoc
502 mkAlgAltMsg3 con alts
503 = vcat [
504 text "In some algebraic case alternative, number of arguments doesn't match constructor:",
505 ppr con,
506 ppr alts
507 ]
508
509 mkAlgAltMsg4 :: Type -> Id -> MsgDoc
510 mkAlgAltMsg4 ty arg
511 = vcat [
512 text "In some algebraic case alternative, type of argument doesn't match data constructor:",
513 ppr ty,
514 ppr arg
515 ]
516
517 _mkRhsMsg :: Id -> Type -> MsgDoc
518 _mkRhsMsg binder ty
519 = vcat [hsep [ptext (sLit "The type of this binder doesn't match the type of its RHS:"),
520 ppr binder],
521 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)],
522 hsep [ptext (sLit "Rhs type:"), ppr ty]
523 ]
524
525 mkUnLiftedTyMsg :: Id -> StgRhs -> SDoc
526 mkUnLiftedTyMsg binder rhs
527 = (ptext (sLit "Let(rec) binder") <+> quotes (ppr binder) <+>
528 ptext (sLit "has unlifted type") <+> quotes (ppr (idType binder)))
529 $$
530 (ptext (sLit "RHS:") <+> ppr rhs)