[project @ 2003-07-02 13:12:33 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            ( TyCon, isAlgTyCon, isNewTyCon, tyConDataCons )
27 import Util             ( zipEqual, equalLength )
28 import Outputable
29
30 infixr 9 `thenL`, `thenL_`, `thenMaybeL`, `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 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 Message -> Message -> [LintLocInfo] -> Bag Message
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 
384                      in addErrLocHdrLine l hdr msg
385     mk_msg []      = msg
386
387 addLoc :: LintLocInfo -> LintM a -> LintM a
388 addLoc extra_loc m loc scope errs
389   = m (extra_loc:loc) scope errs
390
391 addInScopeVars :: [Id] -> LintM a -> LintM a
392 addInScopeVars ids m loc scope errs
393   = -- We check if these "new" ids are already
394     -- in scope, i.e., we have *shadowing* going on.
395     -- For now, it's just a "trace"; we may make
396     -- a real error out of it...
397     let
398         new_set = mkVarSet ids
399     in
400 --  After adding -fliberate-case, Simon decided he likes shadowed
401 --  names after all.  WDP 94/07
402 --  (if isEmptyVarSet shadowed
403 --  then id
404 --  else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $
405     m loc (scope `unionVarSet` new_set) errs
406 \end{code}
407
408 Checking function applications: we only check that the type has the
409 right *number* of arrows, we don't actually compare the types.  This
410 is because we can't expect the types to be equal - the type
411 applications and type lambdas that we use to calculate accurate types
412 have long since disappeared.
413
414 \begin{code}
415 checkFunApp :: Type                 -- The function type
416             -> [Type]               -- The arg type(s)
417             -> Message              -- Error messgae
418             -> LintM (Maybe Type)   -- The result type
419
420 checkFunApp fun_ty arg_tys msg loc scope errs
421   = cfa res_ty expected_arg_tys arg_tys
422   where
423     (expected_arg_tys, res_ty) = splitFunTys (dropForAlls fun_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 :: [StgAlt] -> 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 mkAltMsg1 :: Type -> Message
494 mkAltMsg1 ty
495   = ($$) (text "In a case expression, type of scrutinee does not match patterns")
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 mkCaseOfCaseMsg :: StgExpr -> Message
523 mkCaseOfCaseMsg e
524   = text "Case of non-tail-call:" $$ ppr e
525
526 mkRhsMsg :: Id -> Type -> Message
527 mkRhsMsg binder ty
528   = vcat [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
529                      ppr binder],
530               hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
531               hsep [ptext SLIT("Rhs type:"), ppr ty]
532              ]
533
534 mkUnLiftedTyMsg binder rhs
535   = (ptext SLIT("Let(rec) binder") <+> quotes (ppr binder) <+> 
536      ptext SLIT("has unlifted type") <+> quotes (ppr (idType binder)))
537     $$
538     (ptext SLIT("RHS:") <+> ppr rhs)
539 \end{code}