d844e9d2d05500c1acf59e06b84c849ac1f7ea88
[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, dataConType )
17 import Const            ( literalType, conType, Literal )
18 import Maybes           ( catMaybes )
19 import Name             ( isLocallyDefined, getSrcLoc )
20 import ErrUtils         ( ErrMsg, Message, addErrLocHdrLine, pprBagOfErrors, dontAddErrLoc )
21 import Type             ( mkFunTys, splitFunTys, splitAlgTyConApp_maybe, 
22                           isUnLiftedType, isTyVarTy, Type
23                         )
24 import TyCon            ( TyCon, isDataTyCon )
25 import Util             ( zipEqual )
26 import Outputable
27
28 infixr 9 `thenL`, `thenL_`, `thenMaybeL`, `thenMaybeL_`
29 \end{code}
30
31 Checks for
32         (a) *some* type errors
33         (b) locally-defined variables used but not defined
34
35 %************************************************************************
36 %*                                                                      *
37 \subsection{``lint'' for various constructs}
38 %*                                                                      *
39 %************************************************************************
40
41 @lintStgBindings@ is the top-level interface function.
42
43 \begin{code}
44 lintStgBindings :: String -> [StgBinding] -> [StgBinding]
45
46 lintStgBindings whodunnit binds
47   = _scc_ "StgLint"
48     case (initL (lint_binds binds)) of
49       Nothing  -> binds
50       Just msg -> pprPanic "" (vcat [
51                         ptext SLIT("*** Stg Lint ErrMsgs: in") <+> text whodunnit <+> ptext SLIT("***"),
52                         msg,
53                         ptext SLIT("*** Offending Program ***"),
54                         pprStgBindings binds,
55                         ptext SLIT("*** End of Offense ***")])
56   where
57     lint_binds :: [StgBinding] -> LintM ()
58
59     lint_binds [] = returnL ()
60     lint_binds (bind:binds)
61       = lintStgBinds bind               `thenL` \ binders ->
62         addInScopeVars binders (
63             lint_binds binds
64         )
65 \end{code}
66
67
68 \begin{code}
69 lintStgArg :: StgArg -> LintM (Maybe Type)
70 lintStgArg (StgConArg con) = returnL (Just (conType con))
71 lintStgArg (StgVarArg v)   = lintStgVar v
72
73 lintStgVar v  = checkInScope v  `thenL_`
74                 returnL (Just (idType v))
75 \end{code}
76
77 \begin{code}
78 lintStgBinds :: StgBinding -> LintM [Id]                -- Returns the binders
79 lintStgBinds (StgNonRec binder rhs)
80   = lint_binds_help (binder,rhs)        `thenL_`
81     returnL [binder]
82
83 lintStgBinds (StgRec pairs)
84   = addInScopeVars binders (
85         mapL lint_binds_help pairs `thenL_`
86         returnL binders
87     )
88   where
89     binders = [b | (b,_) <- pairs]
90
91 lint_binds_help (binder, rhs)
92   = addLoc (RhsOf binder) (
93         -- Check the rhs
94         lintStgRhs rhs    `thenL` \ maybe_rhs_ty ->
95
96         -- Check binder doesn't have unlifted type
97         checkL (not (isUnLiftedType binder_ty))
98                (mkUnLiftedTyMsg binder rhs)             `thenL_`
99
100         -- Check match to RHS type
101         (case maybe_rhs_ty of
102           Nothing     -> returnL ()
103           Just rhs_ty -> checkTys  binder_ty
104                                    rhs_ty
105                                    (mkRhsMsg binder rhs_ty)
106         )                       `thenL_`
107
108         returnL ()
109     )
110   where
111     binder_ty = idType binder
112 \end{code}
113
114 \begin{code}
115 lintStgRhs :: StgRhs -> LintM (Maybe Type)
116
117 lintStgRhs (StgRhsClosure _ _ _ _ _ binders expr)
118   = addLoc (LambdaBodyOf binders) (
119     addInScopeVars binders (
120         lintStgExpr expr   `thenMaybeL` \ body_ty ->
121         returnL (Just (mkFunTys (map idType binders) body_ty))
122     ))
123
124 lintStgRhs (StgRhsCon _ con args)
125   = mapMaybeL lintStgArg args   `thenL` \ maybe_arg_tys ->
126     case maybe_arg_tys of
127       Nothing       -> returnL Nothing
128       Just arg_tys  -> checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys)
129   where
130     con_ty = dataConType con
131 \end{code}
132
133 \begin{code}
134 lintStgExpr :: StgExpr -> LintM (Maybe Type)    -- Nothing if error found
135
136 lintStgExpr e@(StgApp fun args)
137   = lintStgVar fun              `thenMaybeL` \ fun_ty  ->
138     mapMaybeL lintStgArg args   `thenL`      \ maybe_arg_tys ->
139     case maybe_arg_tys of
140       Nothing       -> returnL Nothing
141       Just arg_tys  -> checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e)
142
143 lintStgExpr e@(StgCon con args _)
144   = mapMaybeL lintStgArg args   `thenL` \ maybe_arg_tys ->
145     case maybe_arg_tys of
146       Nothing       -> returnL Nothing
147       Just arg_tys  -> checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e)
148   where
149     con_ty = conType con
150
151 lintStgExpr (StgLam _ bndrs _)
152   = addErrL (ptext SLIT("Unexpected StgLam") <+> ppr bndrs)     `thenL_`
153     returnL Nothing
154
155 lintStgExpr (StgLet binds body)
156   = lintStgBinds binds          `thenL` \ binders ->
157     addLoc (BodyOfLetRec binders) (
158     addInScopeVars binders (
159         lintStgExpr body
160     ))
161
162 lintStgExpr (StgLetNoEscape _ _ binds body)
163   = lintStgBinds binds          `thenL` \ binders ->
164     addLoc (BodyOfLetRec binders) (
165     addInScopeVars binders (
166         lintStgExpr body
167     ))
168
169 lintStgExpr (StgSCC _ expr)     = lintStgExpr expr
170
171 lintStgExpr e@(StgCase scrut _ _ bndr _ alts)
172   = lintStgExpr scrut           `thenMaybeL` \ _ ->
173     checkTys (idType bndr) scrut_ty (mkDefltMsg bndr) `thenL_`
174
175         -- Check that it is a data type
176     case (splitAlgTyConApp_maybe scrut_ty) of
177       Just (tycon, _, _) | isDataTyCon tycon
178               -> addInScopeVars [bndr] (lintStgAlts alts scrut_ty tycon)
179       other   -> addErrL (mkCaseDataConMsg e)   `thenL_`
180                  returnL Nothing
181   where
182     scrut_ty = get_ty alts
183
184     get_ty (StgAlgAlts  ty _ _) = ty
185     get_ty (StgPrimAlts ty _ _) = ty
186 \end{code}
187
188 \begin{code}
189 lintStgAlts :: StgCaseAlts
190              -> Type            -- Type of scrutinee
191              -> TyCon                   -- TyCon pinned on the case
192              -> LintM (Maybe Type)      -- Type of alternatives
193
194 lintStgAlts alts scrut_ty case_tycon
195   = (case alts of
196          StgAlgAlts _ alg_alts deflt ->
197            mapL (lintAlgAlt scrut_ty) alg_alts  `thenL` \ maybe_alt_tys ->
198            lintDeflt deflt scrut_ty             `thenL` \ maybe_deflt_ty ->
199            returnL (maybe_deflt_ty : maybe_alt_tys)
200
201          StgPrimAlts _ prim_alts deflt ->
202            mapL (lintPrimAlt scrut_ty) prim_alts `thenL` \ maybe_alt_tys ->
203            lintDeflt deflt scrut_ty              `thenL` \ maybe_deflt_ty ->
204            returnL (maybe_deflt_ty : maybe_alt_tys)
205     )                                            `thenL` \ maybe_result_tys ->
206          -- Check the result types
207     case catMaybes (maybe_result_tys) of
208       []             -> returnL Nothing
209
210       (first_ty:tys) -> mapL check tys  `thenL_`
211                         returnL (Just first_ty)
212         where
213           check ty = checkTys first_ty ty (mkCaseAltMsg alts)
214
215 lintAlgAlt scrut_ty (con, args, _, rhs)
216   = (case splitAlgTyConApp_maybe scrut_ty of
217       Nothing ->
218          addErrL (mkAlgAltMsg1 scrut_ty)
219       Just (tycon, tys_applied, cons) ->
220          let
221            arg_tys = dataConArgTys con tys_applied
222          in
223          checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con) `thenL_`
224          checkL (length arg_tys == length args) (mkAlgAltMsg3 con args)
225                                                                  `thenL_`
226          mapL check (zipEqual "lintAlgAlt:stg" arg_tys args)     `thenL_`
227          returnL ()
228     )                                                            `thenL_`
229     addInScopeVars args         (
230          lintStgExpr rhs
231     )
232   where
233     check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
234
235     -- elem: yes, the elem-list here can sometimes be long-ish,
236     -- but as it's use-once, probably not worth doing anything different
237     -- We give it its own copy, so it isn't overloaded.
238     elem _ []       = False
239     elem x (y:ys)   = x==y || elem x ys
240
241 lintPrimAlt scrut_ty alt@(lit,rhs)
242  = checkTys (literalType lit) scrut_ty (mkPrimAltMsg alt)       `thenL_`
243    lintStgExpr rhs
244
245 lintDeflt StgNoDefault scrut_ty = returnL Nothing
246 lintDeflt deflt@(StgBindDefault rhs) scrut_ty = lintStgExpr rhs
247 \end{code}
248
249
250 %************************************************************************
251 %*                                                                      *
252 \subsection[lint-monad]{The Lint monad}
253 %*                                                                      *
254 %************************************************************************
255
256 \begin{code}
257 type LintM a = [LintLocInfo]    -- Locations
258             -> IdSet            -- Local vars in scope
259             -> Bag ErrMsg       -- Error messages so far
260             -> (a, Bag ErrMsg)  -- Result and error messages (if any)
261
262 data LintLocInfo
263   = RhsOf Id            -- The variable bound
264   | LambdaBodyOf [Id]   -- The lambda-binder
265   | BodyOfLetRec [Id]   -- One of the binders
266
267 dumpLoc (RhsOf v) =
268   (getSrcLoc v, ptext SLIT(" [RHS of ") <> pp_binders [v] <> char ']' )
269 dumpLoc (LambdaBodyOf bs) =
270   (getSrcLoc (head bs), ptext SLIT(" [in body of lambda with binders ") <> pp_binders bs <> char ']' )
271
272 dumpLoc (BodyOfLetRec bs) =
273   (getSrcLoc (head bs), ptext SLIT(" [in body of letrec with binders ") <> pp_binders bs <> char ']' )
274
275
276 pp_binders :: [Id] -> SDoc
277 pp_binders bs
278   = sep (punctuate comma (map pp_binder bs))
279   where
280     pp_binder b
281       = hsep [ppr b, dcolon, ppr (idType b)]
282 \end{code}
283
284 \begin{code}
285 initL :: LintM a -> Maybe Message
286 initL m
287   = case (m [] emptyVarSet emptyBag) of { (_, errs) ->
288     if isEmptyBag errs then
289         Nothing
290     else
291         Just (pprBagOfErrors errs)
292     }
293
294 returnL :: a -> LintM a
295 returnL r loc scope errs = (r, errs)
296
297 thenL :: LintM a -> (a -> LintM b) -> LintM b
298 thenL m k loc scope errs
299   = case m loc scope errs of
300       (r, errs') -> k r loc scope errs'
301
302 thenL_ :: LintM a -> LintM b -> LintM b
303 thenL_ m k loc scope errs
304   = case m loc scope errs of
305       (_, errs') -> k loc scope errs'
306
307 thenMaybeL :: LintM (Maybe a) -> (a -> LintM (Maybe b)) -> LintM (Maybe b)
308 thenMaybeL m k loc scope errs
309   = case m loc scope errs of
310       (Nothing, errs2) -> (Nothing, errs2)
311       (Just r,  errs2) -> k r loc scope errs2
312
313 thenMaybeL_ :: LintM (Maybe a) -> LintM (Maybe b) -> LintM (Maybe b)
314 thenMaybeL_ m k loc scope errs
315   = case m loc scope errs of
316       (Nothing, errs2) -> (Nothing, errs2)
317       (Just _,  errs2) -> k loc scope errs2
318
319 mapL :: (a -> LintM b) -> [a] -> LintM [b]
320 mapL f [] = returnL []
321 mapL f (x:xs)
322   = f x         `thenL` \ r ->
323     mapL f xs   `thenL` \ rs ->
324     returnL (r:rs)
325
326 mapMaybeL :: (a -> LintM (Maybe b)) -> [a] -> LintM (Maybe [b])
327         -- Returns Nothing if anything fails
328 mapMaybeL f [] = returnL (Just [])
329 mapMaybeL f (x:xs)
330   = f x             `thenMaybeL` \ r ->
331     mapMaybeL f xs  `thenMaybeL` \ rs ->
332     returnL (Just (r:rs))
333 \end{code}
334
335 \begin{code}
336 checkL :: Bool -> Message -> LintM ()
337 checkL True  msg loc scope errs = ((), errs)
338 checkL False msg loc scope errs = ((), addErr errs msg loc)
339
340 addErrL :: Message -> LintM ()
341 addErrL msg loc scope errs = ((), addErr errs msg loc)
342
343 addErr :: Bag ErrMsg -> Message -> [LintLocInfo] -> Bag ErrMsg
344
345 addErr errs_so_far msg locs
346   = errs_so_far `snocBag` mk_msg locs
347   where
348     mk_msg (loc:_) = let (l,hdr) = dumpLoc loc in addErrLocHdrLine l hdr msg
349     mk_msg []      = dontAddErrLoc "" msg
350
351 addLoc :: LintLocInfo -> LintM a -> LintM a
352 addLoc extra_loc m loc scope errs
353   = m (extra_loc:loc) scope errs
354
355 addInScopeVars :: [Id] -> LintM a -> LintM a
356 addInScopeVars ids m loc scope errs
357   = -- We check if these "new" ids are already
358     -- in scope, i.e., we have *shadowing* going on.
359     -- For now, it's just a "trace"; we may make
360     -- a real error out of it...
361     let
362         new_set = mkVarSet ids
363
364         shadowed = scope `intersectVarSet` new_set
365     in
366 --  After adding -fliberate-case, Simon decided he likes shadowed
367 --  names after all.  WDP 94/07
368 --  (if isEmptyVarSet shadowed
369 --  then id
370 --  else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $
371     m loc (scope `unionVarSet` new_set) errs
372 \end{code}
373
374 \begin{code}
375 checkFunApp :: Type                 -- The function type
376             -> [Type]               -- The arg type(s)
377             -> Message              -- Error messgae
378             -> LintM (Maybe Type)   -- The result type
379
380 checkFunApp fun_ty arg_tys msg loc scope errs
381   = cfa res_ty expected_arg_tys arg_tys
382   where
383     (expected_arg_tys, res_ty) = splitFunTys fun_ty
384
385     cfa res_ty expected []      -- Args have run out; that's fine
386       = (Just (mkFunTys expected res_ty), errs)
387
388     cfa res_ty [] arg_tys       -- Expected arg tys ran out first;
389                                 -- first see if res_ty is a tyvar template;
390                                 -- otherwise, maybe res_ty is a
391                                 -- dictionary type which is actually a function?
392       | isTyVarTy res_ty
393       = (Just res_ty, errs)
394       | otherwise
395       = case splitFunTys res_ty of
396           ([], _)                 -> (Nothing, addErr errs msg loc)     -- Too many args
397           (new_expected, new_res) -> cfa new_res new_expected arg_tys
398
399     cfa res_ty (expected_arg_ty:expected_arg_tys) (arg_ty:arg_tys)
400       = if (expected_arg_ty == arg_ty)
401         then cfa res_ty expected_arg_tys arg_tys
402         else (Nothing, addErr errs msg loc) -- Arg mis-match
403 \end{code}
404
405 \begin{code}
406 checkInScope :: Id -> LintM ()
407 checkInScope id loc scope errs
408   = if isLocallyDefined id && not (id `elemVarSet` scope) then
409         ((), addErr errs (hsep [ppr id, ptext SLIT("is out of scope")]) loc)
410     else
411         ((), errs)
412
413 checkTys :: Type -> Type -> Message -> LintM ()
414 checkTys ty1 ty2 msg loc scope errs
415   = if (ty1 == ty2)
416     then ((), errs)
417     else ((), addErr errs msg loc)
418 \end{code}
419
420 \begin{code}
421 mkCaseAltMsg :: StgCaseAlts -> Message
422 mkCaseAltMsg alts
423   = ($$) (text "In some case alternatives, type of alternatives not all same:")
424             -- LATER: (ppr alts)
425             (panic "mkCaseAltMsg")
426
427 mkCaseDataConMsg :: StgExpr -> Message
428 mkCaseDataConMsg expr
429   = ($$) (ptext SLIT("A case scrutinee not a type-constructor type:"))
430             (ppr expr)
431
432 mkCaseAbstractMsg :: TyCon -> Message
433 mkCaseAbstractMsg tycon
434   = ($$) (ptext SLIT("An algebraic case on an abstract type:"))
435             (ppr tycon)
436
437 mkDefltMsg :: Id -> Message
438 mkDefltMsg bndr
439   = ($$) (ptext SLIT("Binder of a case expression doesn't match type of scrutinee:"))
440             (panic "mkDefltMsg")
441
442 mkFunAppMsg :: Type -> [Type] -> StgExpr -> Message
443 mkFunAppMsg fun_ty arg_tys expr
444   = vcat [text "In a function application, function type doesn't match arg types:",
445               hang (ptext SLIT("Function type:")) 4 (ppr fun_ty),
446               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys)),
447               hang (ptext SLIT("Expression:")) 4 (ppr expr)]
448
449 mkRhsConMsg :: Type -> [Type] -> Message
450 mkRhsConMsg fun_ty arg_tys
451   = vcat [text "In a RHS constructor application, con type doesn't match arg types:",
452               hang (ptext SLIT("Constructor type:")) 4 (ppr fun_ty),
453               hang (ptext SLIT("Arg types:")) 4 (vcat (map (ppr) arg_tys))]
454
455 mkUnappTyMsg :: Id -> Type -> Message
456 mkUnappTyMsg var ty
457   = vcat [text "Variable has a for-all type, but isn't applied to any types.",
458               (<>) (ptext SLIT("Var:      ")) (ppr var),
459               (<>) (ptext SLIT("Its type: ")) (ppr ty)]
460
461 mkAlgAltMsg1 :: Type -> Message
462 mkAlgAltMsg1 ty
463   = ($$) (text "In some case statement, type of scrutinee is not a data type:")
464             (ppr ty)
465
466 mkAlgAltMsg2 :: Type -> DataCon -> Message
467 mkAlgAltMsg2 ty con
468   = vcat [
469         text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
470         ppr ty,
471         ppr con
472     ]
473
474 mkAlgAltMsg3 :: DataCon -> [Id] -> Message
475 mkAlgAltMsg3 con alts
476   = vcat [
477         text "In some algebraic case alternative, number of arguments doesn't match constructor:",
478         ppr con,
479         ppr alts
480     ]
481
482 mkAlgAltMsg4 :: Type -> Id -> Message
483 mkAlgAltMsg4 ty arg
484   = vcat [
485         text "In some algebraic case alternative, type of argument doesn't match data constructor:",
486         ppr ty,
487         ppr arg
488     ]
489
490 mkPrimAltMsg :: (Literal, StgExpr) -> Message
491 mkPrimAltMsg alt
492   = text "In a primitive case alternative, type of literal doesn't match type of scrutinee:"
493     $$ ppr alt
494
495 mkRhsMsg :: Id -> Type -> Message
496 mkRhsMsg binder ty
497   = vcat [hsep [ptext SLIT("The type of this binder doesn't match the type of its RHS:"),
498                      ppr binder],
499               hsep [ptext SLIT("Binder's type:"), ppr (idType binder)],
500               hsep [ptext SLIT("Rhs type:"), ppr ty]
501              ]
502
503 mkUnLiftedTyMsg binder rhs
504   = (ptext SLIT("Let(rec) binder") <+> quotes (ppr binder) <+> 
505      ptext SLIT("has unlifted type") <+> quotes (ppr (idType binder)))
506     $$
507     (ptext SLIT("RHS:") <+> ppr rhs)
508 \end{code}