-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreter.go
executable file
·67 lines (57 loc) · 1.5 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import "fmt"
import "github.com/skywalkerlee/gvm/instructions"
import "github.com/skywalkerlee/gvm/instructions/base"
import "github.com/skywalkerlee/gvm/rtda"
import "github.com/skywalkerlee/gvm/rtda/heap"
func interpret(method *heap.Method, logInst bool) {
thread := rtda.NewThread()
frame := thread.NewFrame(method)
thread.PushFrame(frame)
defer catchErr(thread)
loop(thread, logInst)
}
func catchErr(thread *rtda.Thread) {
if r := recover(); r != nil {
logFrames(thread)
panic(r)
}
}
func loop(thread *rtda.Thread, logInst bool) {
reader := &base.BytecodeReader{}
for {
frame := thread.CurrentFrame()
pc := frame.NextPC()
thread.SetPC(pc)
// decode
reader.Reset(frame.Method().Code(), pc)
opcode := reader.ReadUint8()
inst := instructions.NewInstruction(opcode)
inst.FetchOperands(reader)
frame.SetNextPC(reader.PC())
if logInst {
logInstruction(frame, inst)
}
// execute
inst.Execute(frame)
if thread.IsStackEmpty() {
break
}
}
}
func logInstruction(frame *rtda.Frame, inst base.Instruction) {
method := frame.Method()
className := method.Class().Name()
methodName := method.Name()
pc := frame.Thread().PC()
fmt.Printf("%v.%v() #%2d %T %v\n", className, methodName, pc, inst, inst)
}
func logFrames(thread *rtda.Thread) {
for !thread.IsStackEmpty() {
frame := thread.PopFrame()
method := frame.Method()
className := method.Class().Name()
fmt.Printf(">> pc:%4d %v.%v%v \n",
frame.NextPC(), className, method.Name(), method.Descriptor())
}
}