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