-
Notifications
You must be signed in to change notification settings - Fork 2
/
spiker.go
73 lines (56 loc) · 1.3 KB
/
spiker.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
package spiker
import "strings"
// Execute return the computed result of a string expression
func Execute(code string) (val interface{}, err error) {
code = padSemicolon(code)
lexer := NewLexer(code)
p := Parser{Lexer: lexer}
stmts, err := p.Statements()
if err != nil {
return
}
ast, err := Transform(stmts)
if err != nil {
return
}
return Evaluator(ast)
}
// ExecuteWithScope return the execute result with scope
func ExecuteWithScope(code string, scope *VariableScope) (val interface{}, err error) {
code = padSemicolon(code)
lexer := NewLexer(code)
p := Parser{Lexer: lexer}
stmts, err := p.Statements()
if err != nil {
return
}
ast, err := Transform(stmts)
if err != nil {
return
}
return EvaluateWithScope(ast, scope)
}
// Format return the formatted expression
func Format(code string) (s string, err error) {
code = padSemicolon(code)
lexer := NewLexer(code)
p := Parser{Lexer: lexer}
stmts, err := p.Statements()
if err != nil {
return
}
ast, err := Transform(stmts)
if err != nil {
return
}
return FormatAst(ast)
}
// padding semicolon
func padSemicolon(code string) string {
code = strings.TrimSpace(code)
last := code[len(code)-1:]
if last != SymbolSemicolon.String() && last != SymbolRbrace.String() {
code += SymbolSemicolon.String()
}
return code
}