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