-
Notifications
You must be signed in to change notification settings - Fork 59
/
parser.go
65 lines (56 loc) · 1.34 KB
/
parser.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
//go:generate ragel -Z scanner.rl
//go:generate gofmt -w scanner.go
//go:generate goyacc expressions.y
package expressions
import (
"fmt"
"github.com/osteele/liquid/values"
)
type parseValue struct {
Assignment
Cycle
Loop
When
val func(Context) values.Value
}
// SyntaxError represents a syntax error. The yacc-generated compiler
// doesn't use error returns; this lets us recognize them.
type SyntaxError string
func (e SyntaxError) Error() string { return string(e) }
// Parse parses an expression string into an Expression.
func Parse(source string) (expr Expression, err error) {
p, err := parse(source)
if err != nil {
return nil, err
}
return &expression{p.val}, nil
}
func parse(source string) (p *parseValue, err error) {
defer func() {
if r := recover(); r != nil {
switch e := r.(type) {
case SyntaxError:
err = e
case UndefinedFilter:
err = e
default:
panic(r)
}
}
}()
// FIXME hack to recognize EOF
lex := newLexer([]byte(source + ";"))
n := yyParse(lex)
if n != 0 {
return nil, SyntaxError(fmt.Errorf("syntax error in %q", source).Error())
}
return &lex.parseValue, nil
}
// EvaluateString is a wrapper for Parse and Evaluate.
func EvaluateString(source string, ctx Context) (interface{}, error) {
expr, err := Parse(source)
if err != nil {
return nil, err
}
return expr.Evaluate(ctx)
}