expr

package
v0.0.0-...-d046166 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 10, 2020 License: BSD-3-Clause Imports: 7 Imported by: 0

Documentation

Overview

Package expr provides support for evaluating boolean expressions.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Expr

type Expr struct {
	// contains filtered or unexported fields
}

Expr holds a parsed boolean expression that matches some combination of attributes.

Expressions are supplied as strings consisting of the following tokens:

  • Attributes, either as bare identifiers (only if compliant with https://golang.org/ref/spec#Identifiers) or as double-quoted strings (in which '*' characters are interpreted as wildcards)
  • Binary operators: && (and), || (or)
  • Unary operator: ! (not)
  • Grouping: (, )

The expression syntax is conveniently a subset of Go's syntax, so Go's parser and ast packages are used to convert the initial expression into a binary expression tree.

After an Expr object is created from a string expression, it can be asked if it is satisfied by a supplied set of attributes.

Example
e, _ := New("a && (b || c) && !d")
for _, attrs := range [][]string{
	{"a"},
	{"a", "b"},
	{"a", "c"},
	{"a", "c", "d"},
} {
	if e.Matches(attrs) {
		fmt.Println(attrs, "matched")
	} else {
		fmt.Println(attrs, "not matched")
	}
}
Output:

[a] not matched
[a b] matched
[a c] matched
[a c d] not matched
Example (Quoted)
e, _ := New("\"attr-hyphen\" && \"attr space\" && attr_under")
if e.Matches([]string{"attr-hyphen", "attr space", "attr_under"}) {
	fmt.Println("matched")
}
Output:

matched
Example (Wildcard)
e, _ := New("\"foo:*\" && !\"*bar\"")
for _, attrs := range [][]string{
	{"foo:"},
	{"foo:a"},
	{"foo:a", "bar"},
	{"foo:a", "foo:bar"},
} {
	if e.Matches(attrs) {
		fmt.Println(attrs, "matched")
	} else {
		fmt.Println(attrs, "not matched")
	}
}
Output:

[foo:] matched
[foo:a] matched
[foo:a bar] not matched
[foo:a foo:bar] not matched

func New

func New(s string) (*Expr, error)

New parses and validates boolean expression s, returning an Expr object that can be used to test whether the expression is satisfied by different sets of attributes.

func (*Expr) Matches

func (e *Expr) Matches(attrs []string) bool

Matches returns true if the expression is satisfied by attributes attrs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL