Add kind equalities to GHC.
[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 #if __GLASGOW_HASKELL__ < 709
30 import Control.Applicative ( Applicative(..) )
31 #endif
32 import Control.Monad
33 import Data.Function
34
35 #include "HsVersions.h"
36
37 {-
38 Checks for
39 (a) *some* type errors
40 (b) locally-defined variables used but not defined
41
42
43 Note: unless -dverbose-stg is on, display of lint errors will result
44 in "panic: bOGUS_LVs".
45
46 WARNING:
47 ~~~~~~~~
48
49 This module has suffered bit-rot; it is likely to yield lint errors
50 for Stg code that is currently perfectly acceptable for code
51 generation. Solution: don't use it! (KSW 2000-05).
52
53
54 ************************************************************************
55 * *
56 \subsection{``lint'' for various constructs}
57 * *
58 ************************************************************************
59
60 @lintStgBindings@ is the top-level interface function.
61 -}
62
63 lintStgBindings :: String -> [StgBinding] -> [StgBinding]
64
65 lintStgBindings whodunnit binds
66 = {-# SCC "StgLint" #-}
67 case (initL (lint_binds binds)) of
68 Nothing -> binds
69 Just msg -> pprPanic "" (vcat [
70 ptext (sLit "*** Stg Lint ErrMsgs: in") <+>
71 text whodunnit <+> ptext (sLit "***"),
72 msg,
73 ptext (sLit "*** Offending Program ***"),
74 pprStgBindings binds,
75 ptext (sLit "*** End of Offense ***")])
76 where
77 lint_binds :: [StgBinding] -> LintM ()
78
79 lint_binds [] = return ()
80 lint_binds (bind:binds) = do
81 binders <- lintStgBinds bind
82 addInScopeVars binders $
83 lint_binds binds
84
85 lintStgArg :: StgArg -> LintM (Maybe Type)
86 lintStgArg (StgLitArg lit) = return (Just (literalType lit))
87 lintStgArg (StgVarArg v) = lintStgVar v
88
89 lintStgVar :: Id -> LintM (Maybe Kind)
90 lintStgVar v = do checkInScope v
91 return (Just (idType v))
92
93 lintStgBinds :: StgBinding -> LintM [Id] -- Returns the binders
94 lintStgBinds (StgNonRec binder rhs) = do
95 lint_binds_help (binder,rhs)
96 return [binder]
97
98 lintStgBinds (StgRec pairs)
99 = addInScopeVars binders $ do
100 mapM_ lint_binds_help pairs
101 return binders
102 where
103 binders = [b | (b,_) <- pairs]
104
105 lint_binds_help :: (Id, StgRhs) -> LintM ()
106 lint_binds_help (binder, rhs)
107 = addLoc (RhsOf binder) $ do
108 -- Check the rhs
109 _maybe_rhs_ty <- lintStgRhs rhs
110
111 -- Check binder doesn't have unlifted type
112 checkL (not (isUnLiftedType binder_ty))
113 (mkUnLiftedTyMsg binder rhs)
114
115 -- Check match to RHS type
116 -- Actually we *can't* check the RHS type, because
117 -- unsafeCoerce means it really might not match at all
118 -- notably; eg x::Int = (error @Bool "urk") |> unsafeCoerce...
119 -- case maybe_rhs_ty of
120 -- Nothing -> return ()
121 -- Just rhs_ty -> checkTys binder_ty
122 -- rhs_ty
123 --- (mkRhsMsg binder rhs_ty)
124
125 return ()
126 where
127 binder_ty = idType binder
128
129 lintStgRhs :: StgRhs -> LintM (Maybe Type) -- Just ty => type is exact
130
131 lintStgRhs (StgRhsClosure _ _ _ _ _ [] expr)
132 = lintStgExpr expr
133
134 lintStgRhs (StgRhsClosure _ _ _ _ _ binders expr)
135 = addLoc (LambdaBodyOf binders) $
136 addInScopeVars binders $ runMaybeT $ do
137 body_ty <- MaybeT $ lintStgExpr expr
138 return (mkFunTys (map idType binders) body_ty)
139
140 lintStgRhs (StgRhsCon _ con args) = runMaybeT $ do
141 arg_tys <- mapM (MaybeT . lintStgArg) args
142 MaybeT $ checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys)
143 where
144 con_ty = dataConRepType con
145
146 lintStgExpr :: StgExpr -> LintM (Maybe Type) -- Just ty => type is exact
147
148 lintStgExpr (StgLit l) = return (Just (literalType l))
149
150 lintStgExpr e@(StgApp fun args) = runMaybeT $ do
151 fun_ty <- MaybeT $ lintStgVar fun
152 arg_tys <- mapM (MaybeT . lintStgArg) args
153 MaybeT $ checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e)
154
155 lintStgExpr e@(StgConApp con args) = runMaybeT $ do
156 arg_tys <- mapM (MaybeT . lintStgArg) args
157 MaybeT $ checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e)
158 where
159 con_ty = dataConRepType con
160
161 lintStgExpr e@(StgOpApp (StgPrimOp op) args _) = runMaybeT $ do
162 arg_tys <- mapM (MaybeT . lintStgArg) args
163 MaybeT $ checkFunApp op_ty arg_tys (mkFunAppMsg op_ty arg_tys e)
164 where
165 op_ty = primOpType op
166
167 lintStgExpr (StgOpApp _ args res_ty) = runMaybeT $ do
168 -- We don't have enough type information to check
169 -- the application for StgFCallOp and StgPrimCallOp; ToDo
170 _maybe_arg_tys <- mapM (MaybeT . lintStgArg) args
171 return res_ty
172
173 lintStgExpr (StgLam bndrs _) = do
174 addErrL (ptext (sLit "Unexpected StgLam") <+> ppr bndrs)
175 return Nothing
176
177 lintStgExpr (StgLet binds body) = do
178 binders <- lintStgBinds binds
179 addLoc (BodyOfLetRec binders) $
180 addInScopeVars binders $
181 lintStgExpr body
182
183 lintStgExpr (StgLetNoEscape _ _ binds body) = do
184 binders <- lintStgBinds binds
185 addLoc (BodyOfLetRec binders) $
186 addInScopeVars binders $
187 lintStgExpr body
188
189 lintStgExpr (StgTick _ expr) = lintStgExpr expr
190
191 lintStgExpr (StgCase scrut _ _ bndr _ alts_type alts) = runMaybeT $ do
192 _ <- MaybeT $ lintStgExpr scrut
193
194 in_scope <- MaybeT $ liftM Just $
195 case alts_type of
196 AlgAlt tc -> check_bndr tc >> return True
197 PrimAlt tc -> check_bndr tc >> return True
198 UbxTupAlt _ -> return False -- Binder is always dead in this case
199 PolyAlt -> return True
200
201 MaybeT $ addInScopeVars [bndr | in_scope] $
202 lintStgAlts alts scrut_ty
203 where
204 scrut_ty = idType bndr
205 UnaryRep scrut_rep = repType scrut_ty -- Not used if scrutinee is unboxed tuple
206 check_bndr tc = case tyConAppTyCon_maybe scrut_rep of
207 Just bndr_tc -> checkL (tc == bndr_tc) bad_bndr
208 Nothing -> addErrL bad_bndr
209 where
210 bad_bndr = mkDefltMsg bndr tc
211
212 lintStgAlts :: [StgAlt]
213 -> Type -- Type of scrutinee
214 -> LintM (Maybe Type) -- Just ty => type is accurage
215
216 lintStgAlts alts scrut_ty = do
217 maybe_result_tys <- mapM (lintAlt scrut_ty) alts
218
219 -- Check the result types
220 case catMaybes (maybe_result_tys) of
221 [] -> return Nothing
222
223 (first_ty:_tys) -> do -- mapM_ check tys
224 return (Just first_ty)
225 where
226 -- check ty = checkTys first_ty ty (mkCaseAltMsg alts)
227 -- We can't check that the alternatives have the
228 -- same type, because they don't, with unsafeCoerce#
229
230 lintAlt :: Type -> (AltCon, [Id], [Bool], StgExpr) -> LintM (Maybe Type)
231 lintAlt _ (DEFAULT, _, _, rhs)
232 = lintStgExpr rhs
233
234 lintAlt scrut_ty (LitAlt lit, _, _, rhs) = do
235 checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty)
236 lintStgExpr rhs
237
238 lintAlt scrut_ty (DataAlt con, args, _, rhs) = do
239 case splitTyConApp_maybe scrut_ty of
240 Just (tycon, tys_applied) | isAlgTyCon tycon &&
241 not (isNewTyCon tycon) -> do
242 let
243 cons = tyConDataCons tycon
244 arg_tys = dataConInstArgTys con tys_applied
245 -- This does not work for existential constructors
246
247 checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con)
248 checkL (length args == dataConRepArity con) (mkAlgAltMsg3 con args)
249 when (isVanillaDataCon con) $
250 mapM_ check (zipEqual "lintAlgAlt:stg" arg_tys args)
251 return ()
252 _ ->
253 addErrL (mkAltMsg1 scrut_ty)
254
255 addInScopeVars args $
256 lintStgExpr rhs
257 where
258 check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
259
260 -- elem: yes, the elem-list here can sometimes be long-ish,
261 -- but as it's use-once, probably not worth doing anything different
262 -- We give it its own copy, so it isn't overloaded.
263 elem _ [] = False
264 elem x (y:ys) = x==y || elem x ys
265
266 {-
267 ************************************************************************
268 * *
269 \subsection[lint-monad]{The Lint monad}
270 * *
271 ************************************************************************
272 -}
273
274 newtype LintM a = LintM
275 { unLintM :: [LintLocInfo] -- Locations
276 -> IdSet -- Local vars in scope
277 -> Bag MsgDoc -- Error messages so far
278 -> (a, Bag MsgDoc) -- Result and error messages (if any)
279 }
280
281 data LintLocInfo
282 = RhsOf Id -- The variable bound
283 | LambdaBodyOf [Id] -- The lambda-binder
284 | BodyOfLetRec [Id] -- One of the binders
285
286 dumpLoc :: LintLocInfo -> (SrcSpan, SDoc)
287 dumpLoc (RhsOf v) =
288 (srcLocSpan (getSrcLoc v), ptext (sLit " [RHS of ") <> pp_binders [v] <> char ']' )
289 dumpLoc (LambdaBodyOf bs) =
290 (srcLocSpan (getSrcLoc (head bs)), ptext (sLit " [in body of lambda with binders ") <> pp_binders bs <> char ']' )
291
292 dumpLoc (BodyOfLetRec bs) =
293 (srcLocSpan (getSrcLoc (head bs)), ptext (sLit " [in body of letrec with binders ") <> pp_binders bs <> char ']' )
294
295
296 pp_binders :: [Id] -> SDoc
297 pp_binders bs
298 = sep (punctuate comma (map pp_binder bs))
299 where
300 pp_binder b
301 = hsep [ppr b, dcolon, ppr (idType b)]
302
303 initL :: LintM a -> Maybe MsgDoc
304 initL (LintM m)
305 = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
306 if isEmptyBag errs then
307 Nothing
308 else
309 Just (vcat (punctuate blankLine (bagToList errs)))
310 }
311
312 instance Functor LintM where
313 fmap = liftM
314
315 instance Applicative LintM where
316 pure a = LintM $ \_loc _scope errs -> (a, errs)
317 (<*>) = ap
318 (*>) = thenL_
319
320 instance Monad LintM where
321 return = pure
322 (>>=) = thenL
323 (>>) = (*>)
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)