11// Copyright (c) HashiCorp, Inc.
22// SPDX-License-Identifier: MPL-2.0
33
4- // bexpr is an implementation of a generic boolean expression evaluator.
4+ // Package bexpr is an implementation of a generic boolean expression evaluator.
55// The general goal is to be able to evaluate some expression against some
6- // arbitrary data and get back a boolean of whether or not the data
7- // was matched by the expression
6+ // arbitrary data and get back a boolean indicating if the data was matched by
7+ // the expression
88package bexpr
99
1010//go:generate pigeon -o grammar/grammar.go -optimize-parser grammar/grammar.peg
@@ -15,7 +15,7 @@ import (
1515 "github.com/mitchellh/pointerstructure"
1616)
1717
18- // HookFn provides a way to translate one reflect.Value to another during
18+ // ValueTransformationHookFn provides a way to translate one reflect.Value to another during
1919// evaluation by bexpr. This facilitates making Go structures appear in a way
2020// that matches the expected JSON Pointers used for evaluation. This is
2121// helpful, for example, when working with protocol buffers' well-known types.
@@ -27,8 +27,13 @@ type Evaluator struct {
2727 tagName string
2828 valueTransformationHook ValueTransformationHookFn
2929 unknownVal * interface {}
30+ expression string
3031}
3132
33+ // CreateEvaluator is used to create and configure a new Evaluator, the expression
34+ // will be used by the evaluator when evaluating against any supplied datum.
35+ // The following Option types are supported:
36+ // WithHookFn, WithMaxExpressions, WithTagName, WithUnknownValue.
3237func CreateEvaluator (expression string , opts ... Option ) (* Evaluator , error ) {
3338 parsedOpts := getOpts (opts ... )
3439 var parserOpts []grammar.Option
@@ -46,11 +51,15 @@ func CreateEvaluator(expression string, opts ...Option) (*Evaluator, error) {
4651 tagName : parsedOpts .withTagName ,
4752 valueTransformationHook : parsedOpts .withHookFn ,
4853 unknownVal : parsedOpts .withUnknown ,
54+ expression : expression ,
4955 }
5056
5157 return eval , nil
5258}
5359
60+ // Evaluate attempts to match the configured expression against the supplied datum.
61+ // It returns a value indicating if a match was found and any error that occurred.
62+ // If an error is returned, the value indicating a match will be false.
5463func (eval * Evaluator ) Evaluate (datum interface {}) (bool , error ) {
5564 opts := []Option {
5665 WithTagName (eval .tagName ),
@@ -62,3 +71,8 @@ func (eval *Evaluator) Evaluate(datum interface{}) (bool, error) {
6271
6372 return evaluate (eval .ast , datum , opts ... )
6473}
74+
75+ // Expression can be used to return the initial expression used to create the Evaluator.
76+ func (eval * Evaluator ) Expression () string {
77+ return eval .expression
78+ }
0 commit comments