https://github.com/ArashPartow/exprtk
C++ Mathematical Expression Parsing And Evaluation Library https://www.partow.net/programming/exprtk/index.html
https://github.com/ArashPartow/exprtk
ast c-plus-plus compiler expression-evaluator expression-parser exprtk grammar high-performance language lexer math math-expressions mathematics mirrored-repository mit-license numerical-calculations optimization-algorithms parser scientific-computing semantic-analyzer
Last synced: about 1 year ago
JSON representation
C++ Mathematical Expression Parsing And Evaluation Library https://www.partow.net/programming/exprtk/index.html
- Host: GitHub
- URL: https://github.com/ArashPartow/exprtk
- Owner: ArashPartow
- Created: 2012-01-28T20:47:19.000Z (over 14 years ago)
- Default Branch: master
- Last Pushed: 2024-06-07T09:58:41.000Z (almost 2 years ago)
- Last Synced: 2024-07-31T22:46:51.317Z (almost 2 years ago)
- Topics: ast, c-plus-plus, compiler, expression-evaluator, expression-parser, exprtk, grammar, high-performance, language, lexer, math, math-expressions, mathematics, mirrored-repository, mit-license, numerical-calculations, optimization-algorithms, parser, scientific-computing, semantic-analyzer
- Language: C++
- Homepage: https://www.partow.net/programming/exprtk/index.html
- Size: 3.62 MB
- Stars: 604
- Watchers: 50
- Forks: 252
- Open Issues: 4
-
Metadata Files:
- Readme: readme.txt
Awesome Lists containing this project
README
C++ Mathematical Expression Toolkit Library Documentation
Section 00 - Introduction
Section 01 - Capabilities
Section 02 - Example Expressions
Section 03 - Copyright Notice
Section 04 - Downloads & Updates
Section 05 - Installation
Section 06 - Compilation
Section 07 - Compiler Compatibility
Section 08 - Built-In Operations & Functions
Section 09 - Fundamental Types
Section 10 - Components
Section 11 - Compilation Options
Section 12 - Expression Structures
Section 13 - Variable, Vector & String Definition
Section 14 - Vector Processing
Section 15 - User Defined Functions
Section 16 - Expression Dependents
Section 17 - Hierarchies Of Symbol Tables
Section 18 - Unknown Unknowns
Section 19 - Enabling & Disabling Features
Section 20 - Expression Return Values
Section 21 - Compilation Errors
Section 22 - Runtime Library Packages
Section 23 - Helpers & Utils
Section 24 - Runtime Checks
Section 25 - Benchmarking
Section 26 - Exprtk Notes
Section 27 - Simple Exprtk Example
Section 28 - Build Options
Section 29 - Files
Section 30 - Language Structure
[SECTION 00 - INTRODUCTION]
The C++ Mathematical Expression Toolkit Library (ExprTk) is a simple
to use, easy to integrate and extremely efficient run-time
mathematical expression parsing and evaluation engine. The parsing
engine supports numerous forms of functional and logic processing
semantics and is easily extensible.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 01 - CAPABILITIES]
The ExprTk expression evaluator supports the following fundamental
arithmetic operations, functions and processes:
(00) Types: Scalar, Vector, String
(01) Basic operators: +, -, *, /, %, ^
(02) Assignment: :=, +=, -=, *=, /=, %=
(03) Equalities &
Inequalities: =, ==, <>, !=, <, <=, >, >=
(04) Logic operators: and, mand, mor, nand, nor, not, or, shl, shr,
xnor, xor, true, false
(05) Functions: abs, avg, ceil, clamp, equal, erf, erfc, exp,
expm1, floor, frac, log, log10, log1p, log2,
logn, max, min, mul, ncdf, not_equal, root,
round, roundn, sgn, sqrt, sum, swap, trunc
(06) Trigonometry: acos, acosh, asin, asinh, atan, atanh, atan2,
cos, cosh, cot, csc, sec, sin, sinc, sinh,
tan, tanh, hypot, rad2deg, deg2grad, deg2rad,
grad2deg
(07) Control
structures: if-then-else, ternary conditional, switch-case,
return-statement
(08) Loop statements: while, for, repeat-until, break, continue
(09) String
processing: in, like, ilike, concatenation
(10) Optimisations: constant-folding, simple strength reduction and
dead code elimination
(11) Runtime checks: vector bounds, string bounds, loop iteration,
execution-time bounds and compilation process
checkpointing, assert statements
(12) Calculus: numerical integration and differentiation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 02 - EXAMPLE EXPRESSIONS]
The following is a short listing of infix format based mathematical
expressions that can be parsed and evaluated using the ExprTk library.
(01) sqrt(1 - (3 / x^2))
(02) clamp(-1, sin(2 * pi * x) + cos(y / 2 * pi), +1)
(03) sin(2.34e-3 * x)
(04) if(((x[2] + 2) == 3) and ((y + 5) <= 9),1 + w, 2 / z)
(05) inrange(-2,m,+2) == if(({-2 <= m} and [m <= +2]),1,0)
(06) ({1/1}*[1/2]+(1/3))-{1/4}^[1/5]+(1/6)-({1/7}+[1/8]*(1/9))
(07) a * exp(2.2 / 3.3 * t) + c
(08) z := x + sin(2.567 * pi / y)
(09) u := 2.123 * {pi * z} / (w := x + cos(y / pi))
(10) 2x + 3y + 4z + 5w == 2 * x + 3 * y + 4 * z + 5 * w
(11) 3(x + y) / 2.9 + 1.234e+12 == 3 * (x + y) / 2.9 + 1.234e+12
(12) (x + y)3.3 + 1 / 4.5 == [x + y] * 3.3 + 1 / 4.5
(13) (x + y[i])z + 1.1 / 2.7 == (x + y[i]) * z + 1.1 / 2.7
(14) (sin(x / pi) cos(2y) + 1) == (sin(x / pi) * cos(2 * y) + 1)
(15) 75x^17 + 25.1x^5 - 35x^4 - 15.2x^3 + 40x^2 - 15.3x + 1
(16) (avg(x,y) <= x + y ? x - y : x * y) + 2.345 * pi / x
(17) while (x <= 100) { x -= 1; }
(18) x <= 'abc123' and (y in 'AString') or ('1x2y3z' != z)
(19) ((x + 'abc') like '*123*') or ('a123b' ilike y)
(20) sgn(+1.2^3.4z / -5.6y) <= {-7.8^9 / -10.11x }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 03 - COPYRIGHT NOTICE]
Free use of the C++ Mathematical Expression Toolkit Library is
permitted under the guidelines and in accordance with the most current
version of the MIT License.
(1) https://www.opensource.org/licenses/MIT
(2) SPDX-License-Identifier: MIT
(3) SPDX-FileCopyrightText : Copyright (C) 1999-2024 Arash Partow
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 04 - DOWNLOADS & UPDATES]
The most recent version of the C++ Mathematical Expression Toolkit
Library including all updates and tests can be found at the following
locations:
(1) Download: https://www.partow.net/programming/exprtk/index.html
(2) Mirror Repository: https://github.com/ArashPartow/exprtk
https://github.com/ArashPartow/exprtk-extras
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 05 - INSTALLATION]
The header file exprtk.hpp should be placed in a project or system
include path (e.g: /usr/include/).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 06 - COMPILATION]
The ExprTk package contains the ExprTk header, a set of simple
examples and a benchmark and unit test suite. The following is a list
of commands to build the various components:
(a) For a complete build: make clean all
(b) For a PGO build: make clean pgo
(c) To strip executables: make strip_bin
(d) Execute valgrind check: make valgrind_check
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 07 - COMPILER COMPATIBILITY]
ExprTk has been built error and warning free using the following set
of C++ compilers:
(*) GNU Compiler Collection (3.5+)
(*) Clang/LLVM (1.1+)
(*) Microsoft Visual Studio C++ Compiler (7.1+)
(*) Intel C++ Compiler (8.x+)
(*) AMD Optimizing C++ Compiler (1.2+)
(*) Nvidia C++ Compiler (19.x+)
(*) PGI C++ (10.x+)
(*) Circle C++ (circa: b81c37d2bb227c)
(*) IBM XL C/C++ (9.x+)
(*) C++ Builder (XE4+)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 08 - BUILT-IN OPERATIONS & FUNCTIONS]
(0) Arithmetic & Assignment Operators
+----------+---------------------------------------------------------+
| OPERATOR | DEFINITION |
+----------+---------------------------------------------------------+
| + | Addition between x and y. (eg: x + y) |
+----------+---------------------------------------------------------+
| - | Subtraction between x and y. (eg: x - y) |
+----------+---------------------------------------------------------+
| * | Multiplication between x and y. (eg: x * y) |
+----------+---------------------------------------------------------+
| / | Division between x and y. (eg: x / y) |
+----------+---------------------------------------------------------+
| % | Modulus of x with respect to y. (eg: x % y) |
+----------+---------------------------------------------------------+
| ^ | x to the power of y. (eg: x ^ y) |
+----------+---------------------------------------------------------+
| := | Assign the value of x to y. Where y is either a variable|
| | or vector type. (eg: y := x) |
+----------+---------------------------------------------------------+
| += | Increment x by the value of the expression on the right |
| | hand side. Where x is either a variable or vector type. |
| | (eg: x += abs(y - z)) |
+----------+---------------------------------------------------------+
| -= | Decrement x by the value of the expression on the right |
| | hand side. Where x is either a variable or vector type. |
| | (eg: x[i] -= abs(y + z)) |
+----------+---------------------------------------------------------+
| *= | Assign the multiplication of x by the value of the |
| | expression on the righthand side to x. Where x is either|
| | a variable or vector type. |
| | (eg: x *= abs(y / z)) |
+----------+---------------------------------------------------------+
| /= | Assign the division of x by the value of the expression |
| | on the right-hand side to x. Where x is either a |
| | variable or vector type. (eg: x[i + j] /= abs(y * z)) |
+----------+---------------------------------------------------------+
| %= | Assign x modulo the value of the expression on the right|
| | hand side to x. Where x is either a variable or vector |
| | type. (eg: x[2] %= y ^ 2) |
+----------+---------------------------------------------------------+
(1) Equalities & Inequalities
+----------+---------------------------------------------------------+
| OPERATOR | DEFINITION |
+----------+---------------------------------------------------------+
| == or = | True only if x is strictly equal to y. (eg: x == y) |
+----------+---------------------------------------------------------+
| <> or != | True only if x does not equal y. (eg: x <> y or x != y) |
+----------+---------------------------------------------------------+
| < | True only if x is less than y. (eg: x < y) |
+----------+---------------------------------------------------------+
| <= | True only if x is less than or equal to y. (eg: x <= y) |
+----------+---------------------------------------------------------+
| > | True only if x is greater than y. (eg: x > y) |
+----------+---------------------------------------------------------+
| >= | True only if x greater than or equal to y. (eg: x >= y) |
+----------+---------------------------------------------------------+
(2) Boolean Operations
+----------+---------------------------------------------------------+
| OPERATOR | DEFINITION |
+----------+---------------------------------------------------------+
| true | True state or any value other than zero (typically 1). |
+----------+---------------------------------------------------------+
| false | False state, value of exactly zero. |
+----------+---------------------------------------------------------+
| and | Logical AND, True only if x and y are both true. |
| | (eg: x and y) |
+----------+---------------------------------------------------------+
| mand | Multi-input logical AND, True only if all inputs are |
| | true. Left to right short-circuiting of expressions. |
| | (eg: mand(x > y, z < w, u or v, w and x)) |
+----------+---------------------------------------------------------+
| mor | Multi-input logical OR, True if at least one of the |
| | inputs are true. Left to right short-circuiting of |
| | expressions. (eg: mor(x > y, z < w, u or v, w and x)) |
+----------+---------------------------------------------------------+
| nand | Logical NAND, True only if either x or y is false. |
| | (eg: x nand y) |
+----------+---------------------------------------------------------+
| nor | Logical NOR, True only if the result of x or y is false |
| | (eg: x nor y) |
+----------+---------------------------------------------------------+
| not | Logical NOT, Negate the logical sense of the input. |
| | (eg: not(x and y) == x nand y) |
+----------+---------------------------------------------------------+
| or | Logical OR, True if either x or y is true. (eg: x or y) |
+----------+---------------------------------------------------------+
| xor | Logical XOR, True only if the logical states of x and y |
| | differ. (eg: x xor y) |
+----------+---------------------------------------------------------+
| xnor | Logical XNOR, True iff the biconditional of x and y is |
| | satisfied. (eg: x xnor y) |
+----------+---------------------------------------------------------+
| & | Similar to AND but with left to right expression short |
| | circuiting optimisation. (eg: (x & y) == (y and x)) |
+----------+---------------------------------------------------------+
| | | Similar to OR but with left to right expression short |
| | circuiting optimisation. (eg: (x | y) == (y or x)) |
+----------+---------------------------------------------------------+
(3) General Purpose Functions
+----------+---------------------------------------------------------+
| FUNCTION | DEFINITION |
+----------+---------------------------------------------------------+
| abs | Absolute value of x. (eg: abs(x)) |
+----------+---------------------------------------------------------+
| avg | Average of all the inputs. |
| | (eg: avg(x,y,z,w,u,v) == (x + y + z + w + u + v) / 6) |
+----------+---------------------------------------------------------+
| ceil | Smallest integer that is greater than or equal to x. |
+----------+---------------------------------------------------------+
| clamp | Clamp x in range between r0 and r1, where r0 < r1. |
| | (eg: clamp(r0,x,r1)) |
+----------+---------------------------------------------------------+
| equal | Equality test between x and y using normalised epsilon |
+----------+---------------------------------------------------------+
| erf | Error function of x. (eg: erf(x)) |
+----------+---------------------------------------------------------+
| erfc | Complimentary error function of x. (eg: erfc(x)) |
+----------+---------------------------------------------------------+
| exp | e to the power of x. (eg: exp(x)) |
+----------+---------------------------------------------------------+
| expm1 | e to the power of x minus 1, where x is very small. |
| | (eg: expm1(x)) |
+----------+---------------------------------------------------------+
| floor | Largest integer that is less than or equal to x. |
| | (eg: floor(x)) |
+----------+---------------------------------------------------------+
| frac | Fractional portion of x. (eg: frac(x)) |
+----------+---------------------------------------------------------+
| hypot | Hypotenuse of x and y (eg: hypot(x,y) = sqrt(x*x + y*y))|
+----------+---------------------------------------------------------+
| iclamp | Inverse-clamp x outside of the range r0 and r1. Where |
| | r0 < r1. If x is within the range it will snap to the |
| | closest bound. (eg: iclamp(r0,x,r1) |
+----------+---------------------------------------------------------+
| inrange | In-range returns 'true' when x is within the range r0 |
| | and r1. Where r0 < r1. (eg: inrange(r0,x,r1) |
+----------+---------------------------------------------------------+
| log | Natural logarithm of x. (eg: log(x)) |
+----------+---------------------------------------------------------+
| log10 | Base 10 logarithm of x. (eg: log10(x)) |
+----------+---------------------------------------------------------+
| log1p | Natural logarithm of 1 + x, where x is very small. |
| | (eg: log1p(x)) |
+----------+---------------------------------------------------------+
| log2 | Base 2 logarithm of x. (eg: log2(x)) |
+----------+---------------------------------------------------------+
| logn | Base N logarithm of x. where n is a positive integer. |
| | (eg: logn(x,8)) |
+----------+---------------------------------------------------------+
| max | Largest value of all the inputs. (eg: max(x,y,z,w,u,v)) |
+----------+---------------------------------------------------------+
| min | Smallest value of all the inputs. (eg: min(x,y,z,w,u)) |
+----------+---------------------------------------------------------+
| mul | Product of all the inputs. |
| | (eg: mul(x,y,z,w,u,v,t) == (x * y * z * w * u * v * t)) |
+----------+---------------------------------------------------------+
| ncdf | Normal cumulative distribution function. (eg: ncdf(x)) |
+----------+---------------------------------------------------------+
| not_equal| Not-equal test between x and y using normalised epsilon |
+----------+---------------------------------------------------------+
| pow | x to the power of y. (eg: pow(x,y) == x ^ y) |
+----------+---------------------------------------------------------+
| root | Nth-Root of x. where n is a positive integer. |
| | (eg: root(x,3) == x^(1/3)) |
+----------+---------------------------------------------------------+
| round | Round x to the nearest integer. (eg: round(x)) |
+----------+---------------------------------------------------------+
| roundn | Round x to n decimal places (eg: roundn(x,3)) |
| | where n > 0 and is an integer. |
| | (eg: roundn(1.2345678,4) == 1.2346) |
+----------+---------------------------------------------------------+
| sgn | Sign of x, -1 where x < 0, +1 where x > 0, else zero. |
| | (eg: sgn(x)) |
+----------+---------------------------------------------------------+
| sqrt | Square root of x, where x >= 0. (eg: sqrt(x)) |
+----------+---------------------------------------------------------+
| sum | Sum of all the inputs. |
| | (eg: sum(x,y,z,w,u,v,t) == (x + y + z + w + u + v + t)) |
+----------+---------------------------------------------------------+
| swap | Swap the values of the variables x and y and return the |
| <=> | current value of y. (eg: swap(x,y) or x <=> y) |
+----------+---------------------------------------------------------+
| trunc | Integer portion of x. (eg: trunc(x)) |
+----------+---------------------------------------------------------+
(4) Trigonometry Functions
+----------+---------------------------------------------------------+
| FUNCTION | DEFINITION |
+----------+---------------------------------------------------------+
| acos | Arc cosine of x expressed in radians. Interval [-1,+1] |
| | (eg: acos(x)) |
+----------+---------------------------------------------------------+
| acosh | Inverse hyperbolic cosine of x expressed in radians. |
| | (eg: acosh(x)) |
+----------+---------------------------------------------------------+
| asin | Arc sine of x expressed in radians. Interval [-1,+1] |
| | (eg: asin(x)) |
+----------+---------------------------------------------------------+
| asinh | Inverse hyperbolic sine of x expressed in radians. |
| | (eg: asinh(x)) |
+----------+---------------------------------------------------------+
| atan | Arc tangent of x expressed in radians. Interval [-1,+1] |
| | (eg: atan(x)) |
+----------+---------------------------------------------------------+
| atan2 | Arc tangent of (x / y) expressed in radians. [-pi,+pi] |
| | eg: atan2(x,y) |
+----------+---------------------------------------------------------+
| atanh | Inverse hyperbolic tangent of x expressed in radians. |
| | (eg: atanh(x)) |
+----------+---------------------------------------------------------+
| cos | Cosine of x. (eg: cos(x)) |
+----------+---------------------------------------------------------+
| cosh | Hyperbolic cosine of x. (eg: cosh(x)) |
+----------+---------------------------------------------------------+
| cot | Cotangent of x. (eg: cot(x)) |
+----------+---------------------------------------------------------+
| csc | Cosecant of x. (eg: csc(x)) |
+----------+---------------------------------------------------------+
| sec | Secant of x. (eg: sec(x)) |
+----------+---------------------------------------------------------+
| sin | Sine of x. (eg: sin(x)) |
+----------+---------------------------------------------------------+
| sinc | Sine cardinal of x. (eg: sinc(x)) |
+----------+---------------------------------------------------------+
| sinh | Hyperbolic sine of x. (eg: sinh(x)) |
+----------+---------------------------------------------------------+
| tan | Tangent of x. (eg: tan(x)) |
+----------+---------------------------------------------------------+
| tanh | Hyperbolic tangent of x. (eg: tanh(x)) |
+----------+---------------------------------------------------------+
| deg2rad | Convert x from degrees to radians. (eg: deg2rad(x)) |
+----------+---------------------------------------------------------+
| deg2grad | Convert x from degrees to gradians. (eg: deg2grad(x)) |
+----------+---------------------------------------------------------+
| rad2deg | Convert x from radians to degrees. (eg: rad2deg(x)) |
+----------+---------------------------------------------------------+
| grad2deg | Convert x from gradians to degrees. (eg: grad2deg(x)) |
+----------+---------------------------------------------------------+
(5) String Processing
+----------+---------------------------------------------------------+
| FUNCTION | DEFINITION |
+----------+---------------------------------------------------------+
| = , == | All common equality/inequality operators are applicable |
| !=, <> | to strings and are applied in a case sensitive manner. |
| <=, >= | In the following example x, y and z are of type string. |
| < , > | (eg: not((x <= 'AbC') and ('1x2y3z' <> y)) or (z == x) |
+----------+---------------------------------------------------------+
| in | True only if x is a substring of y. |
| | (eg: x in y or 'abc' in 'abcdefgh') |
+----------+---------------------------------------------------------+
| like | True only if the string x matches the pattern y. |
| | Available wildcard characters are '*' and '?' denoting |
| | zero or more and zero or one matches respectively. |
| | (eg: x like y or 'abcdefgh' like 'a?d*h') |
+----------+---------------------------------------------------------+
| ilike | True only if the string x matches the pattern y in a |
| | case insensitive manner. Available wildcard characters |
| | are '*' and '?' denoting zero or more and zero or one |
| | matches respectively. |
| | (eg: x ilike y or 'a1B2c3D4e5F6g7H' ilike 'a?d*h') |
+----------+---------------------------------------------------------+
| [r0:r1] | The closed interval[r0,r1] of the specified string. |
| | eg: Given a string x with a value of 'abcdefgh' then: |
| | 1. x[1:4] == 'bcde' |
| | 2. x[ :4] == x[:8 / 2] == 'abcde' |
| | 3. x[2 + 1: ] == x[3:] =='defgh' |
| | 4. x[ : ] == x[:] == 'abcdefgh' |
| | 5. x[4/2:3+1] == x[2:4] == 'cde' |
| | |
| | Note: Both r0 and r1 are assumed to be integers, where |
| | r0 <= r1. They may also be the result of an expression, |
| | in the event they have fractional components truncation |
| | shall be performed. (eg: 1.67 --> 1) |
+----------+---------------------------------------------------------+
| := | Assign the value of x to y. Where y is a mutable string |
| | or string range and x is either a string or a string |
| | range. eg: |
| | 1. y := x |
| | 2. y := 'abc' |
| | 3. y := x[:i + j] |
| | 4. y := '0123456789'[2:7] |
| | 5. y := '0123456789'[2i + 1:7] |
| | 6. y := (x := '0123456789'[2:7]) |
| | 7. y[i:j] := x |
| | 8. y[i:j] := (x + 'abcdefg'[8 / 4:5])[m:n] |
| | |
| | Note: For options 7 and 8 the shorter of the two ranges |
| | will denote the number characters that are to be copied.|
+----------+---------------------------------------------------------+
| + | Concatenation of x and y. Where x and y are strings or |
| | string ranges. eg |
| | 1. x + y |
| | 2. x + 'abc' |
| | 3. x + y[:i + j] |
| | 4. x[i:j] + y[2:3] + '0123456789'[2:7] |
| | 5. 'abc' + x + y |
| | 6. 'abc' + '1234567' |
| | 7. (x + 'a1B2c3D4' + y)[i:2j] |
+----------+---------------------------------------------------------+
| += | Append to x the value of y. Where x is a mutable string |
| | and y is either a string or a string range. eg: |
| | 1. x += y |
| | 2. x += 'abc' |
| | 3. x += y[:i + j] + 'abc' |
| | 4. x += '0123456789'[2:7] |
+----------+---------------------------------------------------------+
| <=> | Swap the values of x and y. Where x and y are mutable |
| | strings. (eg: x <=> y) |
+----------+---------------------------------------------------------+
| [] | The string size operator returns the size of the string |
| | being actioned. |
| | eg: |
| | 1. 'abc'[] == 3 |
| | 2. var max_str_length := max(s0[], s1[], s2[], s3[]) |
| | 3. ('abc' + 'd')[] == 6 |
| | 4. (('abc' + 'xyz')[1:4])[] == 4 |
+----------+---------------------------------------------------------+
(6) Control Structures
+----------+---------------------------------------------------------+
|STRUCTURE | DEFINITION |
+----------+---------------------------------------------------------+
| if | If x is true then return y else return z. |
| | eg: |
| | 1. if (x, y, z) |
| | 2. if ((x + 1) > 2y, z + 1, w / v) |
| | 3. if (x > y) z; |
| | 4. if (x <= 2*y) { z + w }; |
+----------+---------------------------------------------------------+
| if-else | The if-else/else-if statement. Subject to the condition |
| | branch the statement will return either the value of the|
| | consequent or the alternative branch. |
| | eg: |
| | 1. if (x > y) z; else w; |
| | 2. if (x > y) z; else if (w != u) v; |
| | 3. if (x < y) { z; w + 1; } else u; |
| | 4. if ((x != y) and (z > w)) |
| | { |
| | y := sin(x) / u; |
| | z := w + 1; |
| | } |
| | else if (x > (z + 1)) |
| | { |
| | w := abs (x - y) + z; |
| | u := (x + 1) > 2y ? 2u : 3u; |
| | } |
+----------+---------------------------------------------------------+
| switch | The first true case condition that is encountered will |
| | determine the result of the switch. If none of the case |
| | conditions hold true, the default action is assumed as |
| | the final return value. This is sometimes also known as |
| | a multi-way branch mechanism. |
| | eg: |
| | switch |
| | { |
| | case x > (y + z) : 2 * x / abs(y - z); |
| | case x < 3 : sin(x + y); |
| | default : 1 + x; |
| | } |
+----------+---------------------------------------------------------+
| while | The structure will repeatedly evaluate the internal |
| | statement(s) 'while' the condition is true. The final |
| | statement in the final iteration shall be used as the |
| | return value of the loop. |
| | eg: |
| | while ((x -= 1) > 0) |
| | { |
| | y := x + z; |
| | w := u + y; |
| | } |
+----------+---------------------------------------------------------+
| repeat/ | The structure will repeatedly evaluate the internal |
| until | statement(s) 'until' the condition is true. The final |
| | statement in the final iteration shall be used as the |
| | return value of the loop. |
| | eg: |
| | repeat |
| | y := x + z; |
| | w := u + y; |
| | until ((x += 1) > 100) |
+----------+---------------------------------------------------------+
| for | The structure will repeatedly evaluate the internal |
| | statement(s) while the condition is true. On each loop |
| | iteration, an 'incrementing' expression is evaluated. |
| | The conditional is mandatory whereas the initialiser |
| | and incrementing expressions are optional. |
| | eg: |
| | for (var x := 0; (x < n) and (x != y); x += 1) |
| | { |
| | y := y + x / 2 - z; |
| | w := u + y; |
| | } |
+----------+---------------------------------------------------------+
| break | Break terminates the execution of the nearest enclosed |
| break[] | loop, allowing for the execution to continue on external|
| | to the loop. The default break statement will set the |
| | return value of the loop to NaN, where as the return |
| | based form will set the value to that of the break |
| | expression. |
| | eg: |
| | while ((i += 1) < 10) |
| | { |
| | if (i < 5) |
| | j -= i + 2; |
| | else if (i % 2 == 0) |
| | break; |
| | else |
| | break[2i + 3]; |
| | } |
+----------+---------------------------------------------------------+
| continue | Continue results in the remaining portion of the nearest|
| | enclosing loop body to be skipped. |
| | eg: |
| | for (var i := 0; i < 10; i += 1) |
| | { |
| | if (i < 5) |
| | continue; |
| | j -= i + 2; |
| | } |
+----------+---------------------------------------------------------+
| return | Return immediately from within the current expression. |
| | With the option of passing back a variable number of |
| | values (scalar, vector or string). eg: |
| | 1. return [1]; |
| | 2. return [x, 'abx']; |
| | 3. return [x, x + y,'abx']; |
| | 4. return []; |
| | 5. if (x < y) |
| | return [x, x - y, 'result-set1', 123.456]; |
| | else |
| | return [y, x + y, 'result-set2']; |
+----------+---------------------------------------------------------+
| ?: | Ternary conditional statement, similar to that of the |
| | above denoted if-statement. |
| | eg: |
| | 1. x ? y : z |
| | 2. x + 1 > 2y ? z + 1 : (w / v) |
| | 3. min(x,y) > z ? (x < y + 1) ? x : y : (w * v) |
+----------+---------------------------------------------------------+
| ~ | Evaluate each sub-expression, then return as the result |
| | the value of the last sub-expression. This is sometimes |
| | known as multiple sequence point evaluation. |
| | eg: |
| | ~(i := x + 1, j := y / z, k := sin(w/u)) == (sin(w/u))) |
| | ~{i := x + 1; j := y / z; k := sin(w/u)} == (sin(w/u))) |
+----------+---------------------------------------------------------+
| [*] | Evaluate any consequent for which its case statement is |
| | true. The return value will be either zero or the result|
| | of the last consequent to have been evaluated. |
| | eg: |
| | [*] |
| | { |
| | case (x + 1) > (y - 2) : x := z / 2 + sin(y / pi); |
| | case (x + 2) < abs(y + 3) : w / 4 + min(5y,9); |
| | case (x + 3) == (y * 4) : y := abs(z / 6) + 7y; |
| | } |
+----------+---------------------------------------------------------+
| [] | The vector size operator returns the size of the vector |
| | being actioned. |
| | eg: |
| | 1. v[] |
| | 2. max_size := max(v0[],v1[],v2[],v3[]) |
+----------+---------------------------------------------------------+
Note01: In the tables above, the symbols x, y, z, w, u and v where
appropriate may represent any of one the following:
1. Literal numeric/string value
2. A variable
3. A vector element
4. A vector
5. A string
6. An expression comprised of [1], [2] or [3] (eg: 2 + x / vec[3])
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 09 - FUNDAMENTAL TYPES]
ExprTk supports three fundamental types which can be used freely in
expressions. The types are as follows:
(1) Scalar
(2) Vector
(3) String
(1) Scalar Type
The scalar type is a singular numeric value. The underlying type is
that used to specialise the ExprTk components (float, double, long
double, MPFR et al).
(2) Vector Type
The vector type is a fixed size sequence of contiguous scalar values.
A vector can be indexed resulting in a scalar value. Operations
between a vector and scalar will result in a vector with a size equal
to that of the original vector, whereas operations between vectors
will result in a vector of size equal to that of the smaller of the
two. In both mentioned cases, the operations will occur element-wise.
(3) String Type
The string type is a variable length sequence of 8-bit chars. Strings
can be assigned and concatenated to one another, they can also be
manipulated via sub-ranges using the range definition syntax. Strings
however can not interact with scalar or vector types.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 10 - COMPONENTS]
There are three primary components, that are specialised upon a given
numeric type, which make up the core of ExprTk. The components are as
follows:
(1) Symbol Table exprtk::symbol_table
(2) Expression exprtk::expression
(3) Parser exprtk::parser
(1) Symbol Table
A structure that is used to store references to variables, constants
and functions that are to be used within expressions. Furthermore in
the context of composited recursive functions the symbol table can
also be thought of as a simple representation of a stack specific for
the expression(s) that reference it. The following is a list of the
types a symbol table can handle:
(a) Numeric variables
(b) Numeric constants
(c) Numeric vector elements
(d) String variables
(e) String constants
(f) Functions
(g) Vararg functions
During the compilation process if an expression is found to require
any of the elements noted above, the expression's associated
symbol_table will be queried for the element and if present a
reference to the element will be embedded within the expression's AST.
This allows for the original element to be modified independently of
the expression instance and to also allow the expression to be
evaluated using the current value of the element.
The example below demonstrates the relationship between variables,
symbol_table and expression. Note the variables are modified as they
normally would in a program, and when the expression is evaluated the
current values assigned to the variables shall be used.
typedef exprtk::symbol_table symbol_table_t;
typedef exprtk::expression expression_t;
typedef exprtk::parser parser_t;
double x = 0;
double y = 0;
symbol_table_t symbol_table;
expression_t expression;
parser_t parser;
std::string expression_string = "x * y + 3";
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
expression.register_symbol_table(symbol_table);
parser.compile(expression_string,expression);
x = 1.0;
y = 2.0;
expression.value(); // 1 * 2 + 3
x = 3.7;
expression.value(); // 3.7 * 2 + 3
y = -9.0;
expression.value(); // 3.7 * -9 + 3
// 'x * -9 + 3' for x in range of [0,100) in steps of 0.0001
for (x = 0.0; x < 100.0; x += 0.0001)
{
expression.value(); // x * -9 + 3
}
Note02: Any variable reference provided to a given symbol_table
instance, must have a lifetime at least as long as the lifetime of the
symbol_table instance. In the event the variable reference is
invalidated before the symbol_table or any dependent expression
instances have been destructed, then any associated expression
evaluations or variable referencing via the symbol_table instance will
result in undefined behaviour.
The following bit of code instantiates a symbol_table and expression
instance, then proceeds to demonstrate various ways in which
references to variables can be added to the symbol_table, and how
those references are subsequently invalidated resulting in various
forms of undefined behaviour.
typedef exprtk::symbol_table symbol_table_t;
typedef exprtk::expression expression_t;
symbol_table_t symbol_table;
expression_t expression;
std::deque y {1.1, 2.2, 3.3};
std::vector z {4.4, 5.5, 6.6};
double* w = new double(123.456);
{
double x = 123.4567;
symbol_table.add_variable("x", x);
} // Reference to variable x has been invalidated
symbol_table.add_variable("y", y.back());
y.pop_back(); // Reference to variable y has been invalidated
symbol_table.add_variable("z", z.front());
z.erase(z.begin());
// Reference to variable z has been invalidated
symbol_table.add_variable("w", *w);
delete w; // Reference to variable w has been invalidated
const std::string expression_string = "x + y / z * w";
// Compilation of expression will succeed
parser.compile(expression_string,expression);
expression.value();
// Evaluation will result in undefined behaviour
// due to 'x' and 'w' having been destroyed.
symbol_table.get_variable("x")->ref() = 135.791;
// Assignment will result in undefined behaviour
A compiled expression that references variables from a symbol_table is
dependent on that symbol_table instance and the variables it holds
being valid.
typedef exprtk::symbol_table symbol_table_t;
typedef exprtk::expression expression_t;
symbol_table_t symbol_table;
expression_t expression;
double x = 123.456;
symbol_table.add_variable("x", x);
const std::string expression_string = "(x + 1) / 2";
// Compilation of the expression will succeed
parser.compile(expression_string,expression);
// Clear all variables from symbol_table
symbol_table.clear();
expression.value();
// Evaluation will result in undefined behaviour
// because the reference to 'x' having been destroyed
// during the clearing of the symbol_table
In the above example, an expression is compiled that references
variable "x". As part of the compilation process the node holding the
variable "x" is obtained from the symbol_table and embedded in the AST
of the expression - in short the expression is now referencing the
node that holds the variable "x". The following diagram depicts the
dependencies between the variable x, the symbol table and the
expression:
+--[Symbol Table]--+
| |
| +- ------+ |
| | x-node | |
| +-----A--+ | +--[Expression]--+
+---|---|----------+ | +---------+ |
v | | | A.S.T | |
| +--------<--------[.] | |
+-----+ | +---------+ |
| +----------------+
+-v-[variable]---+
| x: 123.456 |
+----------------+
When the clear method is called on the symbol table the X-Node is
destroyed, so now the expression is referencing a node that has been
destroyed. From this point onwards any attempts to reference the
expression instance will result in undefined behaviour. Simply put the
above example violates the requirement that the lifetime of any
objects referenced by expressions should exceed the lifetime of the
expression instance.
typedef exprtk::symbol_table symbol_table_t;
typedef exprtk::expression expression_t;
symbol_table_t symbol_table;
expression_t expression;
double x = 123.456;
symbol_table.add_variable("x", x);
const std::string expression_string = "(x + 1) / 2";
// Compilation of the expression will succeed
parser.compile(expression_string,expression);
expression.value();
// Release the expression and its dependents
expression.release();
// Clear all variables from symbol_table
symbol_table.clear();
expression.value();
// Will return null_node value of NaN
In the above example the expression is released before the associated
symbol_table is cleared of its variables, which resolves the undefined
behaviour issue noted in the previous example.
Note03: It is possible to register multiple symbol_tables with a
single expression object. In the event an expression has multiple
symbol tables, and where there exists conflicts between symbols, the
compilation stage will resolve the conflicts based on the order of
registration of the symbol_tables to the expression. For a more
expansive discussion please review section [17 - Hierarchies Of Symbol
Tables]
typedef exprtk::symbol_table symbol_table_t;
typedef exprtk::expression expression_t;
typedef exprtk::parser parser_t;
symbol_table_t symbol_table0;
symbol_table_t symbol_table1;
expression_t expression;
parser_t parser;
double x0 = 123.0;
double x1 = 678.0;
std::string expression_string = "x + 1";
symbol_table0.add_variable("x",x0);
symbol_table1.add_variable("x",x1);
expression.register_symbol_table(symbol_table0);
expression.register_symbol_table(symbol_table1);
parser.compile(expression_string,expression);
expression.value(); // 123 + 1
The symbol table supports adding references to external instances of
types that can be accessed within expressions via the following
methods:
1. bool add_variable (const std::string& name, scalar_t& )
2. bool add_constant (const std::string& name, const scalar_t& )
3. bool add_stringvar (const std::string& name, std::string& )
4. bool add_vector (const std::string& name, vector_type& )
5. bool add_function (const std::string& name, function_t& )
6. bool create_stringvar(const std::string& name,const std::string&)
7. bool create_variable (const std::string& name, const T& )
Note04: The 'vector' type must be comprised from a contiguous array of
scalars with a size that is larger than zero. The vector type itself
can be any one of the following:
1. std::vector
2. scalar_t(&v)[N]
3. scalar_t* and array size
4. exprtk::vector_view
When registering a variable, vector, string or function with an
instance of a symbol_table, the call to 'add_...' may fail and return
a false result due to one or more of the following reasons:
1. Variable name contains invalid characters or is ill-formed
2. Variable name conflicts with a reserved word (eg: 'while')
3. Variable name conflicts with a previously registered variable
4. A vector of size (length) zero is being registered
5. A free function exceeding fifteen parameters is being registered
6. The symbol_table instance is in an invalid state
Note05: The symbol_table has a method called clear, which when invoked
will clear all variables, vectors, strings and functions registered
with the symbol_table instance. If this method is to be called, then
one must make sure that all compiled expression instances that
reference variables belonging to that symbol_table instance are
released (aka call release method on expression) before calling the
clear method on the symbol_table instance, otherwise undefined
behaviours will occur.
A further property of symbol tables is that they can be classified at
instantiation as either being mutable (by default) or immutable. This
property determines if variables, vectors or strings registered with
the symbol table can undergo modifications within expressions that
reference them. The following demonstrates construction of an
immutable symbol table instance:
symbol_table_t immutable_symbol_table
(symbol_table_t::symtab_mutability_type::e_immutable);
When a symbol table, that has been constructed as being immutable, is
registered with an expression, any statements in the expression string
that modify the variables that are managed by the immutable symbol
table will result in a compilation error. The operations that trigger
the mutability constraint are the following assignment operators:
1. Assignment: :=
2. Assign operation: +=, -=, *=, /= , %=
const std::string expression_str = "x += x + 123.456";
symbol_table_t immutable_symbol_table
(symbol_table_t::symtab_mutability_type::e_immutable);
T x = 0.0;
immutable_symbol_table.add_variable("x" , x);
expression_t expression;
expression.register_symbol_table(immutable_symbol_table);
parser_t parser;
parser.compile(expression_str, expression);
// Compile error because of assignment to variable x
In the above example, variable x is registered to an immutable symbol
table, making it an immutable variable within the context of any
expressions that reference it. The expression string being compiled
uses the addition assignment operator which will modify the value of
variable x. The compilation process detects this semantic violation
and proceeds to halt compilation and return the appropriate error.
One of the main reasons for this functionality is that, one may want
the immutability properties that come with constness of a variable
such as scalars, vectors and strings, but not necessarily the
accompanying compile time const-folding optimisations, that would
result in the value of the variables being retrieved only once at
compile time, causing external updates to the variables to not be part
of the expression evaluation.
symbol_table_t immutable_symbol_table
(symbol_table_t::symtab_mutability_type::e_immutable);
T x = 0.0;
const std::string expression_str = "x + (y + y)";
immutable_symbol_table.add_variable("x" , x );
immutable_symbol_table.add_constant("y" , 123.0);
expression_t expression;
expression.register_symbol_table(immutable_symbol_table);
parser_t parser;
parser.compile(expression_str, expression);
for (; x < 10.0; ++x)
{
const auto expected_value = x + (123.0 + 123.0);
const auto result_value = expression.value();
assert(expression.value() != expected_value);
}
In the above example, there are two variables X and Y. Where Y is a
constant and X is a normal variable. Both are registered with a symbol
table that is immutable. The expression when compiled will result in
the "(y + y)" part being const-folded at compile time to the literal
value of 246. Whereas the current value of X, being updated via the
for-loop, externally to the expression and the symbol table shall be
observable to the expression upon each evaluation.
(2) Expression
A structure that holds an Abstract Syntax Tree or AST for a specified
expression and is used to evaluate said expression. Evaluation of the
expression is accomplished by performing a post-order traversal of the
AST. If a compiled Expression uses variables or user defined
functions, it will have an associated Symbol Table, which will contain
references to said variables, functions or strings. An example AST
structure for the denoted expression is as follows:
Expression: z := (x + y^-2.345) * sin(pi / min(w - 7.3,v))
[Root]
|
[Assignment]
________/ \_____
/ \
Variable(z) [Multiplication]
____________/ \___________
/ \
/ [Unary-Function(sin)]
[Addition] |
____/ \____ [Division]
/ \ ___/ \___
Variable(x) [Exponentiation] / \
______/ \______ Constant(pi) [Binary-Function(min)]
/ \ ____/ \___
Variable(y) [Negation] / \
| / Variable(v)
Constant(2.345) /
/
[Subtraction]
____/ \____
/ \
Variable(w) Constant(7.3)
The above denoted AST shall be evaluated in the following order:
(01) Load Variable (z) (10) Load Constant (7.3)
(02) Load Variable (x) (11) Subtraction (09 & 10)
(03) Load Variable (y) (12) Load Variable (v)
(04) Load Constant (2.345) (13) Min (11 & 12)
(05) Negation (04) (14) Division (08 & 13)
(06) Exponentiation (03 & 05) (15) Sin (14)
(07) Addition (02 & 06) (16) Multiplication (07 & 15)
(08) Load Constant (pi) (17) Assignment (01 & 16)
(09) Load Variable (w)
Generally an expression in ExprTk can be thought of as a free function
similar to those found in imperative languages. This form of pseudo
function will have a name, it may have a set of one or more inputs and
will return at least one value as its result. Furthermore the function
when invoked, may cause a side-effect that changes the state of the
host program.
As an example the following is a pseudo-code definition of a free
function that performs a computation taking four inputs, modifying one
of them and returning a value based on some arbitrary calculation:
ResultType foo(InputType x, InputType y, InputType z, InputType w)
{
w = 2 * x^y + z; // Side-Effect
return abs(x - y) / z; // Return Result
}
Given the above definition the following is a functionally equivalent
version using ExprTk:
const std::string foo_str =
" w := 2 * x^y + z; "
" abs(x - y) / z; ";
T x, y, z, w;
symbol_table_t symbol_table;
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
symbol_table.add_variable("z",z);
symbol_table.add_variable("w",w);
expression_t foo;
foo.register_symbol_table(symbol_table);
parser_t parser;
if (!parser.compile(foo_str,foo))
{
// Error in expression...
return;
}
T result = foo.value();
(3) Parser
A component which takes as input a string representation of an
expression and attempts to compile said input with the result being an
instance of Expression. If an error is encountered during the
compilation process, the parser will stop compiling and return an
error status code, with a more detailed description of the error(s)
and its location within the input provided by the 'get_error'
interface.
Note06: The exprtk::expression and exprtk::symbol_table components are
reference counted entities. Copy constructing or assigning to or from
either component will result in a shallow copy and a reference count
increment, rather than a complete replication. Furthermore the
expression and symbol_table components being Default-Constructible,
Copy-Constructible and Copy-Assignable make them compatible with
various C++ standard library containers and adaptors such as
std::vector, std::map, std::stack etc.
The following is an example of two unique expressions, after having
been instantiated and compiled, one expression is assigned to the
other. The diagrams depict their initial and post assignment states,
including which control block each expression references and their
associated reference counts.
exprtk::expression e0; // constructed expression, eg: x + 1
exprtk::expression e1; // constructed expression, eg: 2z + y
+-----[ e0 cntrl block]----+ +-----[ e1 cntrl block]-----+
| 1. Expression Node 'x+1' | | 1. Expression Node '2z+y' |
| 2. Ref Count: 1 |<-+ | 2. Ref Count: 1 |<-+
+--------------------------+ | +---------------------------+ |
| |
+--[ e0 expression]--+ | +--[ e1 expression]--+ |
| 1. Reference to ]------+ | 1. Reference to ]-------+
| e0 Control Block | | e1 Control Block |
+--------------------+ +--------------------+
e0 = e1; // e0 and e1 are now 2z+y
+-----[ e1 cntrl block]-----+
| 1. Expression Node '2z+y' |
+----------->| 2. Ref Count: 2 |<----------+
| +---------------------------+ |
| |
| +--[ e0 expression]--+ +--[ e1 expression]--+ |
+---[ 1. Reference to | | 1. Reference to ]---+
| e1 Control Block | | e1 Control Block |
+--------------------+ +--------------------+
The reason for the above complexity and restrictions of deep copies
for the expression and symbol_table components is because expressions
may include user defined variables or functions. These are embedded as
references into the expression's AST. When copying an expression, said
references need to also be copied. If the references are blindly
copied, it will then result in two or more identical expressions
utilising the exact same references for variables. This obviously is
not the default assumed scenario and will give rise to non-obvious
behaviours when using the expressions in various contexts such as
multi-threading et al.
The prescribed method for cloning an expression is to compile it from
its string form. Doing so will allow the 'user' to properly consider
the exact source of user defined variables and functions.
Note07: The exprtk::parser is a non-copyable and non-thread safe
component, and should only be shared via either a reference, a shared
pointer or a std::ref mechanism, and considerations relating to
synchronisation taken into account where appropriate. The parser
represents an object factory, specifically a factory of expressions,
and generally should not be instantiated solely on a per expression
compilation basis.
The following diagram and example depicts the flow of data and
operations for compiling multiple expressions via the parser and
inserting the newly minted exprtk::expression instances into a
std::vector.
+----[exprtk::parser]---+
| Expression Factory |
| parser_t::compile(...)|
+--> ~.~.~.~.~.~.~.~.~.~ ->--+
| +-----------------------+ |
Expressions in | | Expressions as
string form ^ V exprtk::expression
| | instances
[s0:'x+1']--->--+ | | +-[e0: x+1]
| | | |
[s1:'2z+y']-->--+--+ +->+-[e1: 2z+y]
| |
[s2:'sin(k+w)']-+ +-[e2: sin(k+w)]
const std::string expression_str[3] =
{
"x + 1",
"2x + y",
"sin(k + w)"
};
std::vector expression_list;
parser_t parser;
expression_t expression;
symbol_table_t symbol_table;
expression.register_symbol_table(symbol_table);
for (std::size_t i = 0; i < 3; ++i)
{
if (parser.compile(expression_str[i],expression))
{
expression_list.push_back(expression);
}
else
std::cout << "Error in " << expression_str[i] << "\n";
}
for (auto& e : expression_list)
{
e.value();
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 11 - COMPILATION OPTIONS]
The exprtk::parser when being instantiated takes as input a set of
options to be used during the compilation process of expressions.
An example instantiation of exprtk::parser where only the joiner,
commutative and strength reduction options are enabled is as follows:
typedef exprtk::parser::settings_t settings_t;
const std::size_t compile_options =
settings_t::e_joiner +
settings_t::e_commutative_check +
settings_t::e_strength_reduction;
parser_t parser(compile_options);
Currently eight types of compile time options are supported, and
enabled by default. The options and their explanations are as follows:
(1) Replacer
(2) Joiner
(3) Numeric Check
(4) Bracket Check
(5) Sequence Check
(6) Commutative Check
(7) Strength Reduction Check
(8) Stack And Node Depth Check
(9) Vector Size Check
(1) Replacer (e_replacer)
Enable replacement of specific tokens with other tokens. For example
the token "true" of type symbol shall be replaced with the numeric
token of value one.
(a) (x < y) == true ---> (x < y) == 1
(b) false == (x > y) ---> 0 == (x > y)
(2) Joiner (e_joiner)
Enable joining of multi-character operators that may have been
incorrectly disjoint in the string representation of the specified
expression. For example the consecutive tokens of ">" "=" will become
">=" representing the "greater than or equal to" operator. If not
properly resolved the original form will cause a compilation error.
The following is a listing of the scenarios that the joiner can
handle:
(a) '>' '=' ---> '>=' (gte)
(b) '<' '=' ---> '<=' (lte)
(c) '=' '=' ---> '==' (equal)
(d) '!' '=' ---> '!=' (not-equal)
(e) '<' '>' ---> '<>' (not-equal)
(f) ':' '=' ---> ':=' (assignment)
(g) '+' '=' ---> '+=' (addition assignment)
(h) '-' '=' ---> '-=' (subtraction assignment)
(i) '*' '=' ---> '*=' (multiplication assignment)
(j) '/' '=' ---> '/=' (division assignment)
(k) '%' '=' ---> '%=' (modulo assignment)
(l) '+' '-' ---> '-' (subtraction)
(m) '-' '+' ---> '-' (subtraction)
(n) '-' '-' ---> '+' (addition)
(o) '<=' '>' ---> '<=>' (swap)
An example of the transformation that takes place is as follows:
(a) (x > = y) and (z ! = w) ---> (x >= y) and (z != w)
(3) Numeric Check (e_numeric_check)
Enable validation of tokens representing numeric types so as to catch
any errors prior to the costly process of the main compilation step
commencing.
(4) Bracket Check (e_bracket_check)
Enable the check for validating the ordering of brackets in the
specified expression.
(5) Sequence Check (e_sequence_check)
Enable the check for validating that sequences of either pairs or
triplets of tokens make sense. For example the following sequence of
tokens when encountered will raise an error:
(a) (x + * 3) ---> sequence error
(6) Commutative Check (e_commutative_check)
Enable the check that will transform sequences of pairs of tokens that
imply a multiplication operation. The following are some examples of
such transformations:
(a) 2x ---> 2 * x
(b) 25x^3 ---> 25 * x^3
(c) 3(x + 1) ---> 3 * (x + 1)
(d) (x + 1)4 ---> (x + 1) * 4
(e) 5foo(x,y) ---> 5 * foo(x,y)
(f) foo(x,y)6 + 1 ---> foo(x,y) * 6 + 1
(g) (4((2x)3)) ---> 4 * ((2 * x) * 3)
(h) w / (x - y)z ---> w / (x - y) * z
(7) Strength Reduction Check (e_strength_reduction)
Enable the use of strength reduction optimisations during the
compilation process. In ExprTk strength reduction optimisations
predominantly involve transforming sub-expressions into other forms
that are algebraically equivalent yet less costly to compute. The
following are examples of the various transformations that can occur:
(a) (x / y) / z ---> x / (y * z)
(b) (x / y) / (z / w) ---> (x * w) / (y * z)
(c) (2 * x) - (2 * y) ---> 2 * (x - y)
(d) (2 / x) / (3 / y) ---> (2 / 3) / (x * y)
(e) (2 * x) * (3 * y) ---> 6 * (x * y)
(f) (2 * x) * (2 - 4 / 2) ---> 0
(g) (3 - 6 / 2) / (2 * x) ---> 0
(h) avg(x,y,z) * (2 - 4 / 2) ---> 0
Note08: When using strength reduction in conjunction with expressions
whose inputs or sub-expressions may result in values nearing either of
the bounds of the underlying numeric type (eg: double), there may be
the possibility of a decrease in the precision of results.
In the following example the given expression which represents an
attempt at computing the average between x and y will be transformed
as follows:
(0.5 * x) + (y * 0.5) ---> 0.5 * (x + y)
There may be situations where the above transformation will cause
numerical overflows and that the original form of the expression is
desired over the strength reduced form. In these situations it is best
to turn off strength reduction optimisations or to use a type with a
larger numerical bound.
(8) Stack And Node Depth Check
ExprTk incorporates a recursive descent parser. When parsing
expressions comprising inner sub-expressions, the recursive nature of
the parsing process causes the stack to grow. If the expression causes
the stack to grow beyond the stack size limit, this would lead to a
stackoverflow and its associated stack corruption and security
vulnerability issues.
Similarly to parsing, evaluating an expression may cause the stack to
grow. Such things like user defined functions, composite functions and
the general nature of the AST being evaluated can cause the stack to
grow, and may result in potential stackoverflow issues as denoted
above.
ExprTk provides a set of checks that prevent both of the above denoted
problems at compile time. These checks rely on two specific limits
being set on the parser settings instance, these limits are:
1. max_stack_depth (default: 400 )
2. max_node_depth (default: 10000)
The following demonstrates how these two parser parameters can be set:
parser_t parser;
parser.settings().set_max_stack_depth(100);
parser.settings().set_max_node_depth(200);
In the above code, during parsing if the stack depth reaches or
exceeds 100 levels, the parsing process will immediately halt and
return with a failure. Similarly, during synthesizing the AST nodes,
if the compilation process detects an AST tree depth exceeding 200
levels the parsing process will halt and return a parsing failure.
(9) Expression Size Check
ExprTk allows for expression local variables, vectors and strings to
be defined. As such the amount of data in terms of bytes consumed by
the expression locals can also be limited, so as to prevent
expressions once compiled from consuming large amounts of data.
The maximum number of bytes an expression's locally defined variables
may use can be set via the parser settings prior to compilation as
follows:
using expression_t = exprtk::expression;
using parser_t = exprtk::parser;
expression_t expression;
parser_t parser;
parser.settings().set_max_total_local_symbol_size_bytes(16);
const std::string expression1 = "var x := 1; var y := 1;";
const std::string expression2 = "var x := 1; var v[2] := [1];";
expression_t expression;
parser.compile(expression1, expression); // compilation success
parser.compile(expression2, expression); // compilation error
In the above example, the expression's max total local symbol size has
been set to 16 bytes. The numeric type being used is double which is 8
bytes per instance. The first expression (expression1) compiles
successfully because the total local symbol size is 16 bytes, 8 bytes
for each of the variables x and y.
However the second expression (expression2) fails to compile. This is
because the total number of bytes needed for the expression is 24
bytes, 8 bytes for the variable x and 16 bytes for the vector v, as
such exceeding the previously set limit of 16 bytes. The error
diagnostic generated by the parser on compilation failure will look
like the following:
ERR161 - Adding vector 'v' of size 2 bytes will exceed max total
local symbol size of: 16 bytes, current total size: 8 bytes
(10) Vector Size Check
When defining an expression local vector, ExprTk uses a default
maximum vector size of two billion elements. One may want to limit the
maximum vector size to be either smaller or larger than the specified
default value. The maximum size value can be changed via the parser
settings.
parser_t parser;
parser.settings().set_max_local_vector_size(1000000);
std::string expression1 = "var v[1e6] := [123]";
std::string expression2 = "var v[1e9] := [123]";
expression_t expression;
parser.compile(expression1, expression); // compilation success
parser.compile(expression2, expression); // compilation error
In the above code, the maximum local vector size is set to one million
elements. During compilation of an expression if there is a vector
definition where the vector's size exceeds the maximum allowed vector
size a compilation error shall be emitted. The error diagnostic
generated by the parser on compilation failure will look like the
following:
ERR160 - Invalid vector size. Must be an integer in the
range [0,1000000], size: 1000000000
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 12 - EXPRESSION STRUCTURES]
Exprtk supports mathematical expressions in numerous forms based on a
simple imperative programming model. This section will cover the
following topics related to general structure and programming of
expressions using ExprTk:
(1) Multi-Statement Expressions
(2) Statements And Side-Effects
(3) Conditional Statements
(4) Special Functions
(1) Multi-Statement Expressions
Expressions in ExprTk can be comprised of one or more statements, which
may sometimes be called sub-expressions. The following are two
examples of expressions stored in std::string variables, the first a
single statement and the second a multi-statement expression:
std::string single_statement = " z := x + y ";
std::string multi_statement = " var temp := x; "
" x := y + z; "
" y := temp; ";
In a multi-statement expression, the final statement will determine
the overall result of the expression. In the following multi-statement
expression, the result of the expression when evaluated will be '2.3',
which will also be the value stored in the 'y' variable.
z := x + y;
y := 2.3;
As demonstrated in the expression above, statements within an
expression are separated using the semi-colon ';' operator. In the
event two statements are not separated by a semi-colon, and the
implied multiplication feature is active (enabled by default), the
compiler will assume a multiplication operation between the two
statements.
In the following example we have a multi-statement expression composed
of two variable definitions and initialisations for variables x and y
and two seemingly separate mathematical operations.
var x:= 2;
var y:= 3;
x + 1
y * 2
However the result of the expression will not be 6 as may have been
assumed based on the calculation of 'y * 2', but rather the result
will be 8. This is because the compiler will have conjoined the two
mathematical statements into one via a multiplication operation. The
expression when compiled will actually evaluate as the following:
var x:= 2;
var y:= 3;
x + 1 * y * 2; // 2 + 1 * 3 * 2 == 8
In ExprTk any valid statement will itself return a value. This value
can further be used in conjunction with other statements. This
includes language structures such as if-statements, loops (for, while)
and the switch statement. Typically the last statement executed in the
given construct (conditional, loop etc), will be the value that is
returned.
In the following example, the return value of the expression will be
11, which is the sum of the variable 'x' and the final value computed
within the loop body upon its last iteration:
var x := 1;
x + for (var i := x; i < 10; i += 1)
{
i / 2;
i + 1;
}
(2) Statements And Side-Effects
Statements themselves may have side effects, which in-turn affect the
proceeding statements in multi-statement expressions.
A statement is said to have a side-effect if it causes the state of
the expression to change in some way - this includes but is not
limited to the modification of the state of external variables used
within the expression. Currently the following actions being present
in a statement will cause it to have a side-effect:
(a) Assignment operation (explicit or potentially)
(b) Invoking a user-defined function that has side-effects
The following are examples of expressions where the side-effect status
of the statements (sub-expressions) within the expressions have been
noted:
+-+----------------------+------------------------------+
|#| Expression | Side Effect Status |
+-+----------------------+------------------------------+
|0| x + y | False |
+-+----------------------+------------------------------+
|1| z := x + y | True - Due to assignment |
+-+----------------------+------------------------------+
|2| abs(x - y) | False |
+-+----------------------+------------------------------+
|3| abs(x - y); | False |
| | z := (x += y); | True - Due to assignments |
+-+----------------------+------------------------------+
|4| abs(x - y); | False |
| | z := (x += y); | True - Due to assignments |
+-+----------------------+------------------------------+
|5| var t := abs(x - y); | True - Due to initialisation |
| | t + x; | False |
| | z := (x += y); | True - Due to assignments |
+-+----------------------+------------------------------+
|6| foo(x - y) | True - user defined function |
+-+----------------------+------------------------------+
Note09: In example 6 from the above set, it is assumed the user
defined function foo has been registered as having a side-effect. By
default all user defined functions are assumed to have side-effects,
unless they are configured in their constructors to not have side-
effects using the 'disable_has_side_effects' free function. For more
information review Section 15 - User Defined Functions sub-section 7
Function Side-Effects.
At this point we can see that there will be expressions composed of
certain kinds of statements that when executed will not affect the
nature of the expression's result. These statements are typically
called 'dead code'. These statements though not affecting the final
result will still be executed and as such they will consume processing
time that could otherwise be saved. As such ExprTk attempts to detect
and remove such statements from expressions.
The 'Dead Code Elimination' (DCE) optimisation process, which is
enabled by default, will remove any statements that are determined to
not have a side-effect in a multi-statement expression, excluding the
final or last statement.
By default the final statement in an expression will always be present
regardless of its side-effect status, as it is the statement whose
value shall be used as the result of the expression.
In order to further explain the actions taken during the DCE process,
lets review the following expression:
var x := 2; // Statement 1
var y := x + 2; // Statement 2
x + y; // Statement 3
y := x + 3y; // Statement 4
x - y; // Statement 5
The above expression has five statements. Three of them (1, 2 and 4)
actively have side-effects. The first two are variable declaration and
initialisations, where as the third is due to an assignment operation.
There are two statements (3 and 5), that do not explicitly have
side-effects, however the latter, statement 5, is the final statement
in the expression and hence will be assumed to have a side-effect.
During compilation when the DCE optimisation is applied to the above
expression, statement 3 will be removed from the expression, as it has
no bearing on the final result of expression, the rest of the
statements will all remain. The optimised form of the expression is as
follows:
var x := 2; // Statement 1
var y := x + 2; // Statement 2
y := x + 3y; // Statement 3
x - y; // Statement 4
(3) Conditional Statements (If-Then-Else)
ExprTk supports two forms of conditional branching or otherwise known
as if-statements. The first form, is a simple function based
conditional statement, that takes exactly three input expressions:
condition, consequent and alternative. The following is an example
expression that utilises the function based if-statement.
x := if (y < z, y + 1, 2 * z)
In the example above, if the condition 'y < z' is true, then the
consequent 'y + 1' will be evaluated, its value shall be returned and
subsequently assigned to the variable 'x'. Otherwise the alternative
'2 * z' will be evaluated and its value will be returned. This is
essentially the simplest form of an if-then-else statement. A simple
variation of the expression where the value of the if-statement is
used within another statement is as follows:
x := 3 * if (y < z, y + 1, 2 * z) / 2
The second form of if-statement resembles the standard syntax found in
most imperative languages. There are two variations of the statement:
(a) If-Statement
(b) If-Then-Else Statement
(a) If-Statement
This version of the conditional statement returns the value of the
consequent expression when the condition expression is true, else it
will return a quiet NaN value as its result.
Example 1:
x := if (y < z) y + 3;
Example 2:
x := if (y < z)
{
y + 3
};
The two example expressions above are equivalent. If the condition
'y < z' is true, the 'x' variable shall be assigned the value of the
consequent 'y + 3', otherwise it will be assigned the value of quiet
NaN. As previously discussed, if-statements are value returning
constructs, and if not properly terminated using a semi-colon, will
end-up combining with the next statement via a multiplication
operation. The following example will NOT result in the expected value
of 'w + x' being returned:
x := if (y < z) y + 3 // missing semi-colon ';'
w + x
When the above supposed multi-statement expression is compiled, the
expression will have a multiplication inserted between the two
'intended' statements resulting in the unanticipated expression:
x := (if (y < z) y + 3) * w + x
The solution to the above situation is to simply terminate the
conditional statement with a semi-colon as follows:
x := if (y < z) y + 3;
w + x
(b) If-Then-Else Statement
The second variation of the if-statement is to allow for the use of
Else and Else-If cascading statements. Examples of such statements are
as follows:
Example 1: Example 2: Example 3:
if (x < y) if (x < y) if (x > y + 1)
z := x + 3; { y := abs(x - z);
else y := z + x; else
y := x - z; z := x + 3; {
} y := z + x;
else z := x + 3;
y := x - z; };
Example 4: Example 5: Example 6:
if (2 * x < max(y,3)) if (x < y) if (x < y or (x + z) > y)
{ z := x + 3; {
y := z + x; else if (2y != z) z := x + 3;
z := x + 3; { y := x - z;
} z := x + 3; }
else if (2y - z) y := x - z; else if (abs(2y - z) >= 3)
y := x - z; } y := x - z;
else else
x * x; {
z := abs(x * x);
x * y * z;
};
In the case where there is no final else statement and the flow
through the conditional arrives at this final point, the same rules
apply to this form of if-statement as to the previous. That is a quiet
NaN shall be returned as the result of the if-statement. Furthermore
the same requirements of terminating the statement with a semi-colon
apply.
(4) Special Functions
The purpose of special functions in ExprTk is to provide compiler
generated equivalents of common mathematical expressions which can be
invoked by using the 'special function' syntax (eg: $f12(x,y,z) or
$f82(x,y,z,w)).
Special functions dramatically decrease the total evaluation time of
expressions which would otherwise have been written using the common
form by reducing the total number of nodes in the evaluation tree of
an expression and by also leveraging the compiler's ability to
correctly optimise such expressions for a given architecture.
3-Parameter 4-Parameter
+-------------+-------------+ +--------------+------------------+
| Prototype | Operation | | Prototype | Operation |
+-------------+-------------+ +--------------+------------------+
$f00(x,y,z) | (x + y) / z $f48(x,y,z,w) | x + ((y + z) / w)
$f01(x,y,z) | (x + y) * z $f49(x,y,z,w) | x + ((y + z) * w)
$f02(x,y,z) | (x + y) - z $f50(x,y,z,w) | x + ((y - z) / w)
$f03(x,y,z) | (x + y) + z $f51(x,y,z,w) | x + ((y - z) * w)
$f04(x,y,z) | (x - y) + z $f52(x,y,z,w) | x + ((y * z) / w)
$f05(x,y,z) | (x - y) / z $f53(x,y,z,w) | x + ((y * z) * w)
$f06(x,y,z) | (x - y) * z $f54(x,y,z,w) | x + ((y / z) + w)
$f07(x,y,z) | (x * y) + z $f55(x,y,z,w) | x + ((y / z) / w)
$f08(x,y,z) | (x * y) - z $f56(x,y,z,w) | x + ((y / z) * w)
$f09(x,y,z) | (x * y) / z $f57(x,y,z,w) | x - ((y + z) / w)
$f10(x,y,z) | (x * y) * z $f58(x,y,z,w) | x - ((y + z) * w)
$f11(x,y,z) | (x / y) + z $f59(x,y,z,w) | x - ((y - z) / w)
$f12(x,y,z) | (x / y) - z $f60(x,y,z,w) | x - ((y - z) * w)
$f13(x,y,z) | (x / y) / z $f61(x,y,z,w) | x - ((y * z) / w)
$f14(x,y,z) | (x / y) * z $f62(x,y,z,w) | x - ((y * z) * w)
$f15(x,y,z) | x / (y + z) $f63(x,y,z,w) | x - ((y / z) / w)
$f16(x,y,z) | x / (y - z) $f64(x,y,z,w) | x - ((y / z) * w)
$f17(x,y,z) | x / (y * z) $f65(x,y,z,w) | ((x + y) * z) - w
$f18(x,y,z) | x / (y / z) $f66(x,y,z,w) | ((x - y) * z) - w
$f19(x,y,z) | x * (y + z) $f67(x,y,z,w) | ((x * y) * z) - w
$f20(x,y,z) | x * (y - z) $f68(x,y,z,w) | ((x / y) * z) - w
$f21(x,y,z) | x * (y * z) $f69(x,y,z,w) | ((x + y) / z) - w
$f22(x,y,z) | x * (y / z) $f70(x,y,z,w) | ((x - y) / z) - w
$f23(x,y,z) | x - (y + z) $f71(x,y,z,w) | ((x * y) / z) - w
$f24(x,y,z) | x - (y - z) $f72(x,y,z,w) | ((x / y) / z) - w
$f25(x,y,z) | x - (y / z) $f73(x,y,z,w) | (x * y) + (z * w)
$f26(x,y,z) | x - (y * z) $f74(x,y,z,w) | (x * y) - (z * w)
$f27(x,y,z) | x + (y * z) $f75(x,y,z,w) | (x * y) + (z / w)
$f28(x,y,z) | x + (y / z) $f76(x,y,z,w) | (x * y) - (z / w)
$f29(x,y,z) | x + (y + z) $f77(x,y,z,w) | (x / y) + (z / w)
$f30(x,y,z) | x + (y - z) $f78(x,y,z,w) | (x / y) - (z / w)
$f31(x,y,z) | x * y^2 + z $f79(x,y,z,w) | (x / y) - (z * w)
$f32(x,y,z) | x * y^3 + z $f80(x,y,z,w) | x / (y + (z * w))
$f33(x,y,z) | x * y^4 + z $f81(x,y,z,w) | x / (y - (z * w))
$f34(x,y,z) | x * y^5 + z $f82(x,y,z,w) | x * (y + (z * w))
$f35(x,y,z) | x * y^6 + z $f83(x,y,z,w) | x * (y - (z * w))
$f36(x,y,z) | x * y^7 + z $f84(x,y,z,w) | x*y^2 + z*w^2
$f37(x,y,z) | x * y^8 + z $f85(x,y,z,w) | x*y^3 + z*w^3
$f38(x,y,z) | x * y^9 + z $f86(x,y,z,w) | x*y^4 + z*w^4
$f39(x,y,z) | x * log(y)+z $f87(x,y,z,w) | x*y^5 + z*w^5
$f40(x,y,z) | x * log(y)-z $f88(x,y,z,w) | x*y^6 + z*w^6
$f41(x,y,z) | x * log10(y)+z $f89(x,y,z,w) | x*y^7 + z*w^7
$f42(x,y,z) | x * log10(y)-z $f90(x,y,z,w) | x*y^8 + z*w^8
$f43(x,y,z) | x * sin(y)+z $f91(x,y,z,w) | x*y^9 + z*w^9
$f44(x,y,z) | x * sin(y)-z $f92(x,y,z,w) | (x and y) ? z : w
$f45(x,y,z) | x * cos(y)+z $f93(x,y,z,w) | (x or y) ? z : w
$f46(x,y,z) | x * cos(y)-z $f94(x,y,z,w) | (x < y) ? z : w
$f47(x,y,z) | x ? y : z $f95(x,y,z,w) | (x <= y) ? z : w
$f96(x,y,z,w) | (x > y) ? z : w
$f97(x,y,z,w) | (x >= y) ? z : w
$f98(x,y,z,w) | (x == y) ? z : w
$f99(x,y,z,w) | x*sin(y)+z*cos(w)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 13 - VARIABLE, VECTOR & STRING DEFINITION]
ExprTk supports the definition of expression local variables, vectors
and strings. The definitions must be unique as shadowing is not
allowed and object lifetimes are based on scope. Definitions use the
following general form:
var := ;
(1) Variable Definition
Variables are of numeric type denoting a single value. They can be
explicitly initialised to a value, otherwise they will be defaulted to
zero. The following are examples of variable definitions:
(a) Initialise x to zero
var x;
(b) Initialise y to three
var y := 3;
(c) Initialise z to the expression
var z := if (max(1, x + y) > 2, w, v);
(d) Initialise const literal n
var n := 12 / 3;
(2) Vector Definition
Vectors are arrays of a common numeric type. The elements in a vector
can be explicitly initialised, otherwise they will all be defaulted to
zero. The following are examples of vector definitions:
(a) Initialise all values to zero
var x[3];
(b) Initialise all values to zero
var x[3] := {};
(c) Initialise all values to given value or expression
var x[3] := [ 42 ];
var y[x[]] := [ 123 + 3y + sin(w / z) ];
(d) Initialise all values iota style
var v[4] := [ 0 : +1]; // 0, 1, 2, 3
var v[5] := [-3 : -2]; // -3, -5, -7, -9, -11
(e) Initialise the first two values, all other elements to zero
var x[3] := { (1 + x[2]) / x[], (sin(y[0] / x[]) + 3) / x[] };
(f) Initialise the first three (all) values
const var size := 3;
var x[size] := { 1, 2, 3 };
(g) Initialise vector from a vector
var x[4] := { 1, 2, 3, 4 };
var y[3] := x;
var w[5] := { 1, 2 }; // 1, 2, 0, 0, 0
(h) Initialise vector from a smaller vector
var x[3] := { 1, 2, 3 };
var y[5] := x; // 1, 2, 3, ??, ??
(i) Non-initialised vector
var x[3] := null; // ?? ?? ??
(j) Error as there are too many initialisers
var x[3] := { 1, 2, 3, 4 };
(k) Error as a vector of size zero is not allowed.
var x[0];
(3) String Definition
Strings are sequences comprised of 8-bit characters. They can only be
defined with an explicit initialisation value. The following are
examples of string variable definitions:
(a) Initialise to a string
var x := 'abc';
(b) Initialise to an empty string
var x := '';
(c) Initialise to a string expression
var x := 'abc' + '123';
(d) Initialise to a string range
var x := 'abc123'[2:4];
(e) Initialise to another string variable
var x := 'abc';
var y := x;
(f) Initialise to another string variable range
var x := 'abc123';
var y := x[2:4];
(g) Initialise to a string expression
var x := 'abc';
var y := x + '123';
(h) Initialise to a string expression range
var x := 'abc';
var y := (x + '123')[1:3];
(4) Return Value
Variable and vector definitions have a return value. In the case of
variable definitions, the value to which the variable is initialised
will be returned. Where as for vectors, the value of the first element
(eg: v[0]) shall be returned.
8 == ((var x := 7;) + 1)
4 == (var y[3] := {4, 5, 6};)
(5) Variable/Vector Assignment
The value of a variable can be assigned to a vector and a vector or a
vector expression can be assigned to a variable.
(a) Variable To Vector:
Every element of the vector is assigned the value of the variable
or expression.
var x := 3;
var y[3] := { 1, 2, 3 };
y := x + 1;
(b) Vector To Variable:
The variable is assigned the value of the first element of the
vector (aka vec[0])
var x := 3;
var y[3] := { 1, 2, 3 };
x := y + 1;
Note10: During the expression compilation phase, tokens are classified
based on the following priorities:
(a) Reserved keywords or operators (+, -, and, or, etc)
(b) Base functions (abs, sin, cos, min, max etc)
(c) Symbol table variables
(d) Expression local defined variables
(e) Symbol table functions
(f) Unknown symbol resolver based variables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[SECTION 14 - VECTOR PROCESSING]
ExprTk provides support for various forms of vector oriented
arithmetic, inequalities and processing. The various supported pairs
are as follows:
(a) vector and vector (eg: v0 + v1)
(b) vector and scalar (eg: v + 33)
(c) scalar and vector (eg: 22 * v)
The following is a list of operations that can be used in conjunction
with vectors:
(a) Arithmetic: +, -, *, /, %
(b) Exponentiation: vector ^ scalar
(c) Assignment: :=, +=, -=, *=, /=, %=, <=>
(d) Inequalities: <, <=, >, >=, ==, =, equal
(e) Boolean logic: and, nand, nor, or, xnor, xor
(f) Unary operations:
abs, acos, acosh, asin, asinh, atan, atanh, ceil, cos, cosh,
cot, csc, deg2grad, deg2rad, erf, erfc, exp, expm1, floor,
frac, grad2deg, log, log10, log1p, log2, rad2deg, round, sec,
sgn, sin, sinc, sinh, sqrt, swap, tan, tanh, trunc,
thresholding
(g) Aggregate and Reduce operations:
avg, max, min, mul, dot, dotk, sum, sumk, count, all_true,
all_false, any_true, any_false
(h) Transformation operations:
copy, diff, reverse, rotate-left/right, shift-left/right, sort,
nth_element
(i) BLAS-L1:
axpy, axpby, axpyz, axpbyz, axpbz
Note11: When one of the above described operations is being performed
between two vectors, the operation will only span the size of the
smallest vector. The elements of the larger vector outside of the
range will not be included. The operation itself will be processed
element-wise over values of the smaller of the two ranges.
The following simple example demonstrates the vector processing
capabilities by computing the dot-product of the vectors v0 and v1 and
then assigning it to the variable v0dotv1:
var v0[3] := { 1, 2, 3 };
var v1[3] := { 4, 5, 6 };
var v0dotv1 := sum(v0 * v1);
The following is a for-loop based implementation that is equivalent to
the previously mentioned dot-product computation expression:
var v0[3] := { 1, 2, 3 };
var v1[3] := { 4, 5, 6 };
var v0dotv1;
for (var i := 0; i < min(v0[],v1[]); i += 1)
{
v0dotv1 += (v0[i] * v1[i]);
}
Note12: When the aggregate or reduction operations denoted above are
used in conjunction with a vector or vector expression, the return
value is not a vector but rather a single value.
var x[3] := { 1, 2, 3 };
sum(x) == 6
sum(1 + 2x) == 15
avg(3x + 1) == 7
min(1 / x) == (1 / 3)
max(x / 2) == (3 / 2)
sum(x > 0 and x < 5) == x[]
When utilising external user defined vectors via the symbol table as
opposed to expression local defined vectors, the typical 'add_vector'
method from the symbol table will register the entirety of the vector
that is passed. The following example attempts to evaluate the sum of
elements of the external user defined vector within a typical yet
trivial expression:
const std::string reduce_program = " sum(2 * v + 1) ";
std::vector v0 { T(1.1), T(2.2), ..... , T(99.99) };
symbol_table_t symbol_table;
symbol_table.add_vector("v",v);
expression_t expression;
expression.register_symbol_table(symbol_table);
parser_t parser;
parser.compile(reduce_program,expression);
T sum = expression.value();
For the most part, this is a very common use-case. However there may
be situations where one may want to evaluate the same vector oriented
expression many times over, but using different vectors or sub ranges
of the same vector of the same size to that of the original upon every
evaluation.
The usual solution is to either recompile the expression for the new
vector instance, or to copy the contents from the new vector to the
symbol table registered vector and then perform the evaluation. When
the vectors are large or the re-evaluation attempts are numerous,
these solutions can become rather time consuming and generally
inefficient.
std::vector v1 { T(2.2), T(2.2), ..... , T(2.2) };
std::vector v2 { T(3.3), T(3.3), ..... , T(3.3) };
std::vector v3 { T(4.4), T(4.4), ..... , T(4.4) };
std::vector> vv { v1, v2, v3 };
...
T sum = T(0);
for (auto& new_vec : vv)
{
v = new_vec; // update vector
sum += expression.value();
}
A solution to the above 'efficiency' problem, is to use the
exprtk::vector_view object. The vector_view is instantiated with a
size and backing based upon a vector. Upon evaluations if the backing
needs to be 'updated' to either another vector or sub-range, the
vector_view instance can be efficiently rebased, and the expression
evaluated as normal.
exprtk::vector_view view = exprtk::make_vector_view(v,v.size());
symbol_table_t symbol_table;
symbol_table.add_vector("v",view);
...
T sum = T(0);
for (auto& new_vec : vv)
{
view.rebase(new_vec.data()); // update vector
sum += expression.value();
}
Another useful feature of exprtk::vector_view is that all such vectors
can have their sizes modified (or "resized"). The resizing of the
associated vectors can happen either between or during evaluations.
std::vector v = { 1, 2, 3, 4, 5, 6, 7, 8 };
exprtk::vector_view view = exprtk::make_vector_view(v,v.size());
symbol_table_t symbol_table;
symbol_table.add_vector("v",view);
const std::string expression_string = "v[]";
expression_t expression;
expression.register_symbol_table(symbol_table);
parser_t parser;
parser.compile(expression_string, expression);
for (std::size_t i = 1; i <= v.size(); ++i)
{
vv.set_size(i);
expression.value();
}
In the example above, a vector_view is instantiated with a std::vector
instance with eight elements and registered to the given symbol_table.
An expression is then compiled, which in this case simply returns the
size of the vector at that point in time. The expression is evaluated
eight times (size of vector times