compiler: de-lhs stgSyn/
[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 TypeRep
24 import Type
25 import TyCon
26 import Util
27 import SrcLoc
28 import Outputable
29 import FastString
30 #if __GLASGOW_HASKELL__ < 709
31 import Control.Applicative ( Applicative(..) )
32 #endif
33 import Control.Monad
34 import Data.Function
35
36 #include "HsVersions.h"
37
38 {-
39 Checks for
40 (a) *some* type errors
41 (b) locally-defined variables used but not defined
42
43
44 Note: unless -dverbose-stg is on, display of lint errors will result
45 in "panic: bOGUS_LVs".
46
47 WARNING:
48 ~~~~~~~~
49
50 This module has suffered bit-rot; it is likely to yield lint errors
51 for Stg code that is currently perfectly acceptable for code
52 generation. Solution: don't use it! (KSW 2000-05).
53
54
55 ************************************************************************
56 * *
57 \subsection{``lint'' for various constructs}
58 * *
59 ************************************************************************
60
61 @lintStgBindings@ is the top-level interface function.
62 -}
63
64 lintStgBindings :: String -> [StgBinding] -> [StgBinding]
65
66 lintStgBindings whodunnit binds
67 = {-# SCC "StgLint" #-}
68 case (initL (lint_binds binds)) of
69 Nothing -> binds
70 Just msg -> pprPanic "" (vcat [
71 ptext (sLit "*** Stg Lint ErrMsgs: in") <+>
72 text whodunnit <+> ptext (sLit "***"),
73 msg,
74 ptext (sLit "*** Offending Program ***"),
75 pprStgBindings binds,
76 ptext (sLit "*** End of Offense ***")])
77 where
78 lint_binds :: [StgBinding] -> LintM ()
79
80 lint_binds [] = return ()
81 lint_binds (bind:binds) = do
82 binders <- lintStgBinds bind
83 addInScopeVars binders $
84 lint_binds binds
85
86 lintStgArg :: StgArg -> LintM (Maybe Type)
87 lintStgArg (StgLitArg lit) = return (Just (literalType lit))
88 lintStgArg (StgVarArg v) = lintStgVar v
89
90 lintStgVar :: Id -> LintM (Maybe Kind)
91 lintStgVar v = do checkInScope v
92 return (Just (idType v))
93
94 lintStgBinds :: StgBinding -> LintM [Id] -- Returns the binders
95 lintStgBinds (StgNonRec binder rhs) = do
96 lint_binds_help (binder,rhs)
97 return [binder]
98
99 lintStgBinds (StgRec pairs)
100 = addInScopeVars binders $ do
101 mapM_ lint_binds_help pairs
102 return binders
103 where
104 binders = [b | (b,_) <- pairs]
105
106 lint_binds_help :: (Id, StgRhs) -> LintM ()
107 lint_binds_help (binder, rhs)
108 = addLoc (RhsOf binder) $ do
109 -- Check the rhs
110 _maybe_rhs_ty <- lintStgRhs rhs
111
112 -- Check binder doesn't have unlifted type
113 checkL (not (isUnLiftedType binder_ty))
114 (mkUnLiftedTyMsg binder rhs)
115
116 -- Check match to RHS type
117 -- Actually we *can't* check the RHS type, because
118 -- unsafeCoerce means it really might not match at all
119 -- notably; eg x::Int = (error @Bool "urk") |> unsafeCoerce...
120 -- case maybe_rhs_ty of
121 -- Nothing -> return ()
122 -- Just rhs_ty -> checkTys binder_ty
123 -- rhs_ty
124 --- (mkRhsMsg binder rhs_ty)
125
126 return ()
127 where
128 binder_ty = idType binder
129
130 lintStgRhs :: StgRhs -> LintM (Maybe Type) -- Just ty => type is exact
131
132 lintStgRhs (StgRhsClosure _ _ _ _ _ [] expr)
133 = lintStgExpr expr
134
135 lintStgRhs (StgRhsClosure _ _ _ _ _ binders expr)
136 = addLoc (LambdaBodyOf binders) $
137 addInScopeVars binders $ runMaybeT $ do
138 body_ty <- MaybeT $ lintStgExpr expr
139 return (mkFunTys (map idType binders) body_ty)
140
141 lintStgRhs (StgRhsCon _ con args) = runMaybeT $ do
142 arg_tys <- mapM (MaybeT . lintStgArg) args
143 MaybeT $ checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys)
144 where
145 con_ty = dataConRepType con
146
147 lintStgExpr :: StgExpr -> LintM (Maybe Type) -- Just ty => type is exact
148
149 lintStgExpr (StgLit l) = return (Just (literalType l))
150
151 lintStgExpr e@(StgApp fun args) = runMaybeT $ do
152 fun_ty <- MaybeT $ lintStgVar fun
153 arg_tys <- mapM (MaybeT . lintStgArg) args
154 MaybeT $ checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e)
155
156 lintStgExpr e@(StgConApp con args) = runMaybeT $ do
157 arg_tys <- mapM (MaybeT . lintStgArg) args
158 MaybeT $ checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e)
159 where
160 con_ty = dataConRepType con
161
162 lintStgExpr e@(StgOpApp (StgPrimOp op) args _) = runMaybeT $ do
163 arg_tys <- mapM (MaybeT . lintStgArg) args
164 MaybeT $ checkFunApp op_ty arg_tys (mkFunAppMsg op_ty arg_tys e)
165 where
166 op_ty = primOpType op
167
168 lintStgExpr (StgOpApp _ args res_ty) = runMaybeT $ do
169 -- We don't have enough type information to check
170 -- the application for StgFCallOp and StgPrimCallOp; ToDo
171 _maybe_arg_tys <- mapM (MaybeT . lintStgArg) args
172 return res_ty
173
174 lintStgExpr (StgLam bndrs _) = do
175 addErrL (ptext (sLit "Unexpected StgLam") <+> ppr bndrs)
176 return Nothing
177
178 lintStgExpr (StgLet binds body) = do
179 binders <- lintStgBinds binds
180 addLoc (BodyOfLetRec binders) $
181 addInScopeVars binders $
182 lintStgExpr body
183
184 lintStgExpr (StgLetNoEscape _ _ binds body) = do
185 binders <- lintStgBinds binds
186 addLoc (BodyOfLetRec binders) $
187 addInScopeVars binders $
188 lintStgExpr body
189
190 lintStgExpr (StgSCC _ _ _ expr) = lintStgExpr expr
191
192 lintStgExpr (StgCase scrut _ _ bndr _ alts_type alts) = runMaybeT $ do
193 _ <- MaybeT $ lintStgExpr scrut
194
195 in_scope <- MaybeT $ liftM Just $
196 case alts_type of
197 AlgAlt tc -> check_bndr tc >> return True
198 PrimAlt tc -> check_bndr tc >> return True
199 UbxTupAlt _ -> return False -- Binder is always dead in this case
200 PolyAlt -> return True
201
202 MaybeT $ addInScopeVars [bndr | in_scope] $
203 lintStgAlts alts scrut_ty
204 where
205 scrut_ty = idType bndr
206 UnaryRep scrut_rep = repType scrut_ty -- Not used if scrutinee is unboxed tuple
207 check_bndr tc = case tyConAppTyCon_maybe scrut_rep of
208 Just bndr_tc -> checkL (tc == bndr_tc) bad_bndr
209 Nothing -> addErrL bad_bndr
210 where
211 bad_bndr = mkDefltMsg bndr tc
212
213 lintStgExpr e = pprPanic "lintStgExpr" (ppr e)
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], [Bool], 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), ptext (sLit " [RHS of ") <> pp_binders [v] <> char ']' )
292 dumpLoc (LambdaBodyOf bs) =
293 (srcLocSpan (getSrcLoc (head bs)), ptext (sLit " [in body of lambda with binders ") <> pp_binders bs <> char ']' )
294
295 dumpLoc (BodyOfLetRec bs) =
296 (srcLocSpan (getSrcLoc (head bs)), ptext (sLit " [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 = return
320 (<*>) = ap
321
322 instance Monad LintM where
323 return a = LintM $ \_loc _scope errs -> (a, errs)
324 (>>=) = thenL
325 (>>) = thenL_
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 -> -- We check if these "new" ids are already
359 -- in scope, i.e., we have *shadowing* going on.
360 -- For now, it's just a "trace"; we may make
361 -- a real error out of it...
362 let
363 new_set = mkVarSet ids
364 in
365 -- After adding -fliberate-case, Simon decided he likes shadowed
366 -- names after all. WDP 94/07
367 -- (if isEmptyVarSet shadowed
368 -- then id
369 -- else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $
370 unLintM m loc (scope `unionVarSet` new_set) errs
371
372 {-
373 Checking function applications: we only check that the type has the
374 right *number* of arrows, we don't actually compare the types. This
375 is because we can't expect the types to be equal - the type
376 applications and type lambdas that we use to calculate accurate types
377 have long since disappeared.
378 -}
379
380 checkFunApp :: Type -- The function type
381 -> [Type] -- The arg type(s)
382 -> MsgDoc -- Error message
383 -> LintM (Maybe Type) -- Just ty => result type is accurate
384
385 checkFunApp fun_ty arg_tys msg
386 = do { case mb_msg of
387 Just msg -> addErrL msg
388 Nothing -> return ()
389 ; return mb_ty }
390 where
391 (mb_ty, mb_msg) = cfa True fun_ty arg_tys
392
393 cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result?
394 , Maybe MsgDoc) -- Errors?
395
396 cfa accurate fun_ty [] -- Args have run out; that's fine
397 = (if accurate then Just fun_ty else Nothing, Nothing)
398
399 cfa accurate fun_ty arg_tys@(arg_ty':arg_tys')
400 | Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty
401 = if accurate && not (arg_ty `stgEqType` arg_ty')
402 then (Nothing, Just msg) -- Arg type mismatch
403 else cfa accurate res_ty arg_tys'
404
405 | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty
406 = cfa False fun_ty' arg_tys
407
408 | Just (tc,tc_args) <- splitTyConApp_maybe fun_ty
409 , isNewTyCon tc
410 = if length tc_args < tyConArity tc
411 then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg )
412 (Nothing, Nothing) -- This is odd, but I've seen it
413 else cfa False (newTyConInstRhs tc tc_args) arg_tys
414
415 | Just tc <- tyConAppTyCon_maybe fun_ty
416 , not (isTypeFamilyTyCon tc) -- Definite error
417 = (Nothing, Just msg) -- Too many args
418
419 | otherwise
420 = (Nothing, Nothing)
421
422 stgEqType :: Type -> Type -> Bool
423 -- Compare types, but crudely because we have discarded
424 -- both casts and type applications, so types might look
425 -- different but be the same. So reply "True" if in doubt.
426 -- "False" means that the types are definitely different.
427 --
428 -- Fundamentally this is a losing battle because of unsafeCoerce
429
430 stgEqType orig_ty1 orig_ty2
431 = gos (repType orig_ty1) (repType orig_ty2)
432 where
433 gos :: RepType -> RepType -> Bool
434 gos (UbxTupleRep tys1) (UbxTupleRep tys2)
435 = equalLength tys1 tys2 && and (zipWith go tys1 tys2)
436 gos (UnaryRep ty1) (UnaryRep ty2) = go ty1 ty2
437 gos _ _ = False
438
439 go :: UnaryType -> UnaryType -> Bool
440 go ty1 ty2
441 | Just (tc1, tc_args1) <- splitTyConApp_maybe ty1
442 , Just (tc2, tc_args2) <- splitTyConApp_maybe ty2
443 , let res = if tc1 == tc2
444 then equalLength tc_args1 tc_args2 && and (zipWith (gos `on` repType) tc_args1 tc_args2)
445 else -- TyCons don't match; but don't bleat if either is a
446 -- family TyCon because a coercion might have made it
447 -- equal to something else
448 (isFamilyTyCon tc1 || isFamilyTyCon tc2)
449 = if res then True
450 else
451 pprTrace "stgEqType: unequal" (vcat [ppr ty1, ppr ty2])
452 False
453
454 | otherwise = True -- Conservatively say "fine".
455 -- Type variables in particular
456
457 checkInScope :: Id -> LintM ()
458 checkInScope id = LintM $ \loc scope errs
459 -> if isLocalId id && not (id `elemVarSet` scope) then
460 ((), addErr errs (hsep [ppr id, ptext (sLit "is out of scope")]) loc)
461 else
462 ((), errs)
463
464 checkTys :: Type -> Type -> MsgDoc -> LintM ()
465 checkTys ty1 ty2 msg = LintM $ \loc _scope errs
466 -> if (ty1 `stgEqType` ty2)
467 then ((), errs)
468 else ((), addErr errs msg loc)
469
470 _mkCaseAltMsg :: [StgAlt] -> MsgDoc
471 _mkCaseAltMsg _alts
472 = ($$) (text "In some case alternatives, type of alternatives not all same:")
473 (Outputable.empty) -- LATER: ppr alts
474
475 mkDefltMsg :: Id -> TyCon -> MsgDoc
476 mkDefltMsg bndr tc
477 = ($$) (ptext (sLit "Binder of a case expression doesn't match type of scrutinee:"))
478 (ppr bndr $$ ppr (idType bndr) $$ ppr tc)
479
480 mkFunAppMsg :: Type -> [Type] -> StgExpr -> MsgDoc
481 mkFunAppMsg fun_ty arg_tys expr
482 = vcat [text "In a function application, function type doesn't match arg types:",
483 hang (ptext (sLit "Function type:")) 4 (ppr fun_ty),
484 hang (ptext (sLit "Arg types:")) 4 (vcat (map (ppr) arg_tys)),
485 hang (ptext (sLit "Expression:")) 4 (ppr expr)]
486
487 mkRhsConMsg :: Type -> [Type] -> MsgDoc
488 mkRhsConMsg fun_ty arg_tys
489 = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
490 hang (ptext (sLit "Constructor type:")) 4 (ppr fun_ty),
491 hang (ptext (sLit "Arg types:")) 4 (vcat (map (ppr) arg_tys))]
492
493 mkAltMsg1 :: Type -> MsgDoc
494 mkAltMsg1 ty
495 = ($$) (text "In a case expression, type of scrutinee does not match patterns")
496 (ppr ty)
497
498 mkAlgAltMsg2 :: Type -> DataCon -> MsgDoc
499 mkAlgAltMsg2 ty con
500 = vcat [
501 text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
502 ppr ty,
503 ppr con
504 ]
505
506 mkAlgAltMsg3 :: DataCon -> [Id] -> MsgDoc
507 mkAlgAltMsg3 con alts
508 = vcat [
509 text "In some algebraic case alternative, number of arguments doesn't match constructor:",
510 ppr con,
511 ppr alts
512 ]
513
514 mkAlgAltMsg4 :: Type -> Id -> MsgDoc
515 mkAlgAltMsg4 ty arg
516 = vcat [
517 text "In some algebraic case alternative, type of argument doesn't match data constructor:",
518 ppr ty,
519 ppr arg
520 ]
521
522 _mkRhsMsg :: Id -> Type -> MsgDoc
523 _mkRhsMsg binder ty
524 = vcat [hsep [ptext (sLit "The type of this binder doesn't match the type of its RHS:"),
525 ppr binder],
526 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)],
527 hsep [ptext (sLit "Rhs type:"), ppr ty]
528 ]
529
530 mkUnLiftedTyMsg :: Id -> StgRhs -> SDoc
531 mkUnLiftedTyMsg binder rhs
532 = (ptext (sLit "Let(rec) binder") <+> quotes (ppr binder) <+>
533 ptext (sLit "has unlifted type") <+> quotes (ppr (idType binder)))
534 $$
535 (ptext (sLit "RHS:") <+> ppr rhs)