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