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