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