Better error handling.
[hs-java.git] / JVM / Exceptions.hs
1 {-# LANGUAGE DeriveDataTypeable, ExistentialQuantification #-}
2 module JVM.Exceptions where
3
4 import Control.Monad.Exception
5 import qualified Data.ByteString.Lazy as B
6
7 import JVM.ClassFile
8
9 data NoItemInPool = forall a. Show a => NoItemInPool a
10   deriving (Typeable)
11
12 instance Exception NoItemInPool
13
14 instance Show NoItemInPool where
15   show (NoItemInPool s) = "Internal error: no such item in pool: <" ++ show s ++ ">"
16
17 data UnexpectedEndMethod = UnexpectedEndMethod
18   deriving (Typeable)
19
20 instance Show UnexpectedEndMethod where
21   show UnexpectedEndMethod = "endMethod without startMethod!"
22
23 instance Exception UnexpectedEndMethod
24
25 data ENotLoaded = ClassFileNotLoaded FilePath
26                 | JARNotLoaded FilePath String
27   deriving (Typeable)
28
29 instance Show ENotLoaded where
30   show (ClassFileNotLoaded p) = "Class file was not loaded: " ++ p
31   show (JARNotLoaded p c) = "Class was not loaded from JAR: " ++ p ++ ": " ++ c
32
33 instance Exception ENotLoaded
34
35 data ENotFound = ClassNotFound String
36                | FieldNotFound String B.ByteString
37                | MethodNotFound String B.ByteString
38   deriving (Typeable)
39
40 instance Show ENotFound where
41   show (ClassNotFound p) = "No such class in ClassPath: " ++ p
42   show (FieldNotFound c f) = "No such field in class " ++ c ++ ": " ++ toString f
43   show (MethodNotFound c m) = "No such method in class " ++ c ++ ": " ++ toString m
44
45 instance Exception ENotFound
46
47 force :: String -> EM AnyException a -> a
48 force s x =
49   case tryEM x of
50     Right result -> result
51     Left  exc    -> error $ "Exception at " ++ s ++ ": " ++ show exc