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