Add Generator shortcuts for some JVM instructions.
[hs-java.git] / TestGen.hs
1 {-# LANGUAGE OverloadedStrings #-}
2
3 import qualified Data.ByteString.Lazy as B
4
5 import JVM.Types
6 import JVM.ClassFile
7 import JVM.Converter
8 import JVM.Assembler
9 import JVM.Generator
10 import JVM.Generator.Instructions
11
12 initNT :: NameType Method
13 initNT = NameType "<init>" $ MethodSignature [] ReturnsVoid
14
15 helloNT :: NameType Method
16 helloNT = NameType "hello" $ MethodSignature [IntType] ReturnsVoid
17
18 printlnNT :: NameType Method
19 printlnNT = NameType "println" $ MethodSignature [ObjectType "java/lang/String"] ReturnsVoid
20
21 outNT :: NameType Field
22 outNT = NameType "out" $ ObjectType "java/io/PrintStream"
23
24 valueOfNT :: NameType Method
25 valueOfNT = NameType "valueOf" $ MethodSignature [IntType] (Returns $ ObjectType "java/lang/Integer")
26
27 printfNT :: NameType Method
28 printfNT = NameType "printf" $ MethodSignature [ObjectType "java/lang/String",
29                                                 Array Nothing $ ObjectType "java/lang/Object"] (Returns $ ObjectType "java/io/PrintStream")
30
31 test :: Generate ()
32 test = do
33   newMethod [ACC_PUBLIC] "<init>" [] ReturnsVoid $ do
34       aload_ I0
35       invokeSpecial "java/lang/Object" initNT
36       i0 RETURN
37
38   newMethod [ACC_PUBLIC, ACC_STATIC] "main" [Array Nothing $ ObjectType "java/lang/String"] ReturnsVoid $ do
39       iconst_5
40       invokeStatic "Test" helloNT
41       i0 RETURN
42
43   newMethod [ACC_PUBLIC, ACC_STATIC] "hello" [IntType] ReturnsVoid $ do
44       getStaticField "java/lang/System" outNT
45       loadString "Здравствуй, мир!"
46       invokeVirtual "java/io/PrintStream" printlnNT
47       getStaticField "java/lang/System" outNT
48       loadString "Argument: %d\n"
49       iconst_1
50       allocArray "java/lang/Object"
51       dup
52       iconst_0
53       iload_ I0
54       invokeStatic "java/lang/Integer" valueOfNT
55       aastore
56       invokeVirtual "java/io/PrintStream" printfNT
57       pop
58       i0 RETURN
59
60 testClass = generate "Test" test
61
62 main = do
63   B.writeFile "Test.class" (encodeClass testClass)
64