9dc83cd86396e6fbac166de7ddb7c05405dc8888
[ghc-hetmet.git] / compiler / stgSyn / StgLint.lhs
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 \begin{code}
7 {-# OPTIONS -w #-}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
12 -- for details
13
14 module StgLint ( lintStgBindings ) where
15
16 #include "HsVersions.h"
17
18 import StgSyn
19
20 import Bag              ( Bag, emptyBag, isEmptyBag, snocBag, bagToList )
21 import Id               ( Id, idType, isLocalId )
22 import VarSet
23 import DataCon          ( DataCon, dataConInstArgTys, dataConRepType )
24 import CoreSyn          ( AltCon(..) )
25 import PrimOp           ( primOpType )
26 import Literal          ( literalType )
27 import Maybes
28 import Name             ( getSrcLoc )
29 import ErrUtils         ( Message, mkLocMessage )
30 import Type             ( mkFunTys, splitFunTys, splitTyConApp_maybe,
31                           isUnLiftedType, isTyVarTy, dropForAlls, Type
32                         )
33 import TyCon            ( isAlgTyCon, isNewTyCon, tyConDataCons )
34 import Util             ( zipEqual, equalLength )
35 import SrcLoc           ( srcLocSpan )
36 import Outputable
37 import Control.Monad
38 \end{code}
39
40 Checks for
41         (a) *some* type errors
42         (b) locally-defined variables used but not defined
43
44
45 Note: unless -dverbose-stg is on, display of lint errors will result
46 in "panic: bOGUS_LVs".
47
48 WARNING:
49 ~~~~~~~~
50
51 This module has suffered bit-rot; it is likely to yield lint errors
52 for Stg code that is currently perfectly acceptable for code
53 generation.  Solution: don't use it!  (KSW 2000-05).
54
55
56 %************************************************************************
57 %*                                                                      *
58 \subsection{``lint'' for various constructs}
59 %*                                                                      *
60 %************************************************************************
61
62 @lintStgBindings@ is the top-level interface function.
63
64 \begin{code}
65 lintStgBindings :: String -> [StgBinding] -> [StgBinding]
66
67 lintStgBindings whodunnit binds
68   = {-# SCC "StgLint" #-}
69     case (initL (lint_binds binds)) of
70       Nothing  -> binds
71       Just msg -> pprPanic "" (vcat [
72                         ptext SLIT("*** Stg Lint ErrMsgs: in") <+>
73                               text whodunnit <+> ptext SLIT("***"),
74                         msg,
75                         ptext SLIT("*** Offending Program ***"),
76                         pprStgBindings binds,
77                         ptext SLIT("*** End of Offense ***")])
78   where
79     lint_binds :: [StgBinding] -> LintM ()
80
81     lint_binds [] = return ()
82     lint_binds (bind:binds) = do
83         binders <- lintStgBinds bind
84         addInScopeVars binders $
85             lint_binds binds
86 \end{code}
87
88
89 \begin{code}
90 lintStgArg :: StgArg -> LintM (Maybe Type)
91 lintStgArg (StgLitArg lit) = return (Just (literalType lit))
92 lintStgArg (StgVarArg v)   = lintStgVar v
93
94 lintStgVar v = do checkInScope v
95                   return (Just (idType v))
96 \end{code}
97
98 \begin{code}
99 lintStgBinds :: StgBinding -> LintM [Id] -- Returns the binders
100 lintStgBinds (StgNonRec binder rhs) = do
101     lint_binds_help (binder,rhs)
102     return [binder]
103
104 lintStgBinds (StgRec pairs)
105   = addInScopeVars binders $ do
106         mapM_ lint_binds_help pairs
107         return binders
108   where
109     binders = [b | (b,_) <- pairs]
110
111 lint_binds_help (binder, rhs)
112   = addLoc (RhsOf binder) $ do
113         -- Check the rhs
114         maybe_rhs_ty <- lintStgRhs rhs
115
116         -- Check binder doesn't have unlifted type
117         checkL (not (isUnLiftedType binder_ty))
118                (mkUnLiftedTyMsg binder rhs)
119
120         -- Check match to RHS type
121         case maybe_rhs_ty of
122           Nothing     -> return ()
123           Just rhs_ty -> checkTys binder_ty
124                                   rhs_ty
125                                   (mkRhsMsg binder rhs_ty)
126
127         return ()
128   where
129     binder_ty = idType binder
130 \end{code}
131
132 \begin{code}
133 lintStgRhs :: StgRhs -> LintM (Maybe Type)
134
135 lintStgRhs (StgRhsClosure _ _ _ _ _ [] expr)
136   = lintStgExpr expr
137
138 lintStgRhs (StgRhsClosure _ _ _ _ _ binders expr)
139   = addLoc (LambdaBodyOf binders) $
140       addInScopeVars binders $ runMaybeT $ do
141         body_ty <- MaybeT $ lintStgExpr expr
142         return (mkFunTys (map idType binders) body_ty)
143
144 lintStgRhs (StgRhsCon _ con args) = runMaybeT $ do
145     arg_tys <- mapM (MaybeT . lintStgArg) args
146     MaybeT $ checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys)
147   where
148     con_ty = dataConRepType con
149 \end{code}
150
151 \begin{code}
152 lintStgExpr :: StgExpr -> LintM (Maybe Type) -- Nothing if error found
153
154 lintStgExpr (StgLit l) = return (Just (literalType l))
155
156 lintStgExpr e@(StgApp fun args) = runMaybeT $ do
157     fun_ty <- MaybeT $ lintStgVar fun
158     arg_tys <- mapM (MaybeT . lintStgArg) args
159     MaybeT $ checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e)
160
161 lintStgExpr e@(StgConApp con args) = runMaybeT $ do
162     arg_tys <- mapM (MaybeT . lintStgArg) args
163     MaybeT $ checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e)
164   where
165     con_ty = dataConRepType con
166
167 lintStgExpr (StgOpApp (StgFCallOp _ _) args res_ty) = runMaybeT $ do
168         -- We don't have enough type information to check
169         -- the application; ToDo
170     maybe_arg_tys <- mapM (MaybeT . lintStgArg) args
171     return res_ty
172
173 lintStgExpr e@(StgOpApp (StgPrimOp op) args _) = runMaybeT $ do
174     arg_tys <- mapM (MaybeT . lintStgArg) args
175     MaybeT $ checkFunApp op_ty arg_tys (mkFunAppMsg op_ty arg_tys e)
176   where
177     op_ty = primOpType op
178
179 lintStgExpr (StgLam _ bndrs _) = do
180     addErrL (ptext SLIT("Unexpected StgLam") <+> ppr bndrs)
181     return Nothing
182
183 lintStgExpr (StgLet binds body) = do
184     binders <- lintStgBinds binds
185     addLoc (BodyOfLetRec binders) $
186       addInScopeVars binders $
187         lintStgExpr body
188
189 lintStgExpr (StgLetNoEscape _ _ binds body) = do
190     binders <- lintStgBinds binds
191     addLoc (BodyOfLetRec binders) $
192       addInScopeVars binders $
193         lintStgExpr body
194
195 lintStgExpr (StgSCC _ expr) = lintStgExpr expr
196
197 lintStgExpr e@(StgCase scrut _ _ bndr _ alts_type alts) = runMaybeT $ do
198     MaybeT $ lintStgExpr scrut
199
200     MaybeT $ liftM Just $
201      case alts_type of
202         AlgAlt tc    -> check_bndr tc
203         PrimAlt tc   -> check_bndr tc
204         UbxTupAlt tc -> check_bndr tc
205         PolyAlt      -> return ()
206
207     MaybeT $ trace (showSDoc (ppr e)) $ do
208         -- we only allow case of tail-call or primop.
209      case scrut of
210         StgApp _ _     -> return ()
211         StgConApp _ _  -> return ()
212         StgOpApp _ _ _ -> return ()
213         _              -> addErrL (mkCaseOfCaseMsg e)
214
215      addInScopeVars [bndr] $
216         lintStgAlts alts scrut_ty
217   where
218     scrut_ty      = idType bndr
219     bad_bndr      = mkDefltMsg bndr
220     check_bndr tc = case splitTyConApp_maybe scrut_ty of
221                         Just (bndr_tc, _) -> checkL (tc == bndr_tc) bad_bndr
222                         Nothing           -> addErrL bad_bndr
223
224
225 lintStgAlts :: [StgAlt]
226             -> Type               -- Type of scrutinee
227             -> LintM (Maybe Type) -- Type of alternatives
228
229 lintStgAlts alts scrut_ty = do
230     maybe_result_tys <- mapM (lintAlt scrut_ty) alts
231
232     -- Check the result types
233     case catMaybes (maybe_result_tys) of
234       []             -> return Nothing
235
236       (first_ty:tys) -> do mapM_ check tys
237                            return (Just first_ty)
238         where
239           check ty = checkTys first_ty ty (mkCaseAltMsg alts)
240
241 lintAlt _ (DEFAULT, _, _, rhs)
242  = lintStgExpr rhs
243
244 lintAlt scrut_ty (LitAlt lit, _, _, rhs) = do
245    checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty)
246    lintStgExpr rhs
247
248 lintAlt scrut_ty (DataAlt con, args, _, rhs) = do
249     case splitTyConApp_maybe scrut_ty of
250       Just (tycon, tys_applied) | isAlgTyCon tycon &&
251                                   not (isNewTyCon tycon) -> do
252          let
253            cons    = tyConDataCons tycon
254            arg_tys = dataConInstArgTys con tys_applied
255                 -- This almost certainly does not work for existential constructors
256
257          checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con)
258          checkL (equalLength arg_tys args) (mkAlgAltMsg3 con args)
259          mapM_ check (zipEqual "lintAlgAlt:stg" arg_tys args)
260          return ()
261       _ ->
262          addErrL (mkAltMsg1 scrut_ty)
263
264     addInScopeVars args $
265          lintStgExpr rhs
266   where
267     check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
268
269     -- elem: yes, the elem-list here can sometimes be long-ish,
270     -- but as it's use-once, probably not worth doing anything different
271     -- We give it its own copy, so it isn't overloaded.
272     elem _ []       = False
273     elem x (y:ys)   = x==y || elem x ys
274 \end{code}
275
276
277 %************************************************************************
278 %*                                                                      *
279 \subsection[lint-monad]{The Lint monad}
280 %*                                                                      *
281 %************************************************************************
282
283 \begin{code}
284 newtype LintM a = LintM
285     { unLintM :: [LintLocInfo]      -- Locations
286               -> IdSet              -- Local vars in scope
287               -> Bag Message        -- Error messages so far
288               -> (a, Bag Message)   -- Result and error messages (if any)
289     }
290
291 data LintLocInfo
292   = RhsOf Id            -- The variable bound
293   | LambdaBodyOf [Id]   -- The lambda-binder
294   | BodyOfLetRec [Id]   -- One of the binders
295
296 dumpLoc (RhsOf v) =
297   (srcLocSpan (getSrcLoc v), ptext SLIT(" [RHS of ") <> pp_binders [v] <> char ']' )
298 dumpLoc (LambdaBodyOf bs) =
299   (srcLocSpan (getSrcLoc (head bs)), ptext SLIT(" [in body of lambda with binders ") <> pp_binders bs <> char ']' )
300
301 dumpLoc (BodyOfLetRec bs) =
302   (srcLocSpan (getSrcLoc (head bs)), ptext SLIT(" [in body of letrec with binders ") <> pp_binders bs <> char ']' )
303
304
305 pp_binders :: [Id] -> SDoc
306 pp_binders bs
307   = sep (punctuate comma (map pp_binder bs))
308   where
309     pp_binder b
310       = hsep [ppr b, dcolon, ppr (idType b)]
311 \end{code}
312
313 \begin{code}
314 initL :: LintM a -> Maybe Message
315 initL (LintM m)
316   = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
317     if isEmptyBag errs then
318         Nothing
319     else
320         Just (vcat (punctuate (text "") (bagToList errs)))
321     }
322
323 instance Monad LintM where
324     return a = LintM $ \_loc _scope errs -> (a, errs)
325     (>>=) = thenL
326     (>>)  = thenL_
327
328 thenL :: LintM a -> (a -> LintM b) -> LintM b
329 thenL m k = LintM $ \loc scope errs
330   -> case unLintM m loc scope errs of
331       (r, errs') -> unLintM (k r) loc scope errs'
332
333 thenL_ :: LintM a -> LintM b -> LintM b
334 thenL_ m k = LintM $ \loc scope errs
335   -> case unLintM m loc scope errs of
336       (_, errs') -> unLintM k loc scope errs'
337 \end{code}
338
339 \begin{code}
340 checkL :: Bool -> Message -> LintM ()
341 checkL True  _   = return ()
342 checkL False msg = addErrL msg
343
344 addErrL :: Message -> LintM ()
345 addErrL msg = LintM $ \loc _scope errs -> ((), addErr errs msg loc)
346
347 addErr :: Bag Message -> Message -> [LintLocInfo] -> Bag Message
348 addErr errs_so_far msg locs
349   = errs_so_far `snocBag` mk_msg locs
350   where
351     mk_msg (loc:_) = let (l,hdr) = dumpLoc loc
352                      in  mkLocMessage l (hdr $$ msg)
353     mk_msg []      = msg
354
355 addLoc :: LintLocInfo -> LintM a -> LintM a
356 addLoc extra_loc m = LintM $ \loc scope errs
357    -> unLintM m (extra_loc:loc) scope errs
358
359 addInScopeVars :: [Id] -> LintM a -> LintM a
360 addInScopeVars ids m = LintM $ \loc scope errs
361  -> -- We check if these "new" ids are already
362     -- in scope, i.e., we have *shadowing* going on.
363     -- For now, it's just a "trace"; we may make
364     -- a real error out of it...
365     let
366         new_set = mkVarSet ids
367     in
368 --  After adding -fliberate-case, Simon decided he likes shadowed
369 --  names after all.  WDP 94/07
370 --  (if isEmptyVarSet shadowed
371 --  then id
372 --  else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $
373     unLintM m loc (scope `unionVarSet` new_set) errs
374 \end{code}
375
376 Checking function applications: we only check that the type has the
377 right *number* of arrows, we don't actually compare the types.  This
378 is because we can't expect the types to be equal - the type
379 applications and type lambdas that we use to calculate accurate types
380 have long since disappeared.
381
382 \begin{code}
383 checkFunApp :: Type                 -- The function type
384             -> [Type]               -- The arg type(s)
385             -> Message              -- Error messgae
386             -> LintM (Maybe Type)   -- The result type
387
388 checkFunApp fun_ty arg_tys msg = LintM checkFunApp'
389  where
390   checkFunApp' loc _scope errs
391    = cfa res_ty expected_arg_tys arg_tys
392    where
393     (expected_arg_tys, res_ty) = splitFunTys (dropForAlls fun_ty)
394
395     cfa res_ty expected []      -- Args have run out; that's fine
396       = (Just (mkFunTys expected res_ty), errs)
397
398     cfa res_ty [] arg_tys       -- Expected arg tys ran out first;
399                                 -- first see if res_ty is a tyvar template;
400                                 -- otherwise, maybe res_ty is a
401                                 -- dictionary type which is actually a function?
402       | isTyVarTy res_ty
403       = (Just res_ty, errs)
404       | otherwise
405       = case splitFunTys res_ty of
406           ([], _)                 -> (Nothing, addErr errs msg loc)     -- Too many args
407           (new_expected, new_res) -> cfa new_res new_expected arg_tys
408
409     cfa res_ty (_:expected_arg_tys) (_:arg_tys)
410       = cfa res_ty expected_arg_tys arg_tys
411 \end{code}
412
413 \begin{code}
414 checkInScope :: Id -> LintM ()
415 checkInScope id = LintM $ \loc scope errs
416  -> if isLocalId id && not (id `elemVarSet` scope) then
417         ((), addErr errs (hsep [ppr id, ptext SLIT("is out of scope")]) loc)
418     else
419         ((), errs)
420
421 checkTys :: Type -> Type -> Message -> LintM ()
422 checkTys ty1 ty2 msg = LintM $ \loc scope errs
423  -> -- if (ty1 == ty2) then
424     ((), errs)
425     -- else ((), addErr errs msg loc)
426 \end{code}
427
428 \begin{code}
429 mkCaseAltMsg :: [StgAlt] -> Message
430 mkCaseAltMsg alts
431   = ($$) (text "In some case alternatives, type of alternatives not all same:")
432             (empty) -- LATER: ppr alts
433
434 mkDefltMsg :: Id -> Message
435 mkDefltMsg bndr
436   = ($$) (ptext SLIT("Binder of a case expression doesn't match type of scrutinee:"))
437             (panic "mkDefltMsg")
438
439 mkFunAppMsg :: Type -> [Type] -> StgExpr -> Message
440 mkFunAppMsg fun_ty arg_tys expr
441   = vcat [text "In a function application, function type doesn't match arg types:",
442               hang (ptext SLIT("Function type:")) 4 (ppr fun_ty),
443               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys)),
444               hang (ptext SLIT("Expression:")) 4 (ppr expr)]
445
446 mkRhsConMsg :: Type -> [Type] -> Message
447 mkRhsConMsg fun_ty arg_tys
448   = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
449               hang (ptext SLIT("Constructor type:")) 4 (ppr fun_ty),
450               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys))]
451
452 mkAltMsg1 :: Type -> Message
453 mkAltMsg1 ty
454   = ($$) (text "In a case expression, type of scrutinee does not match patterns")
455          (ppr ty)
456
457 mkAlgAltMsg2 :: Type -> DataCon -> Message
458 mkAlgAltMsg2 ty con
459   = vcat [
460         text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
461         ppr ty,
462         ppr con
463     ]
464
465 mkAlgAltMsg3 :: DataCon -> [Id] -> Message
466 mkAlgAltMsg3 con alts
467   = vcat [
468         text "In some algebraic case alternative, number of arguments doesn't match constructor:",
469         ppr con,
470         ppr alts
471     ]
472
473 mkAlgAltMsg4 :: Type -> Id -> Message
474 mkAlgAltMsg4 ty arg
475   = vcat [
476         text "In some algebraic case alternative, type of argument doesn't match data constructor:",
477         ppr ty,
478         ppr arg
479     ]
480
481 mkCaseOfCaseMsg :: StgExpr -> Message
482 mkCaseOfCaseMsg e
483   = text "Case of non-tail-call:" $$ ppr e
484
485 mkRhsMsg :: Id -> Type -> Message
486 mkRhsMsg binder ty
487   = vcat [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
488                      ppr binder],
489               hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
490               hsep [ptext SLIT("Rhs type:"), ppr ty]
491              ]
492
493 mkUnLiftedTyMsg binder rhs
494   = (ptext SLIT("Let(rec) binder") <+> quotes (ppr binder) <+>
495      ptext SLIT("has unlifted type") <+> quotes (ppr (idType binder)))
496     $$
497     (ptext SLIT("RHS:") <+> ppr rhs)
498 \end{code}