Библиотека exprint, часть Expr — вычислитель выражений

Назначение и место в пакете

Вычислитель Expr (каталог src/libs/expr) получает строку с арифметическим выражением, например 2*sin(x)+1.5e-3, и возвращает её значение типа _real (double). Вместе с интерпретатором Inter он собирается в одну статическую библиотеку exprint (так же, как Windows-проект exprint.vcxproj).

В пакете выражения встречаются везде, где в задании .tpl вместо числа можно написать формулу:

Кто Что вычисляет Переменные
Ядра PlanarRT_H / PlanarRT_X (tmcrthnodediel.cpp) eps, N, B, sigma блоков, заданные формулой от координат и частоты x, y, r, f
Ядра, сигнал на порту амплитуда и фаза падающей волны как функции времени и частоты t, f
Библиотека TMCIndan (tmcrth_indanparam.cpp) числовые параметры задания; выбор единиц угла —
Вьюверы (tmcgrexpression.cpp, c2darray.cpp) выражения над графиками и S-параметрами —

Ядра вызывают не сам Expr, а интерпретатор: i1nte_atof_1 удаляет пробелы и передаёт строку в inte_atof, а тот для каждого выражения обращается к expr_inter. Сигналы на порту описаны в теории: сигнал на порту.

Все функции объявлены и подробно описаны в общем заголовке src/Include/expr.h; справочник строится из этих комментариев автоматически.

Состав

Файл Роль
expr_in1.cpp точка входа expr_atof, рекурсивный разбор expr_inter, распознавание чисел expr_numbern
expr_com.cpp одна операция или функция expr_comp; единицы угла expr_set_angle
expr_per.cpp переменные expr_get_per/expr_set_per/expr_is_per; контекст потока
expr_err.cpp код ошибки expr_set_error_cod/expr_get_error_cod
expremsg.cpp текст ошибки expr_get_error
get_err.cpp перевод кода в номер сообщения пакета get_expr_err
drv_expr.cpp консольный «калькулятор» для ручной проверки; в сборку не входит

Грамматика выражения

Пробелов в выражении быть не должно: их заранее удаляет вызывающий код (i1nte_atof_1 убирает пробелы, табуляции и переводы строки \n).

Элементы выражения.

Элемент Запись Пример
Число цифры, необязательные знак - в начале, десятичная точка и порядок e с 1–3 цифрами (со знаком или без); не длиннее 40 символов -12, 0.5, 1.24e+17, 1e18
Переменная одна латинская буква, регистр различается x, f, T
Скобки круглые ( ); фигурные { } тоже учитываются при поиске операций (их использует Inter) 2*(3+4)
Функция имя строчными буквами и сразу ( sin(x)
Операции = + - * / ^ a=3, 2^-1

Порядок E (заглавная буква) не поддерживается: 1E5 — ошибка «abnormal function». Число больше FLT_MAX (около 3.4·1038), например 1e300, — ошибка переполнения.

Порядок разбора. expr_inter рекурсивно проверяет подстроку в таком порядке:

  1. Число (expr_numbern) — значение через atof.
  2. Однобуквенная переменная — значение из таблицы переменных.
  3. Операции вне скобок в порядке возрастания приоритета: =, затем +, -, *, /, ^. Для каждой операции строка просматривается справа налево; найденная операция делит строку на левую и правую части, которые вычисляются рекурсивно. Для + - * / берётся самая правая операция, что даёт левую ассоциативность (8/4/2 = 1). Для ^ берётся самая левая, поэтому степень правоассоциативна: 2^3^2 = 2^(3^2) = 512.
  4. Выражение целиком в круглых скобках — вычисляется содержимое.
  5. Функция: начало строки сравнивается с именами abs( exp( log( sin( cos( tan(, sqrt( sinh( cosh( tanh( asin( acos( atan( и log10(; остаток строки начиная со скобки вычисляется как аргумент.
  6. Иначе — ошибка ERROR_FUNCTION («abnormal function»).

Унарный минус. Знак - в начале строки даёт пустой левый операнд, который считается нулём: -2^2 = 0 - 2^2 = -4. Знак + или - сразу после другой операции (2^-1, 2*-3) и знак порядка числа (1.24e+17) точками деления не считаются.

Присваивание. a=выражение присваивает значение переменной a и возвращает его. Слева может стоять только одна буква; цепочка a=b=3 — ошибка ERROR_VAR.

Операции и функции

Каждая операция выполняется функцией expr_comp. Результат больше FLT_MAX считается переполнением: устанавливается ошибка и возвращается FLT_MAX (или 0).

Операция / функция Условие ошибки Код ошибки
x+y, x-y, x*y результат больше FLT_MAX ERROR_OVERFLOW (-20)
x/y y=0 ERROR_DIV_0 (-15)
x^y, x>0 результат больше FLT_MAX (для 0<x<1 проверяется по факту) ERROR_OVERFLOW (-20)
x^y, x≤0 дробный y; x=0 при y≤0 ERROR_POW (-16)
exp, sinh, cosh аргумент больше ln(FLT_MAX)≈88.7 -EXP, -SINH, -COSH
log, log10 аргумент ≤0 -LOG, -LOG10
sqrt аргумент <0 -SQRT
sin, cos, tan модуль аргумента больше FLT_MAX_SIN = 65536 (в единицах угла) -SIN, -COS, -TAN
asin, acos модуль аргумента больше 1 -ASIN, -ACOS
abs, tanh, atan — —

Отрицательная степень с целым показателем допустима: (-2)^3 = -8; (-2)^0.5 — ошибка.

Единицы угла

Тригонометрические функции работают в градусах или радианах в зависимости от глобального множителя expr_angle:

sin(арг)=sin(арг·k),arcsin(v)=arcsinрад(v)/k,(1)

где k=π/180 в режиме EXPR_GRADUS и k=1 в режиме EXPR_RADIAN. По умолчанию — градусы. Библиотека TMCIndan при создании параметров задания ставит радианы, а затем переключает режим по единицам угла, записанным в задании. Настройка одна на всю программу и в контекст потока не входит.

Ошибки

Код ошибки — отрицательное число; 0 — ошибки нет. После первой ошибки все последующие вызовы expr_inter и expr_comp сразу возвращают 0, поэтому код сохраняет причину первой ошибки. expr_atof и inte_atof перед вычислением сбрасывают код.

Код Константа Текст expr_get_error
0 — all right
-1 -EXP overflow in function exp
-2 -LOG argument LOG <= 0 (bad)
-3 -SIN overflow in function sin (argument > 65536)
-4 -COS overflow in function cos (argument > 65536)
-5 -TAN overflow in function tan …
-7 -SQRT argument SQRT < 0 (bad)
-8 … -10 -SINH, -COSH, -TANH overflow in function sinh / cosh / tanh
-11, -12 -ASIN, -ACOS argument ASIN / ACOS > 1 (bad)
-14 -LOG10 argument LOG10 <=0 (bad)
-15 ERROR_DIV_0 division by zero in x/y
-16 ERROR_POW x^y: x<0 with a fractional y, or 0^y with y<=0
-17 ERROR_BRACKET abnormal bracket
-18 ERROR_FUNCTION abnormal function
-19 ERROR_EXPRESSION abnormal expression
-20 ERROR_OVERFLOW float overflow
-21 ERROR_RETURN bad return (служебный признак return интерпретатора)
-22 ERROR_VAR bad parameter in =

Текст английский; ядра добавляют к нему строку выражения и значения переменных и показывают пользователю через объект ошибки CTmcLibError (TMCLibError). Функция get_expr_err переводит код в номер 2400 + n из error1.h (константы ERROR_EXPR_*), но сообщение по этому номеру не выводится.

Переменные и параллельные потоки

Переменные хранятся в таблице из 256 значений _real, индекс — код символа имени; не присвоенная переменная равна 0. Ядра записывают в неё x, y, r, f (или t, f) через expr_set_per перед каждым вычислением — с полной точностью, без перевода в строку.

Построение узлов сетки ядра выполняют в нескольких потоках, и каждый поток вычисляет формулы со своими координатами. Чтобы потоки не мешали друг другу, у библиотеки есть контекст потока EXPR_THREAD_CTX:

  1. Поток заводит структуру EXPR_THREAD_CTX (обычно на своём стеке) и вызывает expr_thread_ctx_begin(&ctx). В контекст копируются текущие общие переменные, код ошибки и значение return обнуляются, указатель на контекст запоминается в переменной thread_local.
  2. Пока контекст привязан, expr_set_per/expr_get_per, код ошибки и значение return читаются и пишутся в контексте этого потока.
  3. В конце поток вызывает expr_thread_ctx_end() и возвращается к общим переменным.

Единицы угла (expr_angle) в контекст не входят — их нужно выбрать до запуска потоков.

Подводные камни

Всё перечисленное подтверждено кодом и проверочными вычислениями.

  1. Строка временно изменяется. expr_inter на время разбора пишет '\0' в lex[n] и в lex[4], lex[5], lex[6] и затем восстанавливает их. Строка должна быть изменяемой (не литерал), а буфер — не короче 7 символов: для коротких строк запись идёт за завершающий ноль. Одну строку нельзя вычислять из двух потоков сразу.
  2. Переполнение проверяется только сверху. Для + - * ошибка ставится, если результат больше FLT_MAX; большой по модулю отрицательный результат ошибкой не считается (x=0-3e38; x*10 даёт −3·1039 без ошибки).
  3. Пределы — как у float. Хотя _real — double, числа и результаты больше FLT_MAX (около 3.4·1038) считаются переполнением.
  4. Тригонометрия по умолчанию в градусах — см. «Единицы угла».
  5. Имена функций — только строчными буквами, порядок числа — только e: SIN(1) и 1E5 — ошибка «abnormal function».
  6. Переменная — одна буква. Имя из двух букв (ab) — ошибка «abnormal function».

exprint library, Expr part — the expression evaluator

Purpose and place in the package

The Expr evaluator (directory src/libs/expr) receives a string with an arithmetic expression, for example 2*sin(x)+1.5e-3, and returns its value of type _real (double). Together with the Inter interpreter it is built into a single static library exprint (just like the Windows project exprint.vcxproj).

In the package, expressions appear wherever a .tpl task file allows a formula instead of a number:

Who What it evaluates Variables
PlanarRT_H / PlanarRT_X kernels (tmcrthnodediel.cpp) eps, N, B, sigma of blocks given as a formula of coordinates and frequency x, y, r, f
Kernels, port signal amplitude and phase of the incident wave as functions of time and frequency t, f
TMCIndan library (tmcrth_indanparam.cpp) numeric task-file parameters; choice of angle units —
Viewers (tmcgrexpression.cpp, c2darray.cpp) expressions over plots and S-parameters —

The kernels do not call Expr itself but the interpreter: i1nte_atof_1 removes spaces and passes the string to inte_atof, which in turn calls expr_inter for each expression. Port signals are described in the theory section: the port signal.

All functions are declared and described in detail in the shared header src/Include/expr.h; the reference is generated from these comments automatically.

Contents

File Role
expr_in1.cpp entry point expr_atof, recursive parsing expr_inter, number recognition expr_numbern
expr_com.cpp a single operation or function expr_comp; angle units expr_set_angle
expr_per.cpp variables expr_get_per/expr_set_per/expr_is_per; thread context
expr_err.cpp error code expr_set_error_cod/expr_get_error_cod
expremsg.cpp error text expr_get_error
get_err.cpp conversion of the code to a package message number get_expr_err
drv_expr.cpp console "calculator" for manual testing; not part of the build

Expression grammar

The expression must not contain spaces: the calling code removes them beforehand (i1nte_atof_1 removes spaces, tabs and \n line feeds).

Expression elements.

Element Notation Example
Number digits, an optional leading - sign, a decimal point and an exponent e with 1–3 digits (signed or unsigned); no longer than 40 characters -12, 0.5, 1.24e+17, 1e18
Variable one Latin letter, case-sensitive x, f, T
Brackets round ( ); curly { } are also taken into account when searching for operations (they are used by Inter) 2*(3+4)
Function a lower-case name immediately followed by ( sin(x)
Operations = + - * / ^ a=3, 2^-1

An exponent with E (capital letter) is not supported: 1E5 is the "abnormal function" error. A number greater than FLT_MAX (about 3.4·1038), for example 1e300, is an overflow error.

Parsing order. expr_inter recursively checks a substring in the following order:

  1. A number (expr_numbern) — the value via atof.
  2. A one-letter variable — the value from the variable table.
  3. Operations outside brackets in order of increasing precedence: =, then +, -, *, /, ^. For each operation the string is scanned from right to left; the operation found splits the string into a left and a right part, which are evaluated recursively. For + - * / the rightmost operation is taken, which gives left associativity (8/4/2 = 1). For ^ the leftmost one is taken, so exponentiation is right-associative: 2^3^2 = 2^(3^2) = 512.
  4. An expression entirely enclosed in round brackets — its contents are evaluated.
  5. A function: the beginning of the string is compared with the names abs( exp( log( sin( cos( tan(, sqrt( sinh( cosh( tanh( asin( acos( atan( and log10(; the rest of the string starting from the bracket is evaluated as the argument.
  6. Otherwise — the ERROR_FUNCTION error ("abnormal function").

Unary minus. A - sign at the beginning of the string gives an empty left operand, which is treated as zero: -2^2 = 0 - 2^2 = -4. A + or - sign immediately after another operation (2^-1, 2*-3) and the sign of a number's exponent (1.24e+17) are not treated as split points.

Assignment. a=expression assigns the value to the variable a and returns it. Only a single letter may stand on the left; the chain a=b=3 is the ERROR_VAR error.

Operations and functions

Each operation is performed by the expr_comp function. A result greater than FLT_MAX is treated as an overflow: an error is set and FLT_MAX (or 0) is returned.

Operation / function Error condition Error code
x+y, x-y, x*y result greater than FLT_MAX ERROR_OVERFLOW (-20)
x/y y=0 ERROR_DIV_0 (-15)
x^y, x>0 result greater than FLT_MAX (for 0<x<1 it is checked after the fact) ERROR_OVERFLOW (-20)
x^y, x≤0 fractional y; x=0 with y≤0 ERROR_POW (-16)
exp, sinh, cosh argument greater than ln(FLT_MAX)≈88.7 -EXP, -SINH, -COSH
log, log10 argument ≤0 -LOG, -LOG10
sqrt argument <0 -SQRT
sin, cos, tan argument magnitude greater than FLT_MAX_SIN = 65536 (in angle units) -SIN, -COS, -TAN
asin, acos argument magnitude greater than 1 -ASIN, -ACOS
abs, tanh, atan — —

A negative base with an integer exponent is allowed: (-2)^3 = -8; (-2)^0.5 is an error.

Angle units

The trigonometric functions work in degrees or radians depending on the global multiplier expr_angle:

sin(arg)=sin(arg·k),arcsin(v)=arcsinrad(v)/k,(1)

where k=π/180 in the EXPR_GRADUS mode and k=1 in the EXPR_RADIAN mode. The default is degrees. The TMCIndan library sets radians when it creates the task-file parameters, and then switches the mode according to the angle units written in the task file. The setting is one for the whole program and is not part of the thread context.

Errors

The error code is a negative number; 0 means no error. After the first error all subsequent calls of expr_inter and expr_comp return 0 immediately, so the code keeps the cause of the first error. expr_atof and inte_atof reset the code before evaluating.

Code Constant expr_get_error text
0 — all right
-1 -EXP overflow in function exp
-2 -LOG argument LOG <= 0 (bad)
-3 -SIN overflow in function sin (argument > 65536)
-4 -COS overflow in function cos (argument > 65536)
-5 -TAN overflow in function tan …
-7 -SQRT argument SQRT < 0 (bad)
-8 … -10 -SINH, -COSH, -TANH overflow in function sinh / cosh / tanh
-11, -12 -ASIN, -ACOS argument ASIN / ACOS > 1 (bad)
-14 -LOG10 argument LOG10 <=0 (bad)
-15 ERROR_DIV_0 division by zero in x/y
-16 ERROR_POW x^y: x<0 with a fractional y, or 0^y with y<=0
-17 ERROR_BRACKET abnormal bracket
-18 ERROR_FUNCTION abnormal function
-19 ERROR_EXPRESSION abnormal expression
-20 ERROR_OVERFLOW float overflow
-21 ERROR_RETURN bad return (the interpreter's internal return flag)
-22 ERROR_VAR bad parameter in =

The text is in English; the kernels append the expression string and the variable values to it and show it to the user through the error object CTmcLibError (TMCLibError). The function get_expr_err converts the code to the number 2400 + n from error1.h (constants ERROR_EXPR_*), but no message is output for that number.

Variables and parallel threads

Variables are stored in a table of 256 _real values, indexed by the character code of the name; an unassigned variable equals 0. The kernels write x, y, r, f (or t, f) into it via expr_set_per before each evaluation — at full precision, without conversion to a string.

The kernels build the grid nodes in several threads, and each thread evaluates formulas with its own coordinates. To keep the threads from interfering with each other, the library has a thread context EXPR_THREAD_CTX:

  1. A thread creates an EXPR_THREAD_CTX structure (usually on its own stack) and calls expr_thread_ctx_begin(&ctx). The current shared variables are copied into the context, the error code and the return value are zeroed, and the pointer to the context is stored in a thread_local variable.
  2. While the context is bound, expr_set_per/expr_get_per, the error code and the return value are read and written in that thread's context.
  3. At the end the thread calls expr_thread_ctx_end() and returns to the shared variables.

The angle units (expr_angle) are not part of the context — they must be chosen before the threads are started.

Pitfalls

Everything listed below is confirmed by the code and by test evaluations.

  1. The string is modified temporarily. During parsing expr_inter writes '\0' into lex[n] and into lex[4], lex[5], lex[6] and then restores them. The string must be writable (not a literal), and the buffer must be at least 7 characters long: for short strings the write goes past the terminating zero. The same string must not be evaluated from two threads at once.
  2. Overflow is checked only from above. For + - * an error is set if the result is greater than FLT_MAX; a negative result that is large in magnitude is not treated as an error (x=0-3e38; x*10 gives −3·1039 without an error).
  3. The limits are those of float. Although _real is double, numbers and results greater than FLT_MAX (about 3.4·1038) are treated as overflow.
  4. Trigonometry is in degrees by default — see "Angle units".
  5. Function names are lower-case only, and the exponent is only e: SIN(1) and 1E5 are the "abnormal function" error.
  6. A variable is a single letter. A two-letter name (ab) is the "abnormal function" error.