-
Notifications
You must be signed in to change notification settings - Fork 1
/
compile.go
96 lines (88 loc) · 1.93 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
package script
import (
"fmt"
"go/ast"
"go/parser"
)
// Compiles an expression, which can then be evaluated. E.g.:
// expr, err := world.CompileExpr("1+1")
// expr.Eval() // returns 2
func (w *World) CompileExpr(src string) (code Expr, e error) {
// parse
tree, err := parser.ParseExpr(src)
if err != nil {
return nil, fmt.Errorf(`parse "%s": %v`, src, err)
}
if Debug {
ast.Print(nil, tree)
}
// catch compile errors
if !Debug {
defer func() {
err := recover()
if err == nil {
return
}
if er, ok := err.(*compileErr); ok {
code = nil
e = fmt.Errorf(`parse "%s": %v`, src, er)
} else {
panic(err)
}
}()
}
return w.compile(tree), nil
}
// CompileExpr with panic on error.
func (w *World) MustCompileExpr(src string) Expr {
code, err := w.CompileExpr(src)
if err != nil {
panic(err)
}
return code
}
// compiles source consisting of a number of statements. E.g.:
// src = "a = 1; b = sin(x)"
// code, err := world.Compile(src)
// code.Eval()
func (w *World) Compile(src string) (code *BlockStmt, e error) {
// parse
exprSrc := "func(){\n" + src + "\n}" // wrap in func to turn into expression
tree, err := parser.ParseExpr(exprSrc)
if err != nil {
return nil, fmt.Errorf("script line %v: ", err)
}
// catch compile errors and decode line number
if !Debug {
defer func() {
err := recover()
if err == nil {
return
}
if compErr, ok := err.(*compileErr); ok {
code = nil
e = fmt.Errorf("script %v: %v", pos2line(compErr.pos, exprSrc), compErr.msg)
} else {
panic(err)
}
}()
}
// compile
stmts := tree.(*ast.FuncLit).Body.List // strip func again
if Debug {
ast.Print(nil, stmts)
}
block := new(BlockStmt)
for _, s := range stmts {
block.append(w.compile(s), s)
}
return block, nil
}
// Like Compile but panics on error
func (w *World) MustCompile(src string) Expr {
code, err := w.Compile(src)
if err != nil {
panic(err)
}
return code
}