[project @ 2001-10-25 02:13:10 by sof]
[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 )
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         ( ErrMsg, Message, addErrLocHdrLine, pprBagOfErrors, dontAddErrLoc )
22 import Type             ( mkFunTys, splitFunTys, splitTyConApp_maybe,
23                           isUnLiftedType, isTyVarTy, splitForAllTys, Type
24                         )
25 import TyCon            ( TyCon, isDataTyCon, 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 _srt binder rhs)
93   = lint_binds_help (binder,rhs)        `thenL_`
94     returnL [binder]
95
96 lintStgBinds (StgRec _srt 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) | isDataTyCon tycon ->
258          let
259            cons    = tyConDataCons tycon
260            arg_tys = dataConArgTys con tys_applied
261                 -- This almost certainly does not work for existential constructors
262          in
263          checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con) `thenL_`
264          checkL (equalLength arg_tys args) (mkAlgAltMsg3 con args)
265                                                                  `thenL_`
266          mapL check (zipEqual "lintAlgAlt:stg" arg_tys args)     `thenL_`
267          returnL ()
268       other ->
269          addErrL (mkAlgAltMsg1 scrut_ty)
270     )                                                            `thenL_`
271     addInScopeVars args         (
272          lintStgExpr rhs
273     )
274   where
275     check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
276
277     -- elem: yes, the elem-list here can sometimes be long-ish,
278     -- but as it's use-once, probably not worth doing anything different
279     -- We give it its own copy, so it isn't overloaded.
280     elem _ []       = False
281     elem x (y:ys)   = x==y || elem x ys
282
283 lintPrimAlt scrut_ty alt@(lit,rhs)
284  = checkTys (literalType lit) scrut_ty (mkPrimAltMsg alt)       `thenL_`
285    lintStgExpr rhs
286
287 lintDeflt StgNoDefault scrut_ty = returnL Nothing
288 lintDeflt deflt@(StgBindDefault rhs) scrut_ty = lintStgExpr rhs
289 \end{code}
290
291
292 %************************************************************************
293 %*                                                                      *
294 \subsection[lint-monad]{The Lint monad}
295 %*                                                                      *
296 %************************************************************************
297
298 \begin{code}
299 type LintM a = [LintLocInfo]    -- Locations
300             -> IdSet            -- Local vars in scope
301             -> Bag ErrMsg       -- Error messages so far
302             -> (a, Bag ErrMsg)  -- Result and error messages (if any)
303
304 data LintLocInfo
305   = RhsOf Id            -- The variable bound
306   | LambdaBodyOf [Id]   -- The lambda-binder
307   | BodyOfLetRec [Id]   -- One of the binders
308
309 dumpLoc (RhsOf v) =
310   (getSrcLoc v, ptext SLIT(" [RHS of ") <> pp_binders [v] <> char ']' )
311 dumpLoc (LambdaBodyOf bs) =
312   (getSrcLoc (head bs), ptext SLIT(" [in body of lambda with binders ") <> pp_binders bs <> char ']' )
313
314 dumpLoc (BodyOfLetRec bs) =
315   (getSrcLoc (head bs), ptext SLIT(" [in body of letrec with binders ") <> pp_binders bs <> char ']' )
316
317
318 pp_binders :: [Id] -> SDoc
319 pp_binders bs
320   = sep (punctuate comma (map pp_binder bs))
321   where
322     pp_binder b
323       = hsep [ppr b, dcolon, ppr (idType b)]
324 \end{code}
325
326 \begin{code}
327 initL :: LintM a -> Maybe Message
328 initL m
329   = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
330     if isEmptyBag errs then
331         Nothing
332     else
333         Just (pprBagOfErrors errs)
334     }
335
336 returnL :: a -> LintM a
337 returnL r loc scope errs = (r, errs)
338
339 thenL :: LintM a -> (a -> LintM b) -> LintM b
340 thenL m k loc scope errs
341   = case m loc scope errs of
342       (r, errs') -> k r loc scope errs'
343
344 thenL_ :: LintM a -> LintM b -> LintM b
345 thenL_ m k loc scope errs
346   = case m loc scope errs of
347       (_, errs') -> k loc scope errs'
348
349 thenMaybeL :: LintM (Maybe a) -> (a -> LintM (Maybe b)) -> LintM (Maybe b)
350 thenMaybeL m k loc scope errs
351   = case m loc scope errs of
352       (Nothing, errs2) -> (Nothing, errs2)
353       (Just r,  errs2) -> k r loc scope errs2
354
355 thenMaybeL_ :: LintM (Maybe a) -> LintM (Maybe b) -> LintM (Maybe b)
356 thenMaybeL_ m k loc scope errs
357   = case m loc scope errs of
358       (Nothing, errs2) -> (Nothing, errs2)
359       (Just _,  errs2) -> k loc scope errs2
360
361 mapL :: (a -> LintM b) -> [a] -> LintM [b]
362 mapL f [] = returnL []
363 mapL f (x:xs)
364   = f x         `thenL` \ r ->
365     mapL f xs   `thenL` \ rs ->
366     returnL (r:rs)
367
368 mapMaybeL :: (a -> LintM (Maybe b)) -> [a] -> LintM (Maybe [b])
369         -- Returns Nothing if anything fails
370 mapMaybeL f [] = returnL (Just [])
371 mapMaybeL f (x:xs)
372   = f x             `thenMaybeL` \ r ->
373     mapMaybeL f xs  `thenMaybeL` \ rs ->
374     returnL (Just (r:rs))
375 \end{code}
376
377 \begin{code}
378 checkL :: Bool -> Message -> LintM ()
379 checkL True  msg loc scope errs = ((), errs)
380 checkL False msg loc scope errs = ((), addErr errs msg loc)
381
382 addErrL :: Message -> LintM ()
383 addErrL msg loc scope errs = ((), addErr errs msg loc)
384
385 addErr :: Bag ErrMsg -> Message -> [LintLocInfo] -> Bag ErrMsg
386
387 addErr errs_so_far msg locs
388   = errs_so_far `snocBag` mk_msg locs
389   where
390     mk_msg (loc:_) = let (l,hdr) = dumpLoc loc in addErrLocHdrLine l hdr msg
391     mk_msg []      = dontAddErrLoc msg
392
393 addLoc :: LintLocInfo -> LintM a -> LintM a
394 addLoc extra_loc m loc scope errs
395   = m (extra_loc:loc) scope errs
396
397 addInScopeVars :: [Id] -> LintM a -> LintM a
398 addInScopeVars ids m loc scope errs
399   = -- We check if these "new" ids are already
400     -- in scope, i.e., we have *shadowing* going on.
401     -- For now, it's just a "trace"; we may make
402     -- a real error out of it...
403     let
404         new_set = mkVarSet ids
405     in
406 --  After adding -fliberate-case, Simon decided he likes shadowed
407 --  names after all.  WDP 94/07
408 --  (if isEmptyVarSet shadowed
409 --  then id
410 --  else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $
411     m loc (scope `unionVarSet` new_set) errs
412 \end{code}
413
414 Checking function applications: we only check that the type has the
415 right *number* of arrows, we don't actually compare the types.  This
416 is because we can't expect the types to be equal - the type
417 applications and type lambdas that we use to calculate accurate types
418 have long since disappeared.
419
420 \begin{code}
421 checkFunApp :: Type                 -- The function type
422             -> [Type]               -- The arg type(s)
423             -> Message              -- Error messgae
424             -> LintM (Maybe Type)   -- The result type
425
426 checkFunApp fun_ty arg_tys msg loc scope errs
427   = cfa res_ty expected_arg_tys arg_tys
428   where
429     (_, de_forall_ty)          = splitForAllTys fun_ty
430     (expected_arg_tys, res_ty) = splitFunTys de_forall_ty
431
432     cfa res_ty expected []      -- Args have run out; that's fine
433       = (Just (mkFunTys expected res_ty), errs)
434
435     cfa res_ty [] arg_tys       -- Expected arg tys ran out first;
436                                 -- first see if res_ty is a tyvar template;
437                                 -- otherwise, maybe res_ty is a
438                                 -- dictionary type which is actually a function?
439       | isTyVarTy res_ty
440       = (Just res_ty, errs)
441       | otherwise
442       = case splitFunTys res_ty of
443           ([], _)                 -> (Nothing, addErr errs msg loc)     -- Too many args
444           (new_expected, new_res) -> cfa new_res new_expected arg_tys
445
446     cfa res_ty (expected_arg_ty:expected_arg_tys) (arg_ty:arg_tys)
447       = cfa res_ty expected_arg_tys arg_tys
448 \end{code}
449
450 \begin{code}
451 checkInScope :: Id -> LintM ()
452 checkInScope id loc scope errs
453   = if isLocalId id && not (id `elemVarSet` scope) then
454         ((), addErr errs (hsep [ppr id, ptext SLIT("is out of scope")]) loc)
455     else
456         ((), errs)
457
458 checkTys :: Type -> Type -> Message -> LintM ()
459 checkTys ty1 ty2 msg loc scope errs
460   = -- if (ty1 == ty2) then
461     ((), errs)
462     -- else ((), addErr errs msg loc)
463 \end{code}
464
465 \begin{code}
466 mkCaseAltMsg :: StgCaseAlts -> Message
467 mkCaseAltMsg alts
468   = ($$) (text "In some case alternatives, type of alternatives not all same:")
469             (empty) -- LATER: ppr alts
470
471 mkCaseAbstractMsg :: TyCon -> Message
472 mkCaseAbstractMsg tycon
473   = ($$) (ptext SLIT("An algebraic case on an abstract type:"))
474             (ppr tycon)
475
476 mkDefltMsg :: Id -> Message
477 mkDefltMsg bndr
478   = ($$) (ptext SLIT("Binder of a case expression doesn't match type of scrutinee:"))
479             (panic "mkDefltMsg")
480
481 mkFunAppMsg :: Type -> [Type] -> StgExpr -> Message
482 mkFunAppMsg fun_ty arg_tys expr
483   = vcat [text "In a function application, function type doesn't match arg types:",
484               hang (ptext SLIT("Function type:")) 4 (ppr fun_ty),
485               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys)),
486               hang (ptext SLIT("Expression:")) 4 (ppr expr)]
487
488 mkRhsConMsg :: Type -> [Type] -> Message
489 mkRhsConMsg fun_ty arg_tys
490   = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
491               hang (ptext SLIT("Constructor type:")) 4 (ppr fun_ty),
492               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys))]
493
494 mkUnappTyMsg :: Id -> Type -> Message
495 mkUnappTyMsg var ty
496   = vcat [text "Variable has a for-all type, but isn't applied to any types.",
497               (<>) (ptext SLIT("Var:      ")) (ppr var),
498               (<>) (ptext SLIT("Its type: ")) (ppr ty)]
499
500 mkAlgAltMsg1 :: Type -> Message
501 mkAlgAltMsg1 ty
502   = ($$) (text "In some case statement, type of scrutinee is not a data type:")
503             (ppr ty)
504
505 mkAlgAltMsg2 :: Type -> DataCon -> Message
506 mkAlgAltMsg2 ty con
507   = vcat [
508         text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
509         ppr ty,
510         ppr con
511     ]
512
513 mkAlgAltMsg3 :: DataCon -> [Id] -> Message
514 mkAlgAltMsg3 con alts
515   = vcat [
516         text "In some algebraic case alternative, number of arguments doesn't match constructor:",
517         ppr con,
518         ppr alts
519     ]
520
521 mkAlgAltMsg4 :: Type -> Id -> Message
522 mkAlgAltMsg4 ty arg
523   = vcat [
524         text "In some algebraic case alternative, type of argument doesn't match data constructor:",
525         ppr ty,
526         ppr arg
527     ]
528
529 mkPrimAltMsg :: (Literal, StgExpr) -> Message
530 mkPrimAltMsg alt
531   = text "In a primitive case alternative, type of literal doesn't match type of scrutinee:"
532     $$ ppr alt
533
534 mkCaseOfCaseMsg :: StgExpr -> Message
535 mkCaseOfCaseMsg e
536   = text "Case of non-tail-call:" $$ ppr e
537
538 mkRhsMsg :: Id -> Type -> Message
539 mkRhsMsg binder ty
540   = vcat [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
541                      ppr binder],
542               hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
543               hsep [ptext SLIT("Rhs type:"), ppr ty]
544              ]
545
546 mkUnLiftedTyMsg binder rhs
547   = (ptext SLIT("Let(rec) binder") <+> quotes (ppr binder) <+> 
548      ptext SLIT("has unlifted type") <+> quotes (ppr (idType binder)))
549     $$
550     (ptext SLIT("RHS:") <+> ppr rhs)
551 \end{code}