-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.go
48 lines (43 loc) · 1.12 KB
/
interpreter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"fmt"
"github.com/jvm-in-go/classfile"
"github.com/jvm-in-go/instructions"
"github.com/jvm-in-go/instructions/base"
"github.com/jvm-in-go/rtda"
)
func interpret(methodInfo *classfile.MemberInfo) {
codeAttr := methodInfo.CodeAttribute()
maxLocals := codeAttr.MaxLocals()
maxStack := codeAttr.MaxStack()
bytecode := codeAttr.Code()
thread := rtda.NewThread()
frame := thread.NewFrame(uint(maxLocals), uint(maxStack))
thread.PushFrame(frame)
defer catchErr(frame)
loop(thread, bytecode)
}
func catchErr(frame *rtda.Frame) {
if r := recover(); r != nil {
fmt.Printf("LocalVars: %v\n", frame.LocalVars())
fmt.Printf("OperandStack: %v\n", frame.OperandStack())
panic(r)
}
}
func loop(thread *rtda.Thread, bytecode []byte) {
frame := thread.PopFrame()
reader := &base.BytecodeReader{}
for {
pc := frame.NextPC()
thread.SetPC(pc)
//decode
reader.Reset(bytecode, pc)
opcode := reader.ReadUint8()
inst := instructions.NewInstruction(opcode)
inst.FetchOperands(reader)
frame.SetNextPC(reader.PC())
//execute
fmt.Printf("pc:%2d inst: %T %v\n, pc, inst, inst")
inst.Execute(frame)
}
}