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