Библиотека exprint, часть Inter — интерпретатор формул

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

Интерпретатор Inter (каталог src/libs/inter) — надстройка над вычислителем Expr. Он позволяет записать в задании не одно выражение, а короткую программу: несколько операторов через ;, блоки {...}, условие if, цикл while и досрочный выход return. Inter и Expr собираются в одну статическую библиотеку exprint.

Именно интерпретатор вызывают ядра PlanarRT_H и PlanarRT_X для формул в задании .tpl (eps, N, B, sigma блоков, амплитуда и фаза сигнала на порту). Точка входа — i1nte_atof_1(строка, &результат): она удаляет из строки пробелы, табуляции и переводы строки \n, выполняет программу и возвращает код ошибки (0 — успех).

Объявления — в src/Include/inter.h; подробные описания функций inte_* и i1nte_atof_1 — в src/Include/expr.h, где они объявлены повторно.

Состав

Файл Роль
inte_in1.cpp i1nte_atof_1, inte_atof, разбор последовательностей и блоков inte_inter, удаление пробелов expr_del_Blanks1
inte_ope.cpp операторы return, if, while (inte_oper), поиск конца условия inte_select_blanck
inte_val.cpp хранение значения return (inte_set_inter_value/inte_get_inter_value)
drv_inte.cpp консольная программа для ручной проверки; в сборку не входит

Синтаксис программы

inte_inter разбирает подстроку так:

  1. Пустая строка или одиночная ; — значение 0.
  2. Строка целиком в фигурных скобках {...} — выполняется содержимое.
  3. Первая ; вне скобок (круглых и фигурных) делит строку: сначала выполняется левая часть, затем правая. Значение — значение правой части (если ; последняя — левой). Так значение программы равно значению последнего оператора.
  4. Иначе строка вычисляется как выражение Expr. Если Expr не распознал строку (код ERROR_FUNCTION), она пробуется как оператор return, if или while.
  5. Любая другая ошибка Expr прерывает выполнение.

Непарные скобки — ошибка ERROR_BRACKET.

Переменные — те же, что у Expr: одна латинская буква, значения общие для всей программы (и для следующих вызовов, пока их не перезапишут).

Операторы

Оператор Действие Значение оператора
return(e) вычисляет e, запоминает значение и прерывает программу e — оно же результат всей программы
if(c){S} выполняет S, если c≥0 значение S; если условие ложно — значение c (отрицательное)
while(c){S} выполняет S, пока c≥0 значение c после выхода из цикла

Условие истинно, если его значение не меньше нуля. Операций сравнения в языке нет: условие записывается разностью. Например, «x≥1» — это if(x-1){...}, «x<5» — if(4.999-x){...} или, для целых, if(4-x){...}.

Тело if и while нужно брать в фигурные скобки, если в нём есть операция вне скобок. Без скобок строка if(x-1)y=7 сначала разбирается как выражение, и присваивание if(x-1)y = 7 даёт ошибку ERROR_VAR («bad parameter in =»). Ветки else нет.

Как работает return. Оператор запоминает значение (inte_set_inter_value) и ставит служебный код ERROR_RETURN. Все вызовы inte_inter/expr_inter при ненулевом коде сразу возвращают 0, поэтому выполнение сворачивается до inte_atof; та видит ERROR_RETURN, берёт запомненное значение и сбрасывает код. return внутри while и if работает так же.

Защита от зацикливания. while выполняет не более 10 000 000 итераций; после этого ставится ошибка ERROR_EXPRESSION.

Примеры (результаты проверены по коду):

Программа Результат
a=3;a*2 6
x=5;if(x-1){y=7};y 7
x=0;if(x-1){y=7} -1 (условие ложно, значение — условие)
i=0;while(9-i){i=i+1};i 10
i=0;while(1){i=i+1;if(i-5){return(i)}} 5
return(5);7 5
x=5;if(x-1)y=7 ошибка -22 (тело без фигурных скобок)

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

Значение return хранится так же, как переменные и код ошибки: в контексте потока EXPR_THREAD_CTX, если он привязан, иначе в общей статической переменной. Порядок работы с контекстом описан на странице Expr: переменные и потоки.

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

  1. Удаляются только пробел, табуляция и \n. Символ возврата каретки \r функция expr_del_Blanks1 не трогает; если он попадёт в формулу, разбор закончится ошибкой. Перед вызовом строку нужно очищать от концов строк Windows.
  2. Строка изменяется на месте: из неё удаляются пробелы, а при разборе временно пишутся нули (см. Expr: подводные камни).
  3. Условие — «не меньше нуля», а не «не равно нулю». if(0){...} выполняет тело; while(1){...} без return упирается в предел итераций.
  4. Ошибка внутри программы обнуляет результат: i1nte_atof_1 возвращает в r значение 0 вместе с ненулевым кодом ошибки.

exprint library, Inter part — the formula interpreter

Purpose and place in the package

The Inter interpreter (directory src/libs/inter) is a layer on top of the Expr evaluator. It lets a task file contain not just a single expression but a short program: several statements separated by ;, {...} blocks, an if condition, a while loop and an early exit with return. Inter and Expr are built into a single static library, exprint.

It is the interpreter that the PlanarRT_H and PlanarRT_X kernels call for formulas in a .tpl task file (eps, N, B, sigma of blocks, amplitude and phase of the port signal). The entry point is i1nte_atof_1(string, &result): it removes spaces, tabs and \n line feeds from the string, executes the program and returns an error code (0 — success).

The declarations are in src/Include/inter.h; detailed descriptions of the inte_* functions and of i1nte_atof_1 are in src/Include/expr.h, where they are declared again.

Contents

File Role
inte_in1.cpp i1nte_atof_1, inte_atof, parsing of sequences and blocks inte_inter, space removal expr_del_Blanks1
inte_ope.cpp the return, if, while statements (inte_oper), search for the end of a condition inte_select_blanck
inte_val.cpp storage of the return value (inte_set_inter_value/inte_get_inter_value)
drv_inte.cpp console program for manual testing; not part of the build

Program syntax

inte_inter parses a substring as follows:

  1. An empty string or a single ; — value 0.
  2. A string entirely enclosed in curly braces {...} — its contents are executed.
  3. The first ; outside brackets (round and curly) splits the string: the left part is executed first, then the right part. The value is the value of the right part (if the ; is the last character — of the left part). Thus the value of the program equals the value of the last statement.
  4. Otherwise the string is evaluated as an Expr expression. If Expr did not recognise the string (code ERROR_FUNCTION), it is tried as a return, if or while statement.
  5. Any other Expr error aborts execution.

Unbalanced brackets are the ERROR_BRACKET error.

Variables are the same as in Expr: a single Latin letter, with values shared by the whole program (and by subsequent calls until they are overwritten).

Statements

Statement Action Value of the statement
return(e) evaluates e, stores the value and terminates the program e — which is also the result of the whole program
if(c){S} executes S if c≥0 the value of S; if the condition is false — the value of c (negative)
while(c){S} executes S while c≥0 the value of c after leaving the loop

A condition is true if its value is not less than zero. The language has no comparison operators: a condition is written as a difference. For example, "x≥1" is if(x-1){...}, "x<5" is if(4.999-x){...} or, for integers, if(4-x){...}.

The body of if and while must be enclosed in curly braces if it contains an operation outside brackets. Without braces the string if(x-1)y=7 is first parsed as an expression, and the assignment if(x-1)y = 7 gives the error ERROR_VAR ("bad parameter in ="). There is no else branch.

How return works. The statement stores the value (inte_set_inter_value) and sets the service code ERROR_RETURN. All inte_inter/expr_inter calls return 0 immediately when the code is non-zero, so execution unwinds up to inte_atof; that function sees ERROR_RETURN, takes the stored value and resets the code. return inside while and if works the same way.

Protection against infinite loops. while performs at most 10,000,000 iterations; after that the error ERROR_EXPRESSION is set.

Examples (results verified against the code):

Program Result
a=3;a*2 6
x=5;if(x-1){y=7};y 7
x=0;if(x-1){y=7} -1 (the condition is false, the value is the condition)
i=0;while(9-i){i=i+1};i 10
i=0;while(1){i=i+1;if(i-5){return(i)}} 5
return(5);7 5
x=5;if(x-1)y=7 error -22 (body without curly braces)

Parallel threads

The return value is stored the same way as variables and the error code: in the thread context EXPR_THREAD_CTX if one is bound, otherwise in a shared static variable. The procedure for working with the context is described on the Expr page: variables and threads.

Pitfalls

  1. Only space, tab and \n are removed. The carriage return character \r is not touched by expr_del_Blanks1; if it gets into a formula, parsing ends with an error. Before the call the string must be cleaned of Windows line endings.
  2. The string is modified in place: spaces are removed from it, and zeros are temporarily written into it during parsing (see Expr: pitfalls).
  3. The condition is "not less than zero", not "not equal to zero". if(0){...} executes the body; while(1){...} without return runs into the iteration limit.
  4. An error inside the program zeroes the result: i1nte_atof_1 returns in r the value 0 together with a non-zero error code.