GO package for analysis and calculation of expressions
Go to file
2024-04-13 05:54:34 +02:00
doc Expression process diagram added 2024-04-04 12:56:43 +02:00
ast_test.go Expressions now support function definition 2024-04-02 04:36:03 +02:00
ast.go merge: solved a lot of conflicts caused by an incorect commit removal 2024-04-13 05:47:10 +02:00
byte-slider.go Added copyrighr note to all sources 2024-03-26 08:45:18 +01:00
context.go ExprContext.SetVar() no longer requires the explicit specification of the type of number 2024-04-09 07:12:22 +02:00
control.go control: exported all control variables by renaming them in upper case 2024-04-13 05:16:23 +02:00
func-import.go control: exported all control variables by renaming them in upper case 2024-04-13 05:16:23 +02:00
func-math.go builtin-funcs: export import functions (made their names uppercase) 2024-04-13 04:18:14 +02:00
go.mod added go.mod 2024-03-26 08:56:20 +01:00
graph_test.go added the graph source files 2024-04-13 05:54:34 +02:00
graph.go added the graph source files 2024-04-13 05:54:34 +02:00
helpers_test.go helpers_test.go: removed the printed messages "Hello World!" 2024-04-13 05:06:43 +02:00
helpers.go Arg struct members are now exported 2024-04-09 06:28:57 +02:00
it-range.go Added Iterator interface and two implementation: list itrator and range iterator 2024-03-30 06:56:12 +01:00
iterator.go Added Iterator interface and two implementation: list itrator and range iterator 2024-03-30 06:56:12 +01:00
operand-const.go class and kind types removed 2024-04-09 05:32:50 +02:00
operand-expr.go class and kind types removed 2024-04-09 05:32:50 +02:00
operand-func.go ExprContext.SetVar() no longer requires the explicit specification of the type of number 2024-04-09 07:12:22 +02:00
operand-list.go class and kind types removed 2024-04-09 05:32:50 +02:00
operand-selector-case.go operand-selector-case.go: String() function added to the selectorCase type 2024-04-13 04:32:54 +02:00
operand-var.go class and kind types removed 2024-04-09 05:32:50 +02:00
operator-assign.go ExprContext.SetVar() no longer requires the explicit specification of the type of number 2024-04-09 07:12:22 +02:00
operator-bool.go control: exported all control variables by renaming them in upper case 2024-04-13 05:16:23 +02:00
operator-but.go class and kind types removed 2024-04-09 05:32:50 +02:00
operator-coalesce.go ExprContext.SetVar() no longer requires the explicit specification of the type of number 2024-04-09 07:12:22 +02:00
operator-ctrl.go class and kind types removed 2024-04-09 05:32:50 +02:00
operator-fact.go class and kind types removed 2024-04-09 05:32:50 +02:00
operator-prod.go class and kind types removed 2024-04-09 05:32:50 +02:00
operator-rel.go class and kind types removed 2024-04-09 05:32:50 +02:00
operator-selector.go class and kind types removed 2024-04-09 05:32:50 +02:00
operator-sign.go class and kind types removed 2024-04-09 05:32:50 +02:00
operator-sum.go class and kind types removed 2024-04-09 05:32:50 +02:00
parser_test.go parser_test.go: changed the notice message about EXPR_PATH 2024-04-13 04:40:48 +02:00
parser.go parser.go: fixed a problem on the selector operator 2024-04-13 04:37:15 +02:00
README.adoc README.adoc: updated draft 2024-04-09 09:11:47 +02:00
sample-export-all.expr Operator '@@' (export-all) added. Experimental include() function also added 2024-04-06 03:06:07 +02:00
scanner_test.go Added copyrighr note to all sources 2024-03-26 08:45:18 +01:00
scanner.go Selector operator, multi-operand, added 2024-04-08 22:16:07 +02:00
simple-func-store.go made some interfaces exportable and fixed/enhaaced some selector operator versions 2024-04-08 23:17:56 +02:00
simple-var-store.go ExprContext.SetVar() no longer requires the explicit specification of the type of number 2024-04-09 07:12:22 +02:00
symbol.go Selector operator, multi-operand, added 2024-04-08 22:16:07 +02:00
term_test.go term_test.go: changed some fmt.Println() to t.Log() 2024-04-13 05:07:38 +02:00
term-constuctor-registry.go Added copyrighr note to all sources 2024-03-26 08:45:18 +01:00
term.go class and kind types removed 2024-04-09 05:32:50 +02:00
test-funcs.expr Operator '@@' (export-all) added. Experimental include() function also added 2024-04-06 03:06:07 +02:00
token_test.go token_test.go: rewritten using a more structured form 2024-04-13 05:08:38 +02:00
token.go token.go: better implementation of the function String() 2024-04-13 04:33:59 +02:00
utils.go ExprContext.SetVar() no longer requires the explicit specification of the type of number 2024-04-09 07:12:22 +02:00

Expr

1. Expr

Expr is a GO package capable of analysing, interpreting and calculating expressions.

A few examples to get started.

Examples taken from parser_test.go
`1.0 / 2`                      // 0.5
`435 + 105 * 2 - 1`            // 644
`4 == (3-1)*(10/5)`            // true
`"uno" * (2+1)`                // `unounouno`
`2+3 but 5*2`                  // 10 (1)
`add(add(1+4),3+2,5*(3-2))`    // 15 (2)
`a=5; b=2; add(a, b*3)`        // 11 (3)
`two=func(){2}; two()`         // 2  (4)
`double=func(x){2*x}; a=4+1; two=func() {2}; (double(3+a) + 1) * two()`  // 34
`import("./test-funcs.expr"); (double(3+a) + 1) * two()`  // 34 (5)
`[1,2,"hello"]`                // Mixed types list
`[1,2]+[3]`                    // append list, result: [1,2,3]
`add([1,[2,2],3,2])`           // Deep list sum, result: 10 (2)
`[a=1,b=2,c=3] but a+b+c`      // 6
1 but operator.
2 The add() function definition may be changed in the future.
3 Multiple expression. Only the last expression value will returned.
4 Simple function definition: two() returns 2.
5 import() function imports expressions from the specified files. See file test-funcs.expr.

1.1. Usage

package main

import (
	"fmt"
	"strings"
	"git.portale-stac.it/go-pkg/expr"
)

func main() {
	ctx := expr.NewSimpleVarStore()
	ctx.SetVar("var", 4)

	source := `(3-1)*(10/5) == var`

	r := strings.NewReader(source)
	scanner := expr.NewScanner(r, expr.DefaultTranslations())
	parser := expr.NewParser(ctx)

	if ast, err := parser.Parse(scanner); err == nil {
		if result, err := ast.Eval(ctx); err == nil {
			fmt.Printf("%q -> %v [%T]\n", source, result, result)
		} else {
			fmt.Println("Error calculating the expression:", err)
		}
	} else {
		fmt.Println("Error parsing the expression:", err)
	}
}

The above program is equivalent to the following one.

package main

import (
	"fmt"
	"git.portale-stac.it/go-pkg/expr"
)

func main() {
	ctx := expr.NewSimpleVarStore()
	ctx.SetVar("var", 4)

	source := `(3-1)*(10/5) == var`

	if result, err := expr.EvalString(ctx, source); err == nil {
		fmt.Printf("%q -> %v [%T]\n", source, result, result)
	} else {
		fmt.Println("Error calculating the expression:", err)
	}
}

Here is another equivalent version.

package main

import (
	"fmt"
	"git.portale-stac.it/go-pkg/expr"
)

func main() {
	source := `(3-1)*(10/5) == var`

	if result, err := expr.EvalStringA(source, expr.Arg{"var", 4}); err == nil {
		fmt.Printf("%q -> %v [%T]\n", source, result, result)
	} else {
		fmt.Println("Error calculating the expression:", err)
	}
}

1.3. Data types

Expr supports numerical, string, relational, boolean expressions, and mixed-type lists.

1.3.1. Numbers

Numbers can be integers (GO int64) or float (GO float64). In mixed operations involving integers and floats, integers are automatically promoted to floats.

Table 1. Arithmetic operators
Symbol Operation Description Examples

+ / -

change sign

Change the sign of values

-1 [-1]
-(+2) [-2]

+

sum

Add two values

-1 + 2 [1]
4 + 0.5 [4.5]

-

subtraction

Subtract the right value from the left one

3 - 1 [2]
4 - 0.5 [3.5]

*

product

Multiply two values

-1 * 2 [-2]
4 * 0.5 [2.0]

/

Division

Divide the left value by the right one

-1 / 2 [0]
1.0 / 2 [0.5]

./

Float division

Force float division

-1 ./ 2 [-0.5]

%

Modulo

Remainder of the integer division

5 % 2 [1]

1.3.2. String

Strings are character sequences enclosed between two double quote ". Example: "Im a string".

Some arithmetic operators can also be used with strings.

Table 2. String operators
Symbol Operation Description Examples

+

concatenation

Join two strings or two stringable values

"one" + "two" ["onetwo"]
"one" + 2 ["one2"]

*

repeat

Make n copy of a string

"one" * 2 ["oneone"]

1.3.3. Boolean

Boolean data type has two values only: true and false. Relational and Boolean expressions produce Boolean values.

Table 3. Relational operators
Symbol Operation Description Examples

==

Equal

True if the left value is equal to the right one

5 == 2 [false]
"a" == "a" [true]

!=

Not Equal

True if the left value is NOT equal to the right one

5 != 2 [true]
"a" != "a" [false]

<

Less

True if the left value is less than the right one

5 < 2 [false]
"a" < "b" [true]

<=

Less or Equal

True if the left value is less than or equal to the right one

5 <= 2 [false]
"b" <= "b" [true]

>

Greater

True if the left value is greater than the right one

5 > 2 [true]
"a" < "b" [false]

>=

Greater or Equal

True if the left value is greater than or equal to the right one

5 >= 2 [true]
"b" <= "b" [true]

Table 4. Boolean operators
Symbol Operation Description Examples

NOT

Not

True if the right value is false

NOT true [false]
NOT (2 < 1) [true]

AND / &&

And

True if both left and right values are true

false && true [false]
"a" < "b" AND NOT (2 < 1) [true]

OR / ||

Or

True if at least one of the left and right values integers true

false or true [true]
"a" == "b" OR (2 == 1) [false]

Currently, boolean operations are evaluated using short cut evaluation. This means that, if the left expression of operators and and or is sufficient to establish the result of the whole operation, the right expression would not evaluated at all.

Example
2 > (a=1) or (a=8) > 0; a (1)
1 This multi-expression returns 1 because in the first expression the left value of or is true and as a conseguence its right value is not computed. Therefore the a variable only receives the integer 1.

1.3.4. List

Expr supports list of mixed-type values, also specified by normal expressions.

List examples
[1, 2, 3]                   // List of integers
["one", "two", "three"]     // List of strings
["one", 2, false, 4.1]      // List of mixed-types
["one"+1, 2.0*(9-2)]        // List of expressions
[ [1,"one"], [2,"two"]]     // List of lists
Table 5. List operators
Symbol Operation Description Examples

+

Join

Joins two lists

[1,2] + [3] [ [1,2,3] ]

-

Difference

Left list without elements in the right list

[1,2,3] - [2] [ [1,3] ]

1.4. Variables

A variable is an identifier with an assigned value. Variables are stored in the object that implements the ExprContext interface.

Examples
a=1
x = 5.2 * (9-3)
x = 1; y = 2*x

1.5. Other operations

1.5.1. ; operator

The semicolon operator ; is an infixed operator. It evaluates the left expression first and then the right expression. The latter is the final result.

Technically ; is not treated as a real operator. It acts as a separator in lists of expressions.
; can be used to set some variables before the final calculation.
Example
a=1; b=2; c=3; a+b+c    // returns 6

1.5.2. but operator

but is an infixed operator. Its operands can be any type of expression. It evaluates the left expression first, then the right expression. The value of the right expression is the final result. Examples: 5 but 2 returns 2, x=2*3 but x-1 returns 5.

but is very similar to ;. The only difference is that ; cant be used inside parenthesis ;( and ).

1.5.3. Assignment operator =

The assignment operator = is used to define variable in the evaluation context or to change their value (see ExprContext). The value on the left side of = must be an identifier. The value on the right side can be any expression and it becomes the result of the assignment operation.

Example
a=15+1    // returns 16

1.5.4. Selector operator ? : ::

The selector operator is very similar to the switch/case/default statement available in many programming languages.

Syntax
<selector-operator> ::= <expression> "?" <selector-case> { ":" <selector-case> } ["::" <case-value>]
<selector-case> ::= [<list>] <case-value>
<case-value> ::= "{" <multi-expr> "}"
<multi-expr> ::= <expr> {";" <expr>}
Example
1 ? {"a"} : {"b"}                           // returns "b"
10 ? {"a"} : {"b"} :: {"c"}                 // returns "c"
10 ? {"a"} :[true, 2+8] {"b"} :: {"c"}      // returns "b"
10 ? {"a"} :[true, 2+8] {"b"} ::[10] {"c"}  // error:  "... case list in default clause"
10 ? {"a"} :[10] {x="b" but x} :: {"c"}     // returns "b"
10 ? {"a"} :[10] {x="b"; x} :: {"c"}        // returns "b"
10 ? {"a"} : {"b"}                          // error:  "... no case catches the value (10) of the selection expression

1.6. Priorities of operators

The table below shows all supported operators by decreasing priorities.

Table 6. Operators priorities
Priority Operators Position Operation Operands and results

FACT

!

Postfix

Factorial

integer "!" → integer

SIGN

+, -

Prefix

Change-sign

("+"|"-") numbernumber

PROD

*

Infix

Product

number "*" numbernumber

*

Infix

String-repeat

string "*" integerstring

/

Infix

Division

number "/" numbernumber

./

Infix

Float-division

number "./" numberfloat

%

Infix

Integer-remainder

integer "%" integerinteger

SUM

+

Infix

Sum

number "+" numbernumber

+

Infix

String-concat

(string|number) "+" (string|number) → string

+

Infix

List-join

list "+" listlist

-

Infix

Subtraction

number "-" numbernumber

-

Infix

List-difference

list "-" listlist

RELATION

<

Infix

less

comparable "<" comparableboolean

<=

Infix

less-equal

comparable "<=" comparableboolean

>

Infix

greater

comparable ">" comparableboolean

>=

Infix

greater-equal

comparable ">=" comparableboolean

==

Infix

equal

comparable "==" comparableboolean

!=

Infix

not-equal

comparable "!=" comparableboolean

NOT

not

Prefix

not

"not" booleanboolean

AND

and

Infix

and

boolean "and" booleanboolean

&&

Infix

and

boolean "&&" booleanboolean

OR

or

Infix

or

boolean "or" booleanboolean

||

Infix

or

boolean "||" booleanboolean

ASSIGN

=

Infix

assignment

identifier "=" anyany

BUT

but

Infix

but

any "but" anyany

1.7. Functions

Functions in Expr are very similar to functions in many programming languages.

In Expr functions compute values in a local context (scope) that do not make effects on the calling context. This is the normal behavior. Using the reference operator @ it is possibile to export local definition to the calling context.

1.7.1. Function calls

TODO: function calls operations

1.7.2. Function definitions

TODO: function definitions operations

1.8. Builtins

TODO: builtins

1.8.2. import()

import(<source-file>) loads the multi-expression contained in the specified source and returns its value.