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