forked from davyxu/tabtoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.go
75 lines (60 loc) · 1.21 KB
/
compiler.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
package exprvm
import (
"go/ast"
"go/parser"
"go/token"
"strconv"
)
func Compile(src string) (*Chunk, error) {
node, err := parser.ParseExpr(src)
if err != nil {
return nil, err
}
ast.Print(nil, node)
ck := newChunk()
if err := walkTree(ck, node); err != nil {
return nil, err
}
return ck, nil
}
func walkTree(ck *Chunk, node ast.Node) (err error) {
switch thisNode := node.(type) {
case *ast.BinaryExpr:
if err = walkTree(ck, thisNode.X); err != nil {
return
}
if err = walkTree(ck, thisNode.Y); err != nil {
return
}
switch thisNode.Op {
case token.ADD:
ck.AddCode(Opcode_Add)
case token.SUB:
ck.AddCode(Opcode_Sub)
case token.MUL:
ck.AddCode(Opcode_Mul)
case token.QUO:
ck.AddCode(Opcode_Div)
}
case *ast.BasicLit: // 字面量/常数
switch thisNode.Kind {
case token.INT:
v, err := strconv.Atoi(thisNode.Value)
if err != nil {
return err
}
ck.AddCodeOperand(Opcode_Push, v)
default:
return ErrUnknownOperandType
}
case *ast.ParenExpr:
return walkTree(ck, thisNode.X)
case *ast.UnaryExpr:
walkTree(ck, thisNode.X)
ck.AddCode(Opcode_Minus)
case *ast.Ident: // 变量/常量
default:
return ErrUnknownExpression
}
return nil
}