1
0
mirror of https://github.com/danog/liquid.git synced 2024-12-02 14:57:49 +01:00
liquid/expressions/evaluator.go

67 lines
1.3 KiB
Go
Raw Normal View History

2017-06-26 15:33:07 +02:00
package expressions
2017-06-27 23:29:50 +02:00
import (
"github.com/osteele/liquid/errors"
"github.com/osteele/liquid/generics"
)
2017-06-27 22:11:32 +02:00
// Expression is a parsed expression.
type Expression interface {
// Evaluate evaluates an expression in a context.
Evaluate(ctx Context) (interface{}, error)
}
// Closure binds an environment.
type Closure interface {
Bind(name string, value interface{}) Closure
Evaluate() (interface{}, error)
}
type closure struct {
expr Expression
context Context
}
func (c closure) Bind(name string, value interface{}) Closure {
// TODO create a new context
c.context.Set(name, value)
return c
}
func (c closure) Evaluate() (interface{}, error) {
return c.expr.Evaluate(c.context)
}
type expression struct {
evaluator func(Context) interface{}
}
2017-06-27 22:11:32 +02:00
func (e expression) Evaluate(ctx Context) (out interface{}, err error) {
defer func() {
if r := recover(); r != nil {
switch e := r.(type) {
2017-06-27 23:29:50 +02:00
case generics.GenericError:
err = e
2017-06-27 22:53:34 +02:00
case InterpreterError:
err = e
2017-06-27 22:11:32 +02:00
case UnimplementedError:
err = e
case errors.UndefinedFilter:
err = e
default:
panic(r)
}
}
}()
return e.evaluator(ctx), nil
2017-06-26 15:06:55 +02:00
}
// EvaluateExpr is a wrapper for Parse and Evaluate.
func EvaluateExpr(source string, ctx Context) (interface{}, error) {
expr, err := Parse(source)
if err != nil {
return nil, err
2017-06-26 15:06:55 +02:00
}
return expr.Evaluate(ctx)
2017-06-26 15:06:55 +02:00
}