forked from hashicorp/go-bexpr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbexpr.go
64 lines (53 loc) · 2.03 KB
/
bexpr.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
// bexpr is an implementation of a generic boolean expression evaluator.
// The general goal is to be able to evaluate some expression against some
// arbitrary data and get back a boolean of whether or not the data
// was matched by the expression
package bexpr
//go:generate pigeon -o grammar/grammar.go -optimize-parser grammar/grammar.peg
//go:generate goimports -w grammar/grammar.go
import (
"github.com/hashicorp/go-bexpr/grammar"
"github.com/mitchellh/pointerstructure"
)
// HookFn provides a way to translate one reflect.Value to another during
// evaluation by bexpr. This facilitates making Go structures appear in a way
// that matches the expected JSON Pointers used for evaluation. This is
// helpful, for example, when working with protocol buffers' well-known types.
type ValueTransformationHookFn = pointerstructure.ValueTransformationHookFn
type Evaluator struct {
// The syntax tree
ast grammar.Expression
tagName string
valueTransformationHook ValueTransformationHookFn
unknownVal *interface{}
}
func CreateEvaluator(expression string, opts ...Option) (*Evaluator, error) {
parsedOpts := getOpts(opts...)
var parserOpts []grammar.Option
if parsedOpts.withMaxExpressions != 0 {
parserOpts = append(parserOpts, grammar.MaxExpressions(parsedOpts.withMaxExpressions))
}
ast, err := grammar.Parse("", []byte(expression), parserOpts...)
if err != nil {
return nil, err
}
eval := &Evaluator{
ast: ast.(grammar.Expression),
tagName: parsedOpts.withTagName,
valueTransformationHook: parsedOpts.withHookFn,
unknownVal: parsedOpts.withUnknown,
}
return eval, nil
}
func (eval *Evaluator) Evaluate(datum interface{}) (bool, error) {
opts := []Option{
WithTagName(eval.tagName),
WithHookFn(eval.valueTransformationHook),
}
if eval.unknownVal != nil {
opts = append(opts, WithUnknownValue(*eval.unknownVal))
}
return evaluate(eval.ast, datum, opts...)
}