Reorganisation of the source tree
[ghc-hetmet.git] / 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, dataConInstArgTys, 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         StgOpApp _ _ _ -> returnL ()
221         other -> addErrL (mkCaseOfCaseMsg e))   `thenL_`
222
223     addInScopeVars [bndr] (lintStgAlts alts scrut_ty)
224     )
225   where
226     scrut_ty      = idType bndr
227     bad_bndr      = mkDefltMsg bndr
228     check_bndr tc = case splitTyConApp_maybe scrut_ty of
229                         Just (bndr_tc, _) -> checkL (tc == bndr_tc) bad_bndr
230                         Nothing           -> addErrL bad_bndr
231
232
233 lintStgAlts :: [StgAlt]
234             -> Type             -- Type of scrutinee
235             -> LintM (Maybe Type)       -- Type of alternatives
236
237 lintStgAlts alts scrut_ty
238   = mapL (lintAlt scrut_ty) alts        `thenL` \ maybe_result_tys ->
239
240          -- Check the result types
241     case catMaybes (maybe_result_tys) of
242       []             -> returnL Nothing
243
244       (first_ty:tys) -> mapL check tys  `thenL_`
245                         returnL (Just first_ty)
246         where
247           check ty = checkTys first_ty ty (mkCaseAltMsg alts)
248
249 lintAlt scrut_ty (DEFAULT, _, _, rhs)
250  = lintStgExpr rhs
251
252 lintAlt scrut_ty (LitAlt lit, _, _, rhs)
253  = checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty)     `thenL_`
254    lintStgExpr rhs
255
256 lintAlt scrut_ty (DataAlt con, args, _, rhs)
257   = (case splitTyConApp_maybe scrut_ty of
258       Just (tycon, tys_applied) | isAlgTyCon tycon && 
259                                   not (isNewTyCon tycon) ->
260          let
261            cons    = tyConDataCons tycon
262            arg_tys = dataConInstArgTys con tys_applied
263                 -- This almost certainly does not work for existential constructors
264          in
265          checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con) `thenL_`
266          checkL (equalLength arg_tys args) (mkAlgAltMsg3 con args)
267                                                                  `thenL_`
268          mapL check (zipEqual "lintAlgAlt:stg" arg_tys args)     `thenL_`
269          returnL ()
270       other ->
271          addErrL (mkAltMsg1 scrut_ty)
272     )                                                            `thenL_`
273     addInScopeVars args         (
274          lintStgExpr rhs
275     )
276   where
277     check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
278
279     -- elem: yes, the elem-list here can sometimes be long-ish,
280     -- but as it's use-once, probably not worth doing anything different
281     -- We give it its own copy, so it isn't overloaded.
282     elem _ []       = False
283     elem x (y:ys)   = x==y || elem x ys
284 \end{code}
285
286
287 %************************************************************************
288 %*                                                                      *
289 \subsection[lint-monad]{The Lint monad}
290 %*                                                                      *
291 %************************************************************************
292
293 \begin{code}
294 type LintM a = [LintLocInfo]    -- Locations
295             -> IdSet            -- Local vars in scope
296             -> Bag Message      -- Error messages so far
297             -> (a, Bag Message) -- Result and error messages (if any)
298
299 data LintLocInfo
300   = RhsOf Id            -- The variable bound
301   | LambdaBodyOf [Id]   -- The lambda-binder
302   | BodyOfLetRec [Id]   -- One of the binders
303
304 dumpLoc (RhsOf v) =
305   (srcLocSpan (getSrcLoc v), ptext SLIT(" [RHS of ") <> pp_binders [v] <> char ']' )
306 dumpLoc (LambdaBodyOf bs) =
307   (srcLocSpan (getSrcLoc (head bs)), ptext SLIT(" [in body of lambda with binders ") <> pp_binders bs <> char ']' )
308
309 dumpLoc (BodyOfLetRec bs) =
310   (srcLocSpan (getSrcLoc (head bs)), ptext SLIT(" [in body of letrec with binders ") <> pp_binders bs <> char ']' )
311
312
313 pp_binders :: [Id] -> SDoc
314 pp_binders bs
315   = sep (punctuate comma (map pp_binder bs))
316   where
317     pp_binder b
318       = hsep [ppr b, dcolon, ppr (idType b)]
319 \end{code}
320
321 \begin{code}
322 initL :: LintM a -> Maybe Message
323 initL m
324   = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
325     if isEmptyBag errs then
326         Nothing
327     else
328         Just (vcat (punctuate (text "") (bagToList errs)))
329     }
330
331 returnL :: a -> LintM a
332 returnL r loc scope errs = (r, errs)
333
334 thenL :: LintM a -> (a -> LintM b) -> LintM b
335 thenL m k loc scope errs
336   = case m loc scope errs of
337       (r, errs') -> k r loc scope errs'
338
339 thenL_ :: LintM a -> LintM b -> LintM b
340 thenL_ m k loc scope errs
341   = case m loc scope errs of
342       (_, errs') -> k loc scope errs'
343
344 thenMaybeL :: LintM (Maybe a) -> (a -> LintM (Maybe b)) -> LintM (Maybe b)
345 thenMaybeL m k loc scope errs
346   = case m loc scope errs of
347       (Nothing, errs2) -> (Nothing, errs2)
348       (Just r,  errs2) -> k r loc scope errs2
349
350 mapL :: (a -> LintM b) -> [a] -> LintM [b]
351 mapL f [] = returnL []
352 mapL f (x:xs)
353   = f x         `thenL` \ r ->
354     mapL f xs   `thenL` \ rs ->
355     returnL (r:rs)
356
357 mapMaybeL :: (a -> LintM (Maybe b)) -> [a] -> LintM (Maybe [b])
358         -- Returns Nothing if anything fails
359 mapMaybeL f [] = returnL (Just [])
360 mapMaybeL f (x:xs)
361   = f x             `thenMaybeL` \ r ->
362     mapMaybeL f xs  `thenMaybeL` \ rs ->
363     returnL (Just (r:rs))
364 \end{code}
365
366 \begin{code}
367 checkL :: Bool -> Message -> LintM ()
368 checkL True  msg loc scope errs = ((), errs)
369 checkL False msg loc scope errs = ((), addErr errs msg loc)
370
371 addErrL :: Message -> LintM ()
372 addErrL msg loc scope errs = ((), addErr errs msg loc)
373
374 addErr :: Bag Message -> Message -> [LintLocInfo] -> Bag Message
375
376 addErr errs_so_far msg locs
377   = errs_so_far `snocBag` mk_msg locs
378   where
379     mk_msg (loc:_) = let (l,hdr) = dumpLoc loc 
380                      in  mkLocMessage l (hdr $$ msg)
381     mk_msg []      = msg
382
383 addLoc :: LintLocInfo -> LintM a -> LintM a
384 addLoc extra_loc m loc scope errs
385   = m (extra_loc:loc) scope errs
386
387 addInScopeVars :: [Id] -> LintM a -> LintM a
388 addInScopeVars ids m loc scope errs
389   = -- We check if these "new" ids are already
390     -- in scope, i.e., we have *shadowing* going on.
391     -- For now, it's just a "trace"; we may make
392     -- a real error out of it...
393     let
394         new_set = mkVarSet ids
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     (expected_arg_tys, res_ty) = splitFunTys (dropForAlls fun_ty)
420
421     cfa res_ty expected []      -- Args have run out; that's fine
422       = (Just (mkFunTys expected res_ty), errs)
423
424     cfa res_ty [] arg_tys       -- Expected arg tys ran out first;
425                                 -- first see if res_ty is a tyvar template;
426                                 -- otherwise, maybe res_ty is a
427                                 -- dictionary type which is actually a function?
428       | isTyVarTy res_ty
429       = (Just res_ty, errs)
430       | otherwise
431       = case splitFunTys res_ty of
432           ([], _)                 -> (Nothing, addErr errs msg loc)     -- Too many args
433           (new_expected, new_res) -> cfa new_res new_expected arg_tys
434
435     cfa res_ty (expected_arg_ty:expected_arg_tys) (arg_ty:arg_tys)
436       = cfa res_ty expected_arg_tys arg_tys
437 \end{code}
438
439 \begin{code}
440 checkInScope :: Id -> LintM ()
441 checkInScope id loc scope errs
442   = if isLocalId id && not (id `elemVarSet` scope) then
443         ((), addErr errs (hsep [ppr id, ptext SLIT("is out of scope")]) loc)
444     else
445         ((), errs)
446
447 checkTys :: Type -> Type -> Message -> LintM ()
448 checkTys ty1 ty2 msg loc scope errs
449   = -- if (ty1 == ty2) then
450     ((), errs)
451     -- else ((), addErr errs msg loc)
452 \end{code}
453
454 \begin{code}
455 mkCaseAltMsg :: [StgAlt] -> Message
456 mkCaseAltMsg alts
457   = ($$) (text "In some case alternatives, type of alternatives not all same:")
458             (empty) -- LATER: ppr alts
459
460 mkDefltMsg :: Id -> Message
461 mkDefltMsg bndr
462   = ($$) (ptext SLIT("Binder of a case expression doesn't match type of scrutinee:"))
463             (panic "mkDefltMsg")
464
465 mkFunAppMsg :: Type -> [Type] -> StgExpr -> Message
466 mkFunAppMsg fun_ty arg_tys expr
467   = vcat [text "In a function application, function type doesn't match arg types:",
468               hang (ptext SLIT("Function type:")) 4 (ppr fun_ty),
469               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys)),
470               hang (ptext SLIT("Expression:")) 4 (ppr expr)]
471
472 mkRhsConMsg :: Type -> [Type] -> Message
473 mkRhsConMsg fun_ty arg_tys
474   = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
475               hang (ptext SLIT("Constructor type:")) 4 (ppr fun_ty),
476               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys))]
477
478 mkAltMsg1 :: Type -> Message
479 mkAltMsg1 ty
480   = ($$) (text "In a case expression, type of scrutinee does not match patterns")
481          (ppr ty)
482
483 mkAlgAltMsg2 :: Type -> DataCon -> Message
484 mkAlgAltMsg2 ty con
485   = vcat [
486         text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
487         ppr ty,
488         ppr con
489     ]
490
491 mkAlgAltMsg3 :: DataCon -> [Id] -> Message
492 mkAlgAltMsg3 con alts
493   = vcat [
494         text "In some algebraic case alternative, number of arguments doesn't match constructor:",
495         ppr con,
496         ppr alts
497     ]
498
499 mkAlgAltMsg4 :: Type -> Id -> Message
500 mkAlgAltMsg4 ty arg
501   = vcat [
502         text "In some algebraic case alternative, type of argument doesn't match data constructor:",
503         ppr ty,
504         ppr arg
505     ]
506
507 mkCaseOfCaseMsg :: StgExpr -> Message
508 mkCaseOfCaseMsg e
509   = text "Case of non-tail-call:" $$ ppr e
510
511 mkRhsMsg :: Id -> Type -> Message
512 mkRhsMsg binder ty
513   = vcat [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
514                      ppr binder],
515               hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
516               hsep [ptext SLIT("Rhs type:"), ppr ty]
517              ]
518
519 mkUnLiftedTyMsg binder rhs
520   = (ptext SLIT("Let(rec) binder") <+> quotes (ppr binder) <+> 
521      ptext SLIT("has unlifted type") <+> quotes (ppr (idType binder)))
522     $$
523     (ptext SLIT("RHS:") <+> ppr rhs)
524 \end{code}