exprel

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2019 License: MPL-2.0 Imports: 9 Imported by: 0

README

exprel GoDoc

Package exprel provides a Spreadsheet-like expression evaluator.

Example expressions which exprel can evaluate:

Expression                        Return value
----------------------------------------------
Hey there                         "Hey there"
1234                              "1234"
=5+5*2                            15
="A" & " " & "B"                  "A B"
=IF(AND(NOT(FALSE());1=1);1+2;2)  3

Documentation

Documentation is provided through the package's godoc. The documentation can be viewed online at godoc.org.

License

MPL 2.0

Author

Tim Cooper (tim.cooper@layeh.com)

Documentation

Overview

Package exprel provides a Spreadsheet-like expression evaluator.

// Quick start

import (
  "layeh.com/exprel"
)

data := map[string]interface{}{
  "name": "Tim",
}
expression := `=LOWER(name) & ".jpg"`
filename, err := exprel.String(exprel.Evaluate(expression, exprel.SourceMap(data)))
if err != nil {
  panic(err)
}
// filename = "tim.jpg"

Introduction

All expressions return a single value. Here are a few examples of some valid expressions and their return values:

Expression                        Return value
----------------------------------------------
Hey there                         "Hey there"
1234                              "1234"
=5+5*2                            15
="A" & " " & "B"                  "A B"
=IF(AND(NOT(FALSE());1=1);1+2;2)  3

Expressions with logic must start with an equals sign (=). Otherwise, the evaluated value is simply the source string.

Values

The following values are can be returned by and used in an expression:

string
float64 (number)
bool (boolean)

Sources may also return the following type, which defines a function that can be called from an expression:

func(c *Call) (value interface{}, err error)

Operators

The following operators and built-ins are defined:

                  Usage              Notes
------------------------------------------
Addition          a + b              number
Subtraction       a - b              number
Multiplication    a * b              number
Division          a / b              number
Exponentiation    a ^ b              number
Modulo            a % b              number
Concatenation     a & b              string

Equality          a = b              string, number, boolean
Inequality        a <> b             string, number, boolean
Greater than      a > b              string, number
Greater or equal  a >= b             string, number
Less than         a < b              string, number
Less or equal     a <= b             string, number

Logical AND       AND(bool...)       Operands lazily evaluated
Logical OR        OR(bool...)        Operands lazily evaluated
Logical NOT       NOT(bool)          Operands lazily evaluated

Condition         IF(bool;ANY;ANY)   Lazily evaluated

Boolean true      TRUE()
Boolean false     FALSE()

The following functions are defined as part of Base:

CHOOSE(number index; ANY...) ANY
  Returns the index item of the remaining arguments
TYPE(ANY a) number
  Identifies the type of a. Types are mapped in the following way:
    Number  = 1
    String  = 2
    Boolean = 4

ABS(number a) number
  Returns the absolute value of a.
EXP(number a) number
  Returns e^a.
LN(number a) number
  Returns the natural logarithm of a.
LOG10(number a) number
  Returns the base-10 logarithm of a.
PI() number
  Returns π.
RAND() number
  Returns a random number in the range [0, 1).
SIGN(number a) number
  Returns the sign of a.

CHAR(number...) string
  Returns a string whose code points are given as arguments.
JOIN(string sep; string...) string
  Returns the trailing string arguments concatenated together with sep.
LEFT(string a; number count = 1) string
  Returns the count left-most characters of a.
LEN(string a) number
  Returns the length of a.
LOWER(string a) string
  Returns a with all uppercase characters transformed to lowercase.
MID(string a; number start; number length = 1) string
  Returns length characters of a, starting from start.
REPT(string a; number count) string
  Returns the string a, repeated count times.
RIGHT(string a; number count = 1) string
  Returns the count right-most characters of a.
SEARCH(string needle; string haystack; number start = 1) number
  Returns the position of needle in haystack, starting from start. -1 is
  returned if needle was not found.
TRIM(string a) string
  Returns a with whitespace removed from the beginning and end.
UPPER(string a) string
  Returns a with all lowercase characters transformed to uppercase.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Boolean added in v0.3.0

func Boolean(val interface{}, err error) (bool, error)

Boolean ensures that an evaluated expression's return type is bool.

func Evaluate added in v0.3.0

func Evaluate(s string, source ...Source) (val interface{}, err error)

Evaluate is a wrapper around EvaluateContext that uses the background context.

func EvaluateContext added in v0.3.0

func EvaluateContext(ctx context.Context, s string, source ...Source) (val interface{}, err error)

EvaluateContext parses the given string and evaluates it with the given sources (Base is automatically included).

Upon success, value and nil are returned. Upon failure, nil and error are returned.

func Number added in v0.3.0

func Number(val interface{}, err error) (float64, error)

Number ensures that an evaluated expression's return type is float64.

func String added in v0.3.0

func String(val interface{}, err error) (string, error)

String ensures that an evaluated expression's return type is string.

Types

type Call added in v0.2.0

type Call struct {
	// The name used to invoke the function.
	Name string
	// The arguments passed to the function.
	Values []interface{}
	// contains filtered or unexported fields
}

Call contains information about an expression function call.

func (*Call) Boolean added in v0.2.0

func (c *Call) Boolean(i int) bool

Boolean returns the ith argument, iff it is a bool. Otherwise, the function panics with a *RuntimeError.

func (*Call) Context added in v0.3.0

func (c *Call) Context() context.Context

Context returns the context for the current function call.

func (*Call) Number added in v0.2.0

func (c *Call) Number(i int) float64

Number returns the ith argument, iff it is a float64. Otherwise, the function panics with a *RuntimeError.

func (*Call) OptBoolean added in v0.3.0

func (c *Call) OptBoolean(i int, def bool) bool

OptBoolean returns the ith argument, iff it is a bool. If the ith argument does not exist, def is returned. If the ith argument is not a bool, the function panics with a *RuntimeError.

func (*Call) OptNumber added in v0.3.0

func (c *Call) OptNumber(i int, def float64) float64

OptNumber returns the ith argument, iff it is a float64. If the ith argument does not exist, def is returned. If the ith argument is not a number, the function panics with a *RuntimeError.

func (*Call) OptString added in v0.3.0

func (c *Call) OptString(i int, def string) string

OptString returns the ith argument, iff it is a string. If the ith argument does not exist, def is returned. If the ith argument is not a string, the function panics with a *RuntimeError.

func (*Call) String added in v0.2.0

func (c *Call) String(i int) string

String returns the ith argument, iff it is a string. Otherwise, the function panics with a *RuntimeError.

type Expression

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

Expression is an user-defined expression that can be evaluated.

func Parse

func Parse(s string) (*Expression, error)

Parse returned a new, executable expression from s. The syntax of s is outlined in the package documentation.

Upon success, expression and nil are returned. Upon failure, nil and error are returned.

func (*Expression) Evaluate

func (e *Expression) Evaluate(s Source) (val interface{}, err error)

Evaluate is a wrapper around EvaluateContext that uses the background context.

func (*Expression) EvaluateContext added in v0.3.0

func (e *Expression) EvaluateContext(ctx context.Context, s Source) (val interface{}, err error)

EvaluateContext evaluates the expression with the given source.

Upon success, value and nil are returned. Upon failure, nil and error are returned.

func (*Expression) MarshalText added in v0.3.0

func (e *Expression) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Expression) UnmarshalText added in v0.3.0

func (e *Expression) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Func

type Func = func(call *Call) (interface{}, error)

Func is a function that can be executed from an Expression.

type RuntimeError

type RuntimeError struct {
	Message string
	Err     error
}

RuntimeError represents an error that is triggered when evaluating an expression.

func (*RuntimeError) Error

func (e *RuntimeError) Error() string

type Source

type Source interface {
	Get(ctx context.Context, name string) (value interface{}, ok bool)
}

Source is a source of data for an expression. Get is called when an identifier needs to be evaluated.

var Base Source = baseSource

Base contains the base functions, as described in the package documentation.

var EmptySource Source = emptySource{}

EmptySource is a Source that contains no values.

type SourceFunc

type SourceFunc func(ctx context.Context, name string) (value interface{}, ok bool)

SourceFunc is a Source that looks up an identifier via a function.

func (SourceFunc) Get

func (f SourceFunc) Get(ctx context.Context, name string) (interface{}, bool)

Get implements Source.

type SourceMap

type SourceMap map[string]interface{}

SourceMap is a Source that looks up an identifier in a map.

func (SourceMap) Get

func (m SourceMap) Get(ctx context.Context, name string) (interface{}, bool)

Get implements Source.

type Sources

type Sources []Source

Sources is a slice of sources. The first Source, in order, to return ok, will have its value returned.

func (Sources) Get

func (s Sources) Get(ctx context.Context, name string) (interface{}, bool)

Get implements Source.

type SyntaxError

type SyntaxError struct {
	Message  string
	Position int
}

SyntaxError represents an error that is triggered when parsing an expression.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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