-
Notifications
You must be signed in to change notification settings - Fork 0
/
compile.go
99 lines (88 loc) · 1.95 KB
/
compile.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package py
import (
"fmt"
)
type (
Opcode struct {
Code string
Arg any
}
SSA struct {
Action string
Arg1, Arg2 any
}
Compiler struct {
Opcodes []*Opcode
Constants []any
index int
}
)
func (s *SSA) String() string {
return fmt.Sprintf("%s-%v-%v", s.Action, s.Arg1, s.Arg2)
}
func NewCompiler(opcodes []*Opcode, constants []any) *Compiler {
return &Compiler{
Opcodes: opcodes,
Constants: constants,
index: 0,
}
}
func (c *Compiler) fetch() *Opcode {
op := c.Opcodes[c.index]
c.index++
return op
}
func (c *Compiler) variable(n int) string {
order := []string{"rax", "rbx", "rcx", "rdi"}
return order[n]
}
func (c *Compiler) Compile() ([]*SSA, error) {
ir := make([]*SSA, 0)
pushSSA := func(a string, b, c any) {
ssa := &SSA{
Action: a,
Arg1: b,
Arg2: c,
}
ir = append(ir, ssa)
}
for c.index < len(c.Opcodes) {
op := c.fetch()
// rdi, rsi
switch op.Code {
case "LOAD_FAST":
pushSSA("push", c.variable(op.Arg.(int)), nil)
case "STORE_FAST":
pushSSA("pop", "rdi", nil)
pushSSA("move", c.variable(op.Arg.(int)), "rdi")
case "LOAD_CONST":
pushSSA("immediate", "rdi", c.Constants[op.Arg.(int)])
pushSSA("push", "rdi", nil)
case "BINARY_MULTIPLY":
pushSSA("pop", "rdi", nil)
pushSSA("pop", "rsi", nil)
pushSSA("imul", "rdi", "rsi")
pushSSA("push", "rdi", nil)
case "BINARY_ADD", "INPLACE_ADD":
pushSSA("pop", "rdi", nil)
pushSSA("pop", "rsi", nil)
pushSSA("add", "rdi", "rsi")
pushSSA("push", "rdi", nil)
case "BINARY_SUBTRACT", "INPLACE_SUBTRACT":
pushSSA("pop", "rsi", nil)
pushSSA("pop", "rdi", nil)
pushSSA("sub", "rdi", "rsi")
pushSSA("push", "rdi", nil)
case "UNARY_NEGATIVE":
pushSSA("pop", "rdi", nil)
pushSSA("neg", "rdi", nil)
pushSSA("push", "rdi", nil)
case "RETURN_VALUE":
pushSSA("pop", "rax", nil)
pushSSA("ret", nil, nil)
default:
return nil, fmt.Errorf("%s not support", op.Code)
}
}
return ir, nil
}