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