[project @ 2003-10-09 11:58:39 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, bagToList )
14 import Id               ( Id, idType, isLocalId )
15 import VarSet
16 import DataCon          ( DataCon, dataConArgTys, dataConRepType )
17 import CoreSyn          ( AltCon(..) )
18 import PrimOp           ( primOpType )
19 import Literal          ( literalType )
20 import Maybes           ( catMaybes )
21 import Name             ( getSrcLoc )
22 import ErrUtils         ( Message, addErrLocHdrLine )
23 import Type             ( mkFunTys, splitFunTys, splitTyConApp_maybe,
24                           isUnLiftedType, isTyVarTy, dropForAlls, Type
25                         )
26 import TyCon            ( isAlgTyCon, isNewTyCon, tyConDataCons )
27 import Util             ( zipEqual, equalLength )
28 import Outputable
29
30 infixr 9 `thenL`, `thenL_`, `thenMaybeL`
31 \end{code}
32
33 Checks for
34         (a) *some* type errors
35         (b) locally-defined variables used but not defined
36
37
38 Note: unless -dverbose-stg is on, display of lint errors will result
39 in "panic: bOGUS_LVs".
40
41 WARNING: 
42 ~~~~~~~~
43
44 This module has suffered bit-rot; it is likely to yield lint errors
45 for Stg code that is currently perfectly acceptable for code
46 generation.  Solution: don't use it!  (KSW 2000-05).
47
48
49 %************************************************************************
50 %*                                                                      *
51 \subsection{``lint'' for various constructs}
52 %*                                                                      *
53 %************************************************************************
54
55 @lintStgBindings@ is the top-level interface function.
56
57 \begin{code}
58 lintStgBindings :: String -> [StgBinding] -> [StgBinding]
59
60 lintStgBindings whodunnit binds
61   = _scc_ "StgLint"
62     case (initL (lint_binds binds)) of
63       Nothing  -> binds
64       Just msg -> pprPanic "" (vcat [
65                         ptext SLIT("*** Stg Lint ErrMsgs: in") <+> text whodunnit <+> ptext SLIT("***"),
66                         msg,
67                         ptext SLIT("*** Offending Program ***"),
68                         pprStgBindings binds,
69                         ptext SLIT("*** End of Offense ***")])
70   where
71     lint_binds :: [StgBinding] -> LintM ()
72
73     lint_binds [] = returnL ()
74     lint_binds (bind:binds)
75       = lintStgBinds bind               `thenL` \ binders ->
76         addInScopeVars binders (
77             lint_binds binds
78         )
79 \end{code}
80
81
82 \begin{code}
83 lintStgArg :: StgArg -> LintM (Maybe Type)
84 lintStgArg (StgLitArg lit) = returnL (Just (literalType lit))
85 lintStgArg (StgVarArg v)   = lintStgVar v
86
87 lintStgVar v  = checkInScope v  `thenL_`
88                 returnL (Just (idType v))
89 \end{code}
90
91 \begin{code}
92 lintStgBinds :: StgBinding -> LintM [Id]                -- Returns the binders
93 lintStgBinds (StgNonRec binder rhs)
94   = lint_binds_help (binder,rhs)        `thenL_`
95     returnL [binder]
96
97 lintStgBinds (StgRec pairs)
98   = addInScopeVars binders (
99         mapL lint_binds_help pairs `thenL_`
100         returnL binders
101     )
102   where
103     binders = [b | (b,_) <- pairs]
104
105 lint_binds_help (binder, rhs)
106   = addLoc (RhsOf binder) (
107         -- Check the rhs
108         lintStgRhs rhs    `thenL` \ maybe_rhs_ty ->
109
110         -- Check binder doesn't have unlifted type
111         checkL (not (isUnLiftedType binder_ty))
112                (mkUnLiftedTyMsg binder rhs)             `thenL_`
113
114         -- Check match to RHS type
115         (case maybe_rhs_ty of
116           Nothing     -> returnL ()
117           Just rhs_ty -> checkTys  binder_ty
118                                    rhs_ty
119                                    (mkRhsMsg binder rhs_ty)
120         )                       `thenL_`
121
122         returnL ()
123     )
124   where
125     binder_ty = idType binder
126 \end{code}
127
128 \begin{code}
129 lintStgRhs :: StgRhs -> LintM (Maybe Type)
130
131 lintStgRhs (StgRhsClosure _ _ _ _ _ [] expr)
132   = lintStgExpr expr
133
134 lintStgRhs (StgRhsClosure _ _ _ _ _ binders expr)
135   = addLoc (LambdaBodyOf binders) (
136     addInScopeVars binders (
137         lintStgExpr expr   `thenMaybeL` \ body_ty ->
138         returnL (Just (mkFunTys (map idType binders) body_ty))
139     ))
140
141 lintStgRhs (StgRhsCon _ con args)
142   = mapMaybeL lintStgArg args   `thenL` \ maybe_arg_tys ->
143     case maybe_arg_tys of
144       Nothing       -> returnL Nothing
145       Just arg_tys  -> checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys)
146   where
147     con_ty = dataConRepType con
148 \end{code}
149
150 \begin{code}
151 lintStgExpr :: StgExpr -> LintM (Maybe Type)    -- Nothing if error found
152
153 lintStgExpr (StgLit l) = returnL (Just (literalType l))
154
155 lintStgExpr e@(StgApp fun args)
156   = lintStgVar fun              `thenMaybeL` \ fun_ty  ->
157     mapMaybeL lintStgArg args   `thenL`      \ maybe_arg_tys ->
158     case maybe_arg_tys of
159       Nothing       -> returnL Nothing
160       Just arg_tys  -> checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e)
161
162 lintStgExpr e@(StgConApp con args)
163   = mapMaybeL lintStgArg args   `thenL` \ maybe_arg_tys ->
164     case maybe_arg_tys of
165       Nothing       -> returnL Nothing
166       Just arg_tys  -> checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e)
167   where
168     con_ty = dataConRepType con
169
170 lintStgExpr e@(StgOpApp (StgFCallOp _ _) args res_ty)
171   =     -- We don't have enough type information to check
172         -- the application; ToDo
173     mapMaybeL lintStgArg args   `thenL` \ maybe_arg_tys ->
174     returnL (Just res_ty)
175
176 lintStgExpr e@(StgOpApp (StgPrimOp op) args _)
177   = mapMaybeL lintStgArg args   `thenL` \ maybe_arg_tys ->
178     case maybe_arg_tys of
179       Nothing       -> returnL Nothing
180       Just arg_tys  -> checkFunApp op_ty arg_tys (mkFunAppMsg op_ty arg_tys e)
181   where
182     op_ty = primOpType op
183
184 lintStgExpr (StgLam _ bndrs _)
185   = addErrL (ptext SLIT("Unexpected StgLam") <+> ppr bndrs)     `thenL_`
186     returnL Nothing
187
188 lintStgExpr (StgLet binds body)
189   = lintStgBinds binds          `thenL` \ binders ->
190     addLoc (BodyOfLetRec binders) (
191     addInScopeVars binders (
192         lintStgExpr body
193     ))
194
195 lintStgExpr (StgLetNoEscape _ _ binds body)
196   = lintStgBinds binds          `thenL` \ binders ->
197     addLoc (BodyOfLetRec binders) (
198     addInScopeVars binders (
199         lintStgExpr body
200     ))
201
202 lintStgExpr (StgSCC _ expr)     = lintStgExpr expr
203
204 lintStgExpr e@(StgCase scrut _ _ bndr _ alts_type alts)
205   = lintStgExpr scrut           `thenMaybeL` \ _ ->
206
207     (case alts_type of
208         AlgAlt tc    -> check_bndr tc
209         PrimAlt tc   -> check_bndr tc
210         UbxTupAlt tc -> check_bndr tc
211         PolyAlt      -> returnL ()
212     )                                                   `thenL_`
213         
214     (trace (showSDoc (ppr e)) $ 
215         -- we only allow case of tail-call or primop.
216     (case scrut of
217         StgApp _ _    -> returnL ()
218         StgConApp _ _ -> returnL ()
219         other -> addErrL (mkCaseOfCaseMsg e))   `thenL_`
220
221     addInScopeVars [bndr] (lintStgAlts alts scrut_ty)
222     )
223   where
224     scrut_ty      = idType bndr
225     bad_bndr      = mkDefltMsg bndr
226     check_bndr tc = case splitTyConApp_maybe scrut_ty of
227                         Just (bndr_tc, _) -> checkL (tc == bndr_tc) bad_bndr
228                         Nothing           -> addErrL bad_bndr
229
230
231 lintStgAlts :: [StgAlt]
232             -> Type             -- Type of scrutinee
233             -> LintM (Maybe Type)       -- Type of alternatives
234
235 lintStgAlts alts scrut_ty
236   = mapL (lintAlt scrut_ty) alts        `thenL` \ maybe_result_tys ->
237
238          -- Check the result types
239     case catMaybes (maybe_result_tys) of
240       []             -> returnL Nothing
241
242       (first_ty:tys) -> mapL check tys  `thenL_`
243                         returnL (Just first_ty)
244         where
245           check ty = checkTys first_ty ty (mkCaseAltMsg alts)
246
247 lintAlt scrut_ty (DEFAULT, _, _, rhs)
248  = lintStgExpr rhs
249
250 lintAlt scrut_ty (LitAlt lit, _, _, rhs)
251  = checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty)     `thenL_`
252    lintStgExpr rhs
253
254 lintAlt scrut_ty (DataAlt con, args, _, rhs)
255   = (case splitTyConApp_maybe scrut_ty of
256       Just (tycon, tys_applied) | isAlgTyCon tycon && 
257                                   not (isNewTyCon 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 (mkAltMsg1 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 \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 Message      -- Error messages so far
295             -> (a, Bag Message) -- 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 (vcat (punctuate (text "") (bagToList 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 mapL :: (a -> LintM b) -> [a] -> LintM [b]
349 mapL f [] = returnL []
350 mapL f (x:xs)
351   = f x         `thenL` \ r ->
352     mapL f xs   `thenL` \ rs ->
353     returnL (r:rs)
354
355 mapMaybeL :: (a -> LintM (Maybe b)) -> [a] -> LintM (Maybe [b])
356         -- Returns Nothing if anything fails
357 mapMaybeL f [] = returnL (Just [])
358 mapMaybeL f (x:xs)
359   = f x             `thenMaybeL` \ r ->
360     mapMaybeL f xs  `thenMaybeL` \ rs ->
361     returnL (Just (r:rs))
362 \end{code}
363
364 \begin{code}
365 checkL :: Bool -> Message -> LintM ()
366 checkL True  msg loc scope errs = ((), errs)
367 checkL False msg loc scope errs = ((), addErr errs msg loc)
368
369 addErrL :: Message -> LintM ()
370 addErrL msg loc scope errs = ((), addErr errs msg loc)
371
372 addErr :: Bag Message -> Message -> [LintLocInfo] -> Bag Message
373
374 addErr errs_so_far msg locs
375   = errs_so_far `snocBag` mk_msg locs
376   where
377     mk_msg (loc:_) = let (l,hdr) = dumpLoc loc 
378                      in addErrLocHdrLine l hdr msg
379     mk_msg []      = msg
380
381 addLoc :: LintLocInfo -> LintM a -> LintM a
382 addLoc extra_loc m loc scope errs
383   = m (extra_loc:loc) scope errs
384
385 addInScopeVars :: [Id] -> LintM a -> LintM a
386 addInScopeVars ids m loc scope errs
387   = -- We check if these "new" ids are already
388     -- in scope, i.e., we have *shadowing* going on.
389     -- For now, it's just a "trace"; we may make
390     -- a real error out of it...
391     let
392         new_set = mkVarSet ids
393     in
394 --  After adding -fliberate-case, Simon decided he likes shadowed
395 --  names after all.  WDP 94/07
396 --  (if isEmptyVarSet shadowed
397 --  then id
398 --  else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $
399     m loc (scope `unionVarSet` new_set) errs
400 \end{code}
401
402 Checking function applications: we only check that the type has the
403 right *number* of arrows, we don't actually compare the types.  This
404 is because we can't expect the types to be equal - the type
405 applications and type lambdas that we use to calculate accurate types
406 have long since disappeared.
407
408 \begin{code}
409 checkFunApp :: Type                 -- The function type
410             -> [Type]               -- The arg type(s)
411             -> Message              -- Error messgae
412             -> LintM (Maybe Type)   -- The result type
413
414 checkFunApp fun_ty arg_tys msg loc scope errs
415   = cfa res_ty expected_arg_tys arg_tys
416   where
417     (expected_arg_tys, res_ty) = splitFunTys (dropForAlls fun_ty)
418
419     cfa res_ty expected []      -- Args have run out; that's fine
420       = (Just (mkFunTys expected res_ty), errs)
421
422     cfa res_ty [] arg_tys       -- Expected arg tys ran out first;
423                                 -- first see if res_ty is a tyvar template;
424                                 -- otherwise, maybe res_ty is a
425                                 -- dictionary type which is actually a function?
426       | isTyVarTy res_ty
427       = (Just res_ty, errs)
428       | otherwise
429       = case splitFunTys res_ty of
430           ([], _)                 -> (Nothing, addErr errs msg loc)     -- Too many args
431           (new_expected, new_res) -> cfa new_res new_expected arg_tys
432
433     cfa res_ty (expected_arg_ty:expected_arg_tys) (arg_ty:arg_tys)
434       = cfa res_ty expected_arg_tys arg_tys
435 \end{code}
436
437 \begin{code}
438 checkInScope :: Id -> LintM ()
439 checkInScope id loc scope errs
440   = if isLocalId id && not (id `elemVarSet` scope) then
441         ((), addErr errs (hsep [ppr id, ptext SLIT("is out of scope")]) loc)
442     else
443         ((), errs)
444
445 checkTys :: Type -> Type -> Message -> LintM ()
446 checkTys ty1 ty2 msg loc scope errs
447   = -- if (ty1 == ty2) then
448     ((), errs)
449     -- else ((), addErr errs msg loc)
450 \end{code}
451
452 \begin{code}
453 mkCaseAltMsg :: [StgAlt] -> Message
454 mkCaseAltMsg alts
455   = ($$) (text "In some case alternatives, type of alternatives not all same:")
456             (empty) -- LATER: ppr alts
457
458 mkDefltMsg :: Id -> Message
459 mkDefltMsg bndr
460   = ($$) (ptext SLIT("Binder of a case expression doesn't match type of scrutinee:"))
461             (panic "mkDefltMsg")
462
463 mkFunAppMsg :: Type -> [Type] -> StgExpr -> Message
464 mkFunAppMsg fun_ty arg_tys expr
465   = vcat [text "In a function application, function type doesn't match arg types:",
466               hang (ptext SLIT("Function type:")) 4 (ppr fun_ty),
467               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys)),
468               hang (ptext SLIT("Expression:")) 4 (ppr expr)]
469
470 mkRhsConMsg :: Type -> [Type] -> Message
471 mkRhsConMsg fun_ty arg_tys
472   = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
473               hang (ptext SLIT("Constructor type:")) 4 (ppr fun_ty),
474               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys))]
475
476 mkAltMsg1 :: Type -> Message
477 mkAltMsg1 ty
478   = ($$) (text "In a case expression, type of scrutinee does not match patterns")
479          (ppr ty)
480
481 mkAlgAltMsg2 :: Type -> DataCon -> Message
482 mkAlgAltMsg2 ty con
483   = vcat [
484         text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
485         ppr ty,
486         ppr con
487     ]
488
489 mkAlgAltMsg3 :: DataCon -> [Id] -> Message
490 mkAlgAltMsg3 con alts
491   = vcat [
492         text "In some algebraic case alternative, number of arguments doesn't match constructor:",
493         ppr con,
494         ppr alts
495     ]
496
497 mkAlgAltMsg4 :: Type -> Id -> Message
498 mkAlgAltMsg4 ty arg
499   = vcat [
500         text "In some algebraic case alternative, type of argument doesn't match data constructor:",
501         ppr ty,
502         ppr arg
503     ]
504
505 mkCaseOfCaseMsg :: StgExpr -> Message
506 mkCaseOfCaseMsg e
507   = text "Case of non-tail-call:" $$ ppr e
508
509 mkRhsMsg :: Id -> Type -> Message
510 mkRhsMsg binder ty
511   = vcat [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
512                      ppr binder],
513               hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
514               hsep [ptext SLIT("Rhs type:"), ppr ty]
515              ]
516
517 mkUnLiftedTyMsg binder rhs
518   = (ptext SLIT("Let(rec) binder") <+> quotes (ppr binder) <+> 
519      ptext SLIT("has unlifted type") <+> quotes (ppr (idType binder)))
520     $$
521     (ptext SLIT("RHS:") <+> ppr rhs)
522 \end{code}