[project @ 2004-01-05 14:54:06 by simonmar]
[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, mkLocMessage )
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 SrcLoc           ( srcLocSpan )
29 import Outputable
30
31 infixr 9 `thenL`, `thenL_`, `thenMaybeL`
32 \end{code}
33
34 Checks for
35         (a) *some* type errors
36         (b) locally-defined variables used but not defined
37
38
39 Note: unless -dverbose-stg is on, display of lint errors will result
40 in "panic: bOGUS_LVs".
41
42 WARNING: 
43 ~~~~~~~~
44
45 This module has suffered bit-rot; it is likely to yield lint errors
46 for Stg code that is currently perfectly acceptable for code
47 generation.  Solution: don't use it!  (KSW 2000-05).
48
49
50 %************************************************************************
51 %*                                                                      *
52 \subsection{``lint'' for various constructs}
53 %*                                                                      *
54 %************************************************************************
55
56 @lintStgBindings@ is the top-level interface function.
57
58 \begin{code}
59 lintStgBindings :: String -> [StgBinding] -> [StgBinding]
60
61 lintStgBindings whodunnit binds
62   = _scc_ "StgLint"
63     case (initL (lint_binds binds)) of
64       Nothing  -> binds
65       Just msg -> pprPanic "" (vcat [
66                         ptext SLIT("*** Stg Lint ErrMsgs: in") <+> text whodunnit <+> ptext SLIT("***"),
67                         msg,
68                         ptext SLIT("*** Offending Program ***"),
69                         pprStgBindings binds,
70                         ptext SLIT("*** End of Offense ***")])
71   where
72     lint_binds :: [StgBinding] -> LintM ()
73
74     lint_binds [] = returnL ()
75     lint_binds (bind:binds)
76       = lintStgBinds bind               `thenL` \ binders ->
77         addInScopeVars binders (
78             lint_binds binds
79         )
80 \end{code}
81
82
83 \begin{code}
84 lintStgArg :: StgArg -> LintM (Maybe Type)
85 lintStgArg (StgLitArg lit) = returnL (Just (literalType lit))
86 lintStgArg (StgVarArg v)   = lintStgVar v
87
88 lintStgVar v  = checkInScope v  `thenL_`
89                 returnL (Just (idType v))
90 \end{code}
91
92 \begin{code}
93 lintStgBinds :: StgBinding -> LintM [Id]                -- Returns the binders
94 lintStgBinds (StgNonRec binder rhs)
95   = lint_binds_help (binder,rhs)        `thenL_`
96     returnL [binder]
97
98 lintStgBinds (StgRec pairs)
99   = addInScopeVars binders (
100         mapL lint_binds_help pairs `thenL_`
101         returnL binders
102     )
103   where
104     binders = [b | (b,_) <- pairs]
105
106 lint_binds_help (binder, rhs)
107   = addLoc (RhsOf binder) (
108         -- Check the rhs
109         lintStgRhs rhs    `thenL` \ maybe_rhs_ty ->
110
111         -- Check binder doesn't have unlifted type
112         checkL (not (isUnLiftedType binder_ty))
113                (mkUnLiftedTyMsg binder rhs)             `thenL_`
114
115         -- Check match to RHS type
116         (case maybe_rhs_ty of
117           Nothing     -> returnL ()
118           Just rhs_ty -> checkTys  binder_ty
119                                    rhs_ty
120                                    (mkRhsMsg binder rhs_ty)
121         )                       `thenL_`
122
123         returnL ()
124     )
125   where
126     binder_ty = idType binder
127 \end{code}
128
129 \begin{code}
130 lintStgRhs :: StgRhs -> LintM (Maybe Type)
131
132 lintStgRhs (StgRhsClosure _ _ _ _ _ [] expr)
133   = lintStgExpr expr
134
135 lintStgRhs (StgRhsClosure _ _ _ _ _ binders expr)
136   = addLoc (LambdaBodyOf binders) (
137     addInScopeVars binders (
138         lintStgExpr expr   `thenMaybeL` \ body_ty ->
139         returnL (Just (mkFunTys (map idType binders) body_ty))
140     ))
141
142 lintStgRhs (StgRhsCon _ con args)
143   = mapMaybeL lintStgArg args   `thenL` \ maybe_arg_tys ->
144     case maybe_arg_tys of
145       Nothing       -> returnL Nothing
146       Just arg_tys  -> checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys)
147   where
148     con_ty = dataConRepType con
149 \end{code}
150
151 \begin{code}
152 lintStgExpr :: StgExpr -> LintM (Maybe Type)    -- Nothing if error found
153
154 lintStgExpr (StgLit l) = returnL (Just (literalType l))
155
156 lintStgExpr e@(StgApp fun args)
157   = lintStgVar fun              `thenMaybeL` \ fun_ty  ->
158     mapMaybeL lintStgArg args   `thenL`      \ maybe_arg_tys ->
159     case maybe_arg_tys of
160       Nothing       -> returnL Nothing
161       Just arg_tys  -> checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e)
162
163 lintStgExpr e@(StgConApp con args)
164   = mapMaybeL lintStgArg args   `thenL` \ maybe_arg_tys ->
165     case maybe_arg_tys of
166       Nothing       -> returnL Nothing
167       Just arg_tys  -> checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e)
168   where
169     con_ty = dataConRepType con
170
171 lintStgExpr e@(StgOpApp (StgFCallOp _ _) args res_ty)
172   =     -- We don't have enough type information to check
173         -- the application; ToDo
174     mapMaybeL lintStgArg args   `thenL` \ maybe_arg_tys ->
175     returnL (Just res_ty)
176
177 lintStgExpr e@(StgOpApp (StgPrimOp op) args _)
178   = mapMaybeL lintStgArg args   `thenL` \ maybe_arg_tys ->
179     case maybe_arg_tys of
180       Nothing       -> returnL Nothing
181       Just arg_tys  -> checkFunApp op_ty arg_tys (mkFunAppMsg op_ty arg_tys e)
182   where
183     op_ty = primOpType op
184
185 lintStgExpr (StgLam _ bndrs _)
186   = addErrL (ptext SLIT("Unexpected StgLam") <+> ppr bndrs)     `thenL_`
187     returnL Nothing
188
189 lintStgExpr (StgLet binds body)
190   = lintStgBinds binds          `thenL` \ binders ->
191     addLoc (BodyOfLetRec binders) (
192     addInScopeVars binders (
193         lintStgExpr body
194     ))
195
196 lintStgExpr (StgLetNoEscape _ _ binds body)
197   = lintStgBinds binds          `thenL` \ binders ->
198     addLoc (BodyOfLetRec binders) (
199     addInScopeVars binders (
200         lintStgExpr body
201     ))
202
203 lintStgExpr (StgSCC _ expr)     = lintStgExpr expr
204
205 lintStgExpr e@(StgCase scrut _ _ bndr _ alts_type alts)
206   = lintStgExpr scrut           `thenMaybeL` \ _ ->
207
208     (case alts_type of
209         AlgAlt tc    -> check_bndr tc
210         PrimAlt tc   -> check_bndr tc
211         UbxTupAlt tc -> check_bndr tc
212         PolyAlt      -> returnL ()
213     )                                                   `thenL_`
214         
215     (trace (showSDoc (ppr e)) $ 
216         -- we only allow case of tail-call or primop.
217     (case scrut of
218         StgApp _ _    -> returnL ()
219         StgConApp _ _ -> returnL ()
220         other -> addErrL (mkCaseOfCaseMsg e))   `thenL_`
221
222     addInScopeVars [bndr] (lintStgAlts alts scrut_ty)
223     )
224   where
225     scrut_ty      = idType bndr
226     bad_bndr      = mkDefltMsg bndr
227     check_bndr tc = case splitTyConApp_maybe scrut_ty of
228                         Just (bndr_tc, _) -> checkL (tc == bndr_tc) bad_bndr
229                         Nothing           -> addErrL bad_bndr
230
231
232 lintStgAlts :: [StgAlt]
233             -> Type             -- Type of scrutinee
234             -> LintM (Maybe Type)       -- Type of alternatives
235
236 lintStgAlts alts scrut_ty
237   = mapL (lintAlt scrut_ty) alts        `thenL` \ maybe_result_tys ->
238
239          -- Check the result types
240     case catMaybes (maybe_result_tys) of
241       []             -> returnL Nothing
242
243       (first_ty:tys) -> mapL check tys  `thenL_`
244                         returnL (Just first_ty)
245         where
246           check ty = checkTys first_ty ty (mkCaseAltMsg alts)
247
248 lintAlt scrut_ty (DEFAULT, _, _, rhs)
249  = lintStgExpr rhs
250
251 lintAlt scrut_ty (LitAlt lit, _, _, rhs)
252  = checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty)     `thenL_`
253    lintStgExpr rhs
254
255 lintAlt scrut_ty (DataAlt con, args, _, rhs)
256   = (case splitTyConApp_maybe scrut_ty of
257       Just (tycon, tys_applied) | isAlgTyCon tycon && 
258                                   not (isNewTyCon tycon) ->
259          let
260            cons    = tyConDataCons tycon
261            arg_tys = dataConArgTys con tys_applied
262                 -- This almost certainly does not work for existential constructors
263          in
264          checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con) `thenL_`
265          checkL (equalLength arg_tys args) (mkAlgAltMsg3 con args)
266                                                                  `thenL_`
267          mapL check (zipEqual "lintAlgAlt:stg" arg_tys args)     `thenL_`
268          returnL ()
269       other ->
270          addErrL (mkAltMsg1 scrut_ty)
271     )                                                            `thenL_`
272     addInScopeVars args         (
273          lintStgExpr rhs
274     )
275   where
276     check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
277
278     -- elem: yes, the elem-list here can sometimes be long-ish,
279     -- but as it's use-once, probably not worth doing anything different
280     -- We give it its own copy, so it isn't overloaded.
281     elem _ []       = False
282     elem x (y:ys)   = x==y || elem x ys
283 \end{code}
284
285
286 %************************************************************************
287 %*                                                                      *
288 \subsection[lint-monad]{The Lint monad}
289 %*                                                                      *
290 %************************************************************************
291
292 \begin{code}
293 type LintM a = [LintLocInfo]    -- Locations
294             -> IdSet            -- Local vars in scope
295             -> Bag Message      -- Error messages so far
296             -> (a, Bag Message) -- Result and error messages (if any)
297
298 data LintLocInfo
299   = RhsOf Id            -- The variable bound
300   | LambdaBodyOf [Id]   -- The lambda-binder
301   | BodyOfLetRec [Id]   -- One of the binders
302
303 dumpLoc (RhsOf v) =
304   (srcLocSpan (getSrcLoc v), ptext SLIT(" [RHS of ") <> pp_binders [v] <> char ']' )
305 dumpLoc (LambdaBodyOf bs) =
306   (srcLocSpan (getSrcLoc (head bs)), ptext SLIT(" [in body of lambda with binders ") <> pp_binders bs <> char ']' )
307
308 dumpLoc (BodyOfLetRec bs) =
309   (srcLocSpan (getSrcLoc (head bs)), ptext SLIT(" [in body of letrec with binders ") <> pp_binders bs <> char ']' )
310
311
312 pp_binders :: [Id] -> SDoc
313 pp_binders bs
314   = sep (punctuate comma (map pp_binder bs))
315   where
316     pp_binder b
317       = hsep [ppr b, dcolon, ppr (idType b)]
318 \end{code}
319
320 \begin{code}
321 initL :: LintM a -> Maybe Message
322 initL m
323   = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
324     if isEmptyBag errs then
325         Nothing
326     else
327         Just (vcat (punctuate (text "") (bagToList errs)))
328     }
329
330 returnL :: a -> LintM a
331 returnL r loc scope errs = (r, errs)
332
333 thenL :: LintM a -> (a -> LintM b) -> LintM b
334 thenL m k loc scope errs
335   = case m loc scope errs of
336       (r, errs') -> k r loc scope errs'
337
338 thenL_ :: LintM a -> LintM b -> LintM b
339 thenL_ m k loc scope errs
340   = case m loc scope errs of
341       (_, errs') -> k loc scope errs'
342
343 thenMaybeL :: LintM (Maybe a) -> (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 r,  errs2) -> k r 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 Message -> Message -> [LintLocInfo] -> Bag Message
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 
379                      in  mkLocMessage l (hdr $$ msg)
380     mk_msg []      = msg
381
382 addLoc :: LintLocInfo -> LintM a -> LintM a
383 addLoc extra_loc m loc scope errs
384   = m (extra_loc:loc) scope errs
385
386 addInScopeVars :: [Id] -> LintM a -> LintM a
387 addInScopeVars ids m loc scope errs
388   = -- We check if these "new" ids are already
389     -- in scope, i.e., we have *shadowing* going on.
390     -- For now, it's just a "trace"; we may make
391     -- a real error out of it...
392     let
393         new_set = mkVarSet ids
394     in
395 --  After adding -fliberate-case, Simon decided he likes shadowed
396 --  names after all.  WDP 94/07
397 --  (if isEmptyVarSet shadowed
398 --  then id
399 --  else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $
400     m loc (scope `unionVarSet` new_set) errs
401 \end{code}
402
403 Checking function applications: we only check that the type has the
404 right *number* of arrows, we don't actually compare the types.  This
405 is because we can't expect the types to be equal - the type
406 applications and type lambdas that we use to calculate accurate types
407 have long since disappeared.
408
409 \begin{code}
410 checkFunApp :: Type                 -- The function type
411             -> [Type]               -- The arg type(s)
412             -> Message              -- Error messgae
413             -> LintM (Maybe Type)   -- The result type
414
415 checkFunApp fun_ty arg_tys msg loc scope errs
416   = cfa res_ty expected_arg_tys arg_tys
417   where
418     (expected_arg_tys, res_ty) = splitFunTys (dropForAlls fun_ty)
419
420     cfa res_ty expected []      -- Args have run out; that's fine
421       = (Just (mkFunTys expected res_ty), errs)
422
423     cfa res_ty [] arg_tys       -- Expected arg tys ran out first;
424                                 -- first see if res_ty is a tyvar template;
425                                 -- otherwise, maybe res_ty is a
426                                 -- dictionary type which is actually a function?
427       | isTyVarTy res_ty
428       = (Just res_ty, errs)
429       | otherwise
430       = case splitFunTys res_ty of
431           ([], _)                 -> (Nothing, addErr errs msg loc)     -- Too many args
432           (new_expected, new_res) -> cfa new_res new_expected arg_tys
433
434     cfa res_ty (expected_arg_ty:expected_arg_tys) (arg_ty:arg_tys)
435       = cfa res_ty expected_arg_tys arg_tys
436 \end{code}
437
438 \begin{code}
439 checkInScope :: Id -> LintM ()
440 checkInScope id loc scope errs
441   = if isLocalId id && not (id `elemVarSet` scope) then
442         ((), addErr errs (hsep [ppr id, ptext SLIT("is out of scope")]) loc)
443     else
444         ((), errs)
445
446 checkTys :: Type -> Type -> Message -> LintM ()
447 checkTys ty1 ty2 msg loc scope errs
448   = -- if (ty1 == ty2) then
449     ((), errs)
450     -- else ((), addErr errs msg loc)
451 \end{code}
452
453 \begin{code}
454 mkCaseAltMsg :: [StgAlt] -> Message
455 mkCaseAltMsg alts
456   = ($$) (text "In some case alternatives, type of alternatives not all same:")
457             (empty) -- LATER: ppr alts
458
459 mkDefltMsg :: Id -> Message
460 mkDefltMsg bndr
461   = ($$) (ptext SLIT("Binder of a case expression doesn't match type of scrutinee:"))
462             (panic "mkDefltMsg")
463
464 mkFunAppMsg :: Type -> [Type] -> StgExpr -> Message
465 mkFunAppMsg fun_ty arg_tys expr
466   = vcat [text "In a function application, function type doesn't match arg types:",
467               hang (ptext SLIT("Function type:")) 4 (ppr fun_ty),
468               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys)),
469               hang (ptext SLIT("Expression:")) 4 (ppr expr)]
470
471 mkRhsConMsg :: Type -> [Type] -> Message
472 mkRhsConMsg fun_ty arg_tys
473   = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
474               hang (ptext SLIT("Constructor type:")) 4 (ppr fun_ty),
475               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys))]
476
477 mkAltMsg1 :: Type -> Message
478 mkAltMsg1 ty
479   = ($$) (text "In a case expression, type of scrutinee does not match patterns")
480          (ppr ty)
481
482 mkAlgAltMsg2 :: Type -> DataCon -> Message
483 mkAlgAltMsg2 ty con
484   = vcat [
485         text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
486         ppr ty,
487         ppr con
488     ]
489
490 mkAlgAltMsg3 :: DataCon -> [Id] -> Message
491 mkAlgAltMsg3 con alts
492   = vcat [
493         text "In some algebraic case alternative, number of arguments doesn't match constructor:",
494         ppr con,
495         ppr alts
496     ]
497
498 mkAlgAltMsg4 :: Type -> Id -> Message
499 mkAlgAltMsg4 ty arg
500   = vcat [
501         text "In some algebraic case alternative, type of argument doesn't match data constructor:",
502         ppr ty,
503         ppr arg
504     ]
505
506 mkCaseOfCaseMsg :: StgExpr -> Message
507 mkCaseOfCaseMsg e
508   = text "Case of non-tail-call:" $$ ppr e
509
510 mkRhsMsg :: Id -> Type -> Message
511 mkRhsMsg binder ty
512   = vcat [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
513                      ppr binder],
514               hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
515               hsep [ptext SLIT("Rhs type:"), ppr ty]
516              ]
517
518 mkUnLiftedTyMsg binder rhs
519   = (ptext SLIT("Let(rec) binder") <+> quotes (ppr binder) <+> 
520      ptext SLIT("has unlifted type") <+> quotes (ppr (idType binder)))
521     $$
522     (ptext SLIT("RHS:") <+> ppr rhs)
523 \end{code}