conditions

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2022 License: MIT Imports: 10 Imported by: 0

README

conditions

This package offers a parser of a simple conditions specification language (reduced set of arithmetic/logical operations). The package is mainly created for Flow-Based Programming components that require configuration to perform some operations on the data received from multiple input ports. But it can be used whereever you need externally define some logical conditions on the internal variables.

Additional credits for this package go to Handwritten Parsers & Lexers in Go by Ben Johnson on Gopher Academy blog and InfluxML package from InfluxDB repository.

Usage example

package main

import (
    "fmt"
    "strings"

    "github.com/zhouzhuojie/conditions"
)

func main() {
    // Our condition to check
    s := `({foo} > 0.45) AND ({bar} == "ON" OR {baz} IN ["ACTIVE", "CLEAR"])`

    // Parse the condition language and get expression
    p := conditions.NewParser(strings.NewReader(s))
    expr, err := p.Parse()
    if err != nil {
        // ...
    }

    // Evaluate expression passing data for $vars
    data := map[string]interface{}{"foo": 0.12, "bar": "OFF", "baz": "ACTIVE"}
    r, err := conditions.Evaluate(expr, data)
    if err != nil {
        // ...
    }

    // r is false
    fmt.Println("Evaluation result:", r)
}

Credit

Forked from https://github.com/oleksandr/conditions

The main differences are

  • Changed the syntax of variables from [foo] to {foo}.
  • Added CONTAINS.
  • Added float comparison with epsilon error torlerence.
  • Optimized long array IN/CONTAINS operator.
  • Removed redundant RWMutex for better performance.

Documentation

Overview

Package conditions package offers a parser of a simple conditions specification language (reduced set of arithmetic/logical operations). It was created for Flow-Based Programming components that require configuration to perform some operations on the data received from multiple input ports.

Index

Constants

View Source
const (
	Unknown  = DataType("")
	Number   = DataType("number")
	Boolean  = DataType("boolean")
	String   = DataType("string")
	Time     = DataType("time")
	Duration = DataType("duration")
)

Variables

This section is empty.

Functions

func Evaluate

func Evaluate(expr Expr, args map[string]interface{}) (bool, error)

Evaluate takes an expr and evaluates it using given args

func EvaluateWithArgResolver

func EvaluateWithArgResolver(expr Expr, args ArgResolver) (bool, error)

EvaluateWithArgResolver takes an expr and evaluates it using given arg resolver

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats a duration to a string.

func Quote

func Quote(s string) string

Quote returns a quoted string.

func QuoteIdent

func QuoteIdent(s string) string

QuoteIdent returns a quoted identifier if the identifier requires quoting. Otherwise returns the original string passed in.

func SetDefaultEpsilon

func SetDefaultEpsilon(ep float64)

SetDefaultEpsilon sets the defaultEpsilon

func Variables

func Variables(expression Expr) []string

Variables ...

func Walk

func Walk(v Visitor, node Node)

Walk traverses a node hierarchy in depth-first order.

func WalkFunc

func WalkFunc(node Node, fn func(Node))

WalkFunc traverses a node hierarchy in depth-first order.

Types

type ArgResolver

type ArgResolver interface {
	Resolve(key string) (interface{}, error)
}

func NewMapArgResolver

func NewMapArgResolver(args map[string]interface{}) ArgResolver

type BinaryExpr

type BinaryExpr struct {
	Op  Token
	LHS Expr
	RHS Expr
}

BinaryExpr represents an operation between two expressions.

func (*BinaryExpr) Args

func (e *BinaryExpr) Args() []string

func (*BinaryExpr) String

func (e *BinaryExpr) String() string

String returns a string representation of the binary expression.

type BooleanLiteral

type BooleanLiteral struct {
	Val bool
}

BooleanLiteral represents a boolean literal.

func (*BooleanLiteral) Args

func (l *BooleanLiteral) Args() []string

func (*BooleanLiteral) String

func (l *BooleanLiteral) String() string

String returns a string representation of the literal.

type Collection added in v0.2.0

type Collection interface {
	String() string
	Count() int
}

func NewCollection added in v0.2.0

func NewCollection(items []interface{}) (Collection, error)

func NewMapNumberCollection

func NewMapNumberCollection(items []interface{}) Collection

func NewMapNumberCollectionFromMap added in v0.2.0

func NewMapNumberCollectionFromMap(items map[float64]bool) Collection

func NewMapStringCollection added in v0.1.4

func NewMapStringCollection(items []interface{}) Collection

func TryNewCollection added in v0.2.0

func TryNewCollection(items []interface{}) Collection

type DataType

type DataType string

DataType represents the primitive data types available in InfluxQL.

func InspectDataType

func InspectDataType(v interface{}) DataType

InspectDataType returns the data type of a given value.

type DurationLiteral

type DurationLiteral struct {
	Val time.Duration
}

DurationLiteral represents a duration literal.

func (*DurationLiteral) String

func (l *DurationLiteral) String() string

String returns a string representation of the literal.

type Expr

type Expr interface {
	Node

	Args() []string
	// contains filtered or unexported methods
}

Expr represents an expression that can be evaluated to a value.

type MapArgResolver

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

func (*MapArgResolver) Resolve

func (r *MapArgResolver) Resolve(key string) (interface{}, error)

type MapNumberCollection

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

func (*MapNumberCollection) Count added in v0.2.0

func (c *MapNumberCollection) Count() int

func (*MapNumberCollection) Has

func (c *MapNumberCollection) Has(number float64) bool

func (*MapNumberCollection) String

func (c *MapNumberCollection) String() string

type MapStringCollection added in v0.1.4

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

func (*MapStringCollection) Count added in v0.2.0

func (c *MapStringCollection) Count() int

func (*MapStringCollection) Has added in v0.1.4

func (c *MapStringCollection) Has(val string) bool

func (*MapStringCollection) String added in v0.1.4

func (c *MapStringCollection) String() string

type Node

type Node interface {
	String() string
	// contains filtered or unexported methods
}

Node represents a node in the conditions abstract syntax tree.

type NumberCollection

type NumberCollection interface {
	Has(number float64) bool
	String() string
}

type NumberCollectionLiteral

type NumberCollectionLiteral struct {
	Val NumberCollection
}

func (*NumberCollectionLiteral) Args

func (l *NumberCollectionLiteral) Args() []string

func (*NumberCollectionLiteral) String

func (l *NumberCollectionLiteral) String() string

type NumberLiteral

type NumberLiteral struct {
	Val float64
}

NumberLiteral represents a numeric literal.

func (*NumberLiteral) Args

func (n *NumberLiteral) Args() []string

func (*NumberLiteral) String

func (l *NumberLiteral) String() string

String returns a string representation of the literal.

type ParenExpr

type ParenExpr struct {
	Expr Expr
}

ParenExpr represents a parenthesized expression.

func (*ParenExpr) Args

func (p *ParenExpr) Args() []string

func (*ParenExpr) String

func (e *ParenExpr) String() string

String returns a string representation of the parenthesized expression.

type Parser

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

Parser encapsulates the scanner and responsible for returning AST composed from statements read from a given reader.

func NewParser

func NewParser(r io.Reader) *Parser

NewParser returns a new instance of Parser.

func (*Parser) Parse

func (p *Parser) Parse() (Expr, error)

Parse starts scanning & parsing process (main entry point). It returns an expression (AST) which you can use for the final evaluation of the conditions/statements

type SliceNumberLiteral

type SliceNumberLiteral struct {
	Val []float64
}

func (*SliceNumberLiteral) Args

func (l *SliceNumberLiteral) Args() []string

func (*SliceNumberLiteral) String

func (l *SliceNumberLiteral) String() string

String returns a string representation of the literal.

type SliceStringLiteral

type SliceStringLiteral struct {
	Val []string
	// contains filtered or unexported fields
}

func NewSliceStringLiteral

func NewSliceStringLiteral(val []string) *SliceStringLiteral

func (*SliceStringLiteral) Args

func (l *SliceStringLiteral) Args() []string

func (*SliceStringLiteral) String

func (l *SliceStringLiteral) String() string

String returns a string representation of the literal.

type StringCollection added in v0.1.4

type StringCollection interface {
	Has(val string) bool
	String() string
}

type StringCollectionLiteral added in v0.1.4

type StringCollectionLiteral struct {
	Val StringCollection
}

func (*StringCollectionLiteral) Args added in v0.1.4

func (l *StringCollectionLiteral) Args() []string

func (*StringCollectionLiteral) String added in v0.1.4

func (l *StringCollectionLiteral) String() string

type StringLiteral

type StringLiteral struct {
	Val string
}

StringLiteral represents a string literal.

func (*StringLiteral) Args

func (l *StringLiteral) Args() []string

func (*StringLiteral) String

func (l *StringLiteral) String() string

String returns a string representation of the literal.

type TimeLiteral

type TimeLiteral struct {
	Val time.Time
}

TimeLiteral represents a point-in-time literal.

func (*TimeLiteral) String

func (l *TimeLiteral) String() string

String returns a string representation of the literal.

type Token

type Token int

Token represents a lexical token.

const (
	// ILLEGAL token represent illegal token found in the statement
	ILLEGAL Token = iota
	// EOF token represents end of statement
	EOF

	IDENT  // Variable references $0, $5, etc
	NUMBER // 12345.67
	STRING // "abc"
	ARRAY  // array of values (string or number) ["a","b","c"]  [342,4325,6,4]
	TRUE   // true
	FALSE  // false

	AND         // AND
	OR          // OR
	EQ          // =
	NEQ         // !=
	LT          // <
	LTE         // <=
	GT          // >
	GTE         // >=
	NAND        // NAND
	XOR         // XOR
	EREG        // =~
	NEREG       // !~
	IN          // IN
	NOTIN       // NOT IN
	CONTAINS    // CONTAINS
	NOTCONTAINS // NOT CONTAINS

	LPAREN // (
	RPAREN // )
)

func (Token) Precedence

func (tok Token) Precedence() int

Precedence returns the operator precedence of the binary operator token.

func (Token) String

func (tok Token) String() string

String returns the string representation of the token.

type VarRef

type VarRef struct {
	Val string
}

VarRef represents a reference to a variable.

func (*VarRef) Args

func (r *VarRef) Args() []string

func (*VarRef) String

func (r *VarRef) String() string

String returns a string representation of the variable reference.

type Visitor

type Visitor interface {
	Visit(Node) Visitor
}

Visitor can be called by Walk to traverse an AST hierarchy. The Visit() function is called once per node.

Jump to

Keyboard shortcuts

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