Библиотека prepr — препроцессор файлов задания

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

Библиотека prepr (каталог src/libs/prepr, общий заголовок src/Include/prepr1.h) — текстовый препроцессор файлов задания .tpl. Она выполняется до разбора задания и превращает исходный текст, удобный человеку, в плоский текст, который понимает разборщик:

  • убирает комментарии !;
  • склеивает строки, разорванные переносом \\ (два обратных слеша);
  • вставляет на место директив #include содержимое указанных файлов;
  • раскрывает макросы #define с параметрами.

Место в конвейере пакета (см. обзор теории):

 .tpl (+ файлы #include)
      │  MainPrepr1()                      библиотека prepr
      ▼
 <имя>.tpl~$Prepr$~<PID>   ← развёрнутый текст задания
      │  CTmcRTH_Indan (разбор секций)     библиотека TMCIndan
      ▼
 ядро PlanarRT_H / PlanarRT_X → файлы результатов → вьюверы

Препроцессор вызывается из CTmcRTH_Indan::MakePreprFile() → MainPrepr() (libs/tmcindan/tmcrth_indan.cpp) при открытии задания счётным ядром — общая часть обоих ядер, H и X. Редактор заданий TPL Designer содержит собственную реализацию того же препроцессора (см. страницу редактора); эталоном для неё служит файл ~$Prepr$~, который строит эта библиотека.

Библиотека написана на C в стиле DOS-версии TAMIC (модификаторы _far, fortran определены пустыми) и компилируется без изменений. Все сообщения об ошибках — на английском, они без перевода выводятся в строку состояния ядра.

Состав

Файл В сборке Роль
include/prepr1.h да структуры BUFFER, MACROS, константы размеров, коды возврата, объявления всех функций
prep_mn.cpp да точка входа MainPrepr1(), главный проход main_preproc(), глобальные buf, szError, szPathName, put_error_messege, DeleteComment
prep_ld.cpp да buf_init() — создание связного буфера
def_str.cpp да операции с буфером: чтение записи, вставка, удаление, сравнение, чтение лексем и фактических параметров
read_buf.cpp да read_buf() — чтение строки до '\n' (в пакете не вызывается)
defmis.cpp да def_include() (вставка файлов), def_sl() (перенос \\), def_macro() (поиск #define)
def_macr.cpp да макросы: разбор заголовка и тела, подстановка в текст
def_erd.cpp да проверка повторных #define, временный файл макросов
def_dest.cpp да dest_prep() — удаление временного файла макросов
def_er.cpp да def_err_get() — тексты кодов возврата
stdafx.h нет* предкомпилированный заголовок MFC-проекта; подключается только из stdafx.cpp
stdafx.cpp, dr_buf.cpp, incpath.cpp нет наследие: файл предкомпиляции MFC, отладочный DOS-драйвер, путь поиска #include

* Файл лежит в каталоге собираемой библиотеки, но ни один собираемый файл его не подключает.

Состав сборки задан в src/CMakeLists.txt (tmc_add_library(prepr ...)) и совпадает с Windows-проектом. Библиотека зависит от TMCLibError и взаимно от sfile95: prepr вызывает alloc_mem_err/free_mem из sfile95, а функции sfile95 пишут ошибки через put_error_messege, определённую в prep_mn.cpp. Поэтому при компоновке программ библиотеки собираются в группу (--start-group … --end-group).

Порядок обработки задания

MainPrepr1(файл_результата, файл_задания, папка_задания, текст_ошибки) выделяет две рабочие строки по 500 000 байт (szError, szPathName), проверяет длину имён (не более 511 символов), вызывает main_preproc(), затем освобождает буфер (unload_prep_buf) и удаляет временный файл макросов (dest_prep). Пустой текст ошибки — успех.

main_preproc() выполняет шаги строго в таком порядке:

  1. Удаление старого результата. Файл результата предыдущего запуска удаляется, чтобы после ошибки разборщик не прочитал устаревший текст.
  2. Чтение задания. Файл читается построчно (fgets, до 499 999 символов за раз). У каждой строки сразу отрезается комментарий ! (DeleteComment), строка заносится в буфер отдельной записью, оканчивающейся '\0'.
  3. Перенос строк и #include (def_include): сначала по всему тексту склеиваются строки с переносом \\ (def_sl), затем вставляются включаемые файлы; после каждой вставки склейка выполняется заново.
  4. Временный файл макросов (load_vr_file): тексты всех #define записываются в $$vr$$s<PID>.prc в папке задания.
  5. Проверка повторных определений (def_err_dec).
  6. Раскрытие макросов (def_main_macro).
  7. Запись результата. Текст буфера записывается в файл результата.

Если на шагах 4–6 возникла ошибка, файл результата не создаётся. Ошибка шага 3 (#include) обрабатывается иначе: текст ошибки возвращается, но файл результата всё равно записывается — с тем, что успели обработать.

Связный буфер

Весь текст задания — вместе со вставленными файлами и раскрытыми макросами — хранится в одном буфере BUFFER из NMAX = 30 000 000 узлов. Узел — символ lsplex[i] и индекс следующего узла ilex[i] (-1 — конец списка). Два списка делят один массив:

  • список текста начинается с узла 0 (символ в нём не используется);
  • список свободных узлов начинается с inp_p_nul (сразу после buf_init() — узел 1, в цепочку связаны все узлы 1 … NMAX−1).

Текущая позиция inp_p — индекс узла; все операции работают с символами после него:

Операция Что делает inp_p после
buf_gets читает запись до '\0' на '\0' прочитанной записи
buf_puts / buf_puts3 вставляет строку с '\0' не меняется / на вставленный '\0'
buf_puts1 / buf_puts2 вставляет символы без '\0' не меняется / на последний вставленный
buf_dels(n) удаляет n символов, узлы уходят в свободный список не меняется
buf_cmpn, buf_cmpn2 сравнивает следующие символы с образцом не меняется

Вставка и удаление не сдвигают память, поэтому подстановка большого макроса в начало большого задания стоит столько же, сколько в конец. Цена — память: 5·NMAX байт (символ + индекс int), около 150 МБ на время работы препроцессора.

Запись — фрагмент текста до '\0'. Сразу после чтения запись совпадает со строкой файла (с её '\n'); после склейки \\ одна запись содержит несколько строк. Директивы #include и #define обрабатываются целыми записями.

Комментарии !

Знак ! в любом месте строки начинает комментарий: текст от ! до конца строки заменяется на пробел и перевод строки (DeleteComment). Это делается для каждой строки задания и каждой строки включаемого файла до всех остальных шагов. Внутри строк кавычек нет — ! в значении параметра тоже будет воспринят как комментарий.

Перенос строки \\

Маркер переноса — ровно два обратных слеша \\ подряд (def_sl). Найдя его, препроцессор удаляет маркер, весь остаток строки после него и разделитель записей '\0', а на их место ставит пробел и перевод строки. Следующая строка файла становится продолжением той же записи. Отсюда следствия:

  • Текст после \\ до конца строки отбрасывается — это место для комментария.
  • Один обратный слеш переносом не является: строка остаётся отдельной записью. Многострочный #define с одиночными \ обрывается на первой строке, а остальные строки тела попадают в результат как обычный текст с неподставленными параметрами; ошибку затем выдаёт разборщик задания.
  • У последней строки тела макроса переноса нет — по этому признаку кончается определение.
  • Перевод строки внутри записи сохраняется, поэтому тело макроса подставляется в несколько строк.
  • Комментарий ! удаляется раньше склейки: если ! стоит в строке перед \\, маркер переноса будет удалён вместе с комментарием и перенос пропадёт.

Директива #include

#include имя_файла
  • Распознаётся последовательность #include с пробелом или табуляцией после неё (buf_cmpn2) — в любом месте текста; принято писать её с начала строки.
  • Имя файла — остаток записи после директивы без ведущих пробелов. Хвостовые пробелы не отрезаются и входят в имя.
  • Полное имя строится как <папка задания>\<имя>: включаемый файл ищется только относительно папки задания. Подпапки допустимы (parts\step.h).
  • Запрещены (def_include_name_outside): любое : (имя диска, поток NTFS) и элемент пути, состоящий только из точек (.., ...). Ошибка: #include: the file must be in the task folder or in its subfolder.
  • Длина полного имени — не более FILENAME_MAX (260 символов в сборке для Windows).
  • Строка директивы удаляется, текст файла вставляется на её место построчно; у каждой строки отрезается комментарий !. Затем по всему тексту повторяется склейка \\.
  • Просмотр продолжается с начала вставленного текста, поэтому вложенные #include работают. Глубина вложенности — не более 64 (DEF_INCLUDE_DEPTH_MAX); превышение означает, как правило, файл, включающий сам себя: #include: more than 64 nested files (does the file include itself?).

Типичное применение — вынести макрос шага #STEP в файл .h рядом с заданием и подключить его до вызовов макроса.

Директива #define

#define ИМЯ п1; п2; ... пN; @ТЕЛО
#define ИМЯ @ТЕЛО

Разбор заголовка — def_separ_mac_name(), конечный автомат по символам после #define (с пробелом или табуляцией):

  • Имя — первый непробельный фрагмент до пробела или табуляции. Если сразу за именем стоит @, макрос без параметров.
  • Каждый формальный параметр заканчивается ;, в том числе последний перед @. Пробелы вокруг параметров допускаются, пробел внутри имени параметра — ошибка.
  • @ (DEF_SEPARATOR) отделяет заголовок от тела. Всё после @ до конца записи — тело (с учётом склеенных \\ строк). Последний символ записи (перевод строки) отбрасывается.
  • Формальных параметров — не более 58 (размер массива BUF_PAR_MAX = 60 вмещает имя и параметры, проверка срабатывает на 59-м).

Разрезание тела — def_set_formal_param(). Тело делится на лексемы (def_gets): идентификатор из букв A–Z, a–z, цифр и _ или один любой другой символ. Каждая лексема, совпадающая с именем формального параметра, вырезается, а текст между такими местами сохраняется фрагментами m1[k]; у фрагмента запоминается номер параметра, который надо вставить перед ним (im1[k], -1 — ничего). Совпадение проверяется целыми лексемами: параметр d заменит d в DELTA d;, но не букву в слове DELTA.

Пример из учебного задания (файл LR2_step.h, тело сокращено):

#define lr2step Freq__; Tfile__; Sfile__; @\\
#STEP\\
#PARM\\
 FREQ   Freq__;\\
 ...
#END_LINK

Вызов макроса и подстановка

ИМЯ ф1; ф2; ... фN;

def_subst_mac() просматривает текст по лексемам (def_buf_gets_mac), начиная с места определения и до конца текста. Найдя лексему, равную имени:

  1. Если у макроса есть параметры, пропускается ровно один символ после имени (обычно пробел).
  2. Читаются N фактических параметров (def_buf_gets_param): каждый — текст до ;, стоящей вне круглых скобок. Поэтому значение параметра может содержать ; внутри скобок. Если значение целиком заключено в скобки ( … ), внешние скобки заменяются пробелами.
  3. Вызов удаляется, на его место пишутся фрагменты тела, перед каждым — значение соответствующего параметра.
  4. Просмотр продолжается с начала подставленного текста — вызовы внутри тела раскрываются тем же проходом.

Подстановка чисто текстовая, без вычислений. Выражения в теле надо брать в скобки: при #define Len @ 38+12 текст Len/2 превратится в 38+12/2.

Если запись кончилась раньше, чем прочитаны все N параметров, — ошибка Fact parameter's (macro ИМЯ) или Fact parameters: a parameter or ';' is missing (macro ИМЯ). Макрос, тело которого вызывает его самого, раскрывается бесконечно, пока не кончится буфер: Small buffer (is the macro recursive?) (macro ИМЯ).

Строка #define после раскрытия удаляется из текста целиком и в результат не попадает.

Порядок подстановки макросов

def_main_macro() сначала находит все определения, затем раскрывает их от последнего к первому. Вместе с тем, что каждый макрос подставляется только ниже своего определения, это даёт правила:

  • Макрос действует только в тексте ниже своего #define.
  • В теле макроса можно использовать макросы, определённые выше него: внешний макрос раскрывается первым, а более ранний затем раскрывается уже в подставленном тексте.
  • Макрос, определённый ниже, в теле более раннего макроса не раскрывается — его имя останется в результате как есть.

Поэтому в учебных заданиях сначала идут простые макросы-константы (#define a @ ( 60.0 )), затем #include файла с макросом шага, затем вызовы.

Повторные определения

def_err_dec() разбирает заголовки всех #define, сортирует имена и ищет первое по тексту определение, имя которого встречается ещё раз. Повтор — ошибка Redefined ИМЯ, даже если тела одинаковы. Ошибка в заголовке любого #define выдаётся на этом же шаге с текстом самой строки: Missing separator in: #define ....

Временный файл макросов

load_vr_file() записывает тексты всех директив #define (с пробелом) в файл $$vr$$s<PID>.prc в папке задания (PID — номер процесса ядра, чтобы два одновременных запуска не мешали друг другу; имя строит vr_mac_file_name()). Многострочные определения пишутся с переносом \\ в конце строк. dest_prep() удаляет файл в конце каждого прохода. Файл другими частями пакета не читается, но для его создания нужно право записи в папку задания — без него препроцессор завершается ошибкой Can't open file ... for writing.

Отладочный вывод ~$Prepr$~

Результат препроцессора — файл рядом с заданием. Имя строит CTmcRTH_Indan::SetTplFileName():

<полное имя задания>~$Prepr$~<PID>      например  wg.tpl~$Prepr$~12345
<полное имя задания>~$Prepr$~           если полное имя с номером длиннее 259 символов

Именно этот файл читает разборщик задания, поэтому он — главный инструмент отладки макросов: в нём видно, раскрылся ли каждый вызов, сколько получилось секций #STEP, не осталось ли неподставленных имён параметров. Файл создаётся при открытии задания ядром и удаляется, когда ядро закрывает задание (CTmcRTH_Indan::DeleteData); пока задание открыто, его можно открыть любым текстовым редактором. Если полное имя файла результата не помещается даже без номера (259 символов), ядро сообщает об этом и предлагает перенести задание в папку с более коротким путём.

Ограничения

Величина Предел Где задано Что при превышении
Весь текст после вставок и подстановок 30 000 000 символов NMAX Small buffer / Buffer is small
Одна запись #define или #include (с учётом склейки \\) 500 000 символов BUF_STR_N_MAX #define: the line is longer than 500000 characters ...
Одна строка при чтении файла 499 999 символов за fgets BUF_STR_INLINE_MAX строка читается частями
Вложенность #include 64 DEF_INCLUDE_DEPTH_MAX #include: more than 64 nested files ...
Полное имя включаемого файла 260 символов (Windows) FILENAME_MAX #include: the file name with the task folder is too long ...
Имя файла задания и файла результата 511 символов MainPrepr1 the task file name is too long ...
Формальных параметров у макроса 58 BUF_PAR_MAX Number of formal parameters > BUF_PAR_MAX
Фрагментов тела макроса 799 999 BUF_MASKA_MAX Maska num

Сообщения об ошибках

Текст ошибки собирается в szError функцией put_error_messege и возвращается из MainPrepr1(); ядро показывает его в строке состояния. Основные тексты:

Текст Причина
file X isn't open не открылся файл задания или не создаётся файл результата
can't open include file X файл #include не найден в папке задания
#include: the file must be in the task folder ... в имени есть .. или :
Redefined ИМЯ макрос определён дважды
Missing separator ..., Missing separator or mac name в #define нет @ или пустое имя
Missing formal parameter's пропущен параметр, нет ; после последнего параметра, пробел в имени параметра
Fact parameter's (macro ИМЯ) строка вызова кончилась раньше, чем прочитаны все параметры (нет завершающей ;)
Fact parameters: a parameter or ';' is missing (macro ИМЯ) очередной параметр начинается с перевода строки — в вызове меньше параметров, чем в определении
Small buffer (is the macro recursive?) (macro ИМЯ) буфер переполнен при подстановке, чаще всего — рекурсивный макрос
preprocessor error N (...) функция вернула код без текста; текст по коду даёт def_err_get()

Коды возврата функций (BUF_NULL = 0 … ERROR_INIT = −11) перечислены в prepr1.h; таблица их английских названий — в def_er.cpp.

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

  • Перенос — только \\. Один обратный слеш не переносит строку (см. перенос строки). При генерации файлов скриптами слеши легко теряются при экранировании — проверяйте результат в файле ~$Prepr$~.
  • ! перед \\ убивает перенос. Комментарий в строке тела макроса ставьте после \\, а не до него.
  • Последняя строка файла. Определение #define в последней строке файла без перевода строки теряет последний символ тела: он отбрасывается как перевод строки.
  • Имена формальных параметров заменяются в теле везде, где встречаются как целая лексема. Короткие имена (d, L) легко совпадают со словами тела — поэтому в примерах пакета параметры имеют вид Freq__.
  • Имя макроса тоже заменяется везде ниже определения, где оно стоит целой лексемой, в том числе внутри других конструкций задания. Для макросов с параметрами каждое такое вхождение считается вызовом и требует параметров.
  • Скобки в выражениях. Подстановка текстовая: #define W @ ( 4*a/3 ), а не #define W @ 4*a/3.
  • Порядок определений. Макрос, используемый в теле другого, должен быть определён выше (см. порядок подстановки).
  • Право записи в папку задания нужно и для временного файла макросов, и для файла результата.
  • Однопоточность. Библиотека хранит состояние в глобальных переменных; в одном процессе одновременно может работать только один проход препроцессора.

prepr library — the task-file preprocessor

Purpose and place in the package

The prepr library (directory src/libs/prepr, shared header src/Include/prepr1.h) is a text preprocessor for .tpl task files. It runs before the task file is parsed and turns the human-friendly source text into flat text that the parser understands:

  • removes ! comments;
  • joins lines split by the \\ continuation (two backslashes);
  • inserts the contents of the specified files in place of #include directives;
  • expands #define macros with parameters.

Place in the package pipeline (see the theory overview):

 .tpl (+ #include files)
      │  MainPrepr1()                      prepr library
      ▼
 <name>.tpl~$Prepr$~<PID>   ← expanded task-file text
      │  CTmcRTH_Indan (section parsing)   TMCIndan library
      ▼
 PlanarRT_H / PlanarRT_X kernel → result files → viewers

The preprocessor is called from CTmcRTH_Indan::MakePreprFile() → MainPrepr() (libs/tmcindan/tmcrth_indan.cpp) when a compute kernel opens a task file — the part shared by both kernels, H and X. The TPL Designer task-file editor contains its own implementation of the same preprocessor (see the editor page); its reference is the ~$Prepr$~ file built by this library.

The library is written in C in the style of the DOS version of TAMIC (the modifiers _far, fortran are defined as empty) and compiles without changes. All error messages are in English; they are shown untranslated in the kernel status bar.

Contents

File In the build Role
include/prepr1.h yes the BUFFER, MACROS structures, size constants, return codes, declarations of all functions
prep_mn.cpp yes entry point MainPrepr1(), main pass main_preproc(), globals buf, szError, szPathName, put_error_messege, DeleteComment
prep_ld.cpp yes buf_init() — creation of the linked buffer
def_str.cpp yes buffer operations: reading a record, insertion, deletion, comparison, reading tokens and actual parameters
read_buf.cpp yes read_buf() — reading a line up to '\n' (not called in the package)
defmis.cpp yes def_include() (file insertion), def_sl() (\\ continuation), def_macro() (search for #define)
def_macr.cpp yes macros: parsing of the header and body, substitution into the text
def_erd.cpp yes check for repeated #define, temporary macro file
def_dest.cpp yes dest_prep() — deletion of the temporary macro file
def_er.cpp yes def_err_get() — texts of the return codes
stdafx.h no* precompiled header of the MFC project; included only from stdafx.cpp
stdafx.cpp, dr_buf.cpp, incpath.cpp no legacy: MFC precompilation file, DOS debug driver, #include search path

* The file is in the directory of a library that is built, but no file that is built includes it.

The build contents are defined in src/CMakeLists.txt (tmc_add_library(prepr ...)) and match the Windows project. The library depends on TMCLibError and mutually on sfile95: prepr calls alloc_mem_err/free_mem from sfile95, while the sfile95 functions report errors through put_error_messege, defined in prep_mn.cpp. Therefore, when programs are linked, the libraries are put into a group (--start-group … --end-group).

Task-file processing order

MainPrepr1(result_file, task_file, task_folder, error_text) allocates two working strings of 500,000 bytes each (szError, szPathName), checks the length of the names (at most 511 characters), calls main_preproc(), then frees the buffer (unload_prep_buf) and deletes the temporary macro file (dest_prep). An empty error text means success.

main_preproc() performs the steps strictly in this order:

  1. Deleting the old result. The result file of the previous run is deleted so that after an error the parser does not read stale text.
  2. Reading the task file. The file is read line by line (fgets, up to 499,999 characters at a time). The ! comment is cut off each line immediately (DeleteComment), and the line is put into the buffer as a separate record ending with '\0'.
  3. Line continuation and #include (def_include): first, lines with the \\ continuation are joined throughout the text (def_sl), then the included files are inserted; after each insertion the joining is performed again.
  4. Temporary macro file (load_vr_file): the texts of all #define directives are written to $$vr$$s<PID>.prc in the task folder.
  5. Check for repeated definitions (def_err_dec).
  6. Macro expansion (def_main_macro).
  7. Writing the result. The buffer text is written to the result file.

If an error occurs in steps 4–6, the result file is not created. An error in step 3 (#include) is handled differently: the error text is returned, but the result file is written anyway — with whatever has been processed so far.

The linked buffer

The entire task-file text — together with the inserted files and expanded macros — is stored in a single BUFFER of NMAX = 30,000,000 nodes. A node is a character lsplex[i] and the index of the next node ilex[i] (-1 — end of list). Two lists share one array:

  • the text list starts at node 0 (the character in it is not used);
  • the free-node list starts at inp_p_nul (right after buf_init() — node 1, with all nodes 1 … NMAX−1 linked into the chain).

The current position inp_p is a node index; all operations work on the characters after it:

Operation What it does inp_p afterwards
buf_gets reads a record up to '\0' on the '\0' of the record read
buf_puts / buf_puts3 inserts a string with '\0' unchanged / on the inserted '\0'
buf_puts1 / buf_puts2 inserts characters without '\0' unchanged / on the last inserted one
buf_dels(n) deletes n characters, the nodes go to the free list unchanged
buf_cmpn, buf_cmpn2 compares the following characters with a pattern unchanged

Insertion and deletion do not shift memory, so substituting a large macro at the beginning of a large task file costs as much as at the end. The price is memory: 5·NMAX bytes (character + int index), about 150 MB while the preprocessor runs.

A record is a fragment of text up to '\0'. Right after reading, a record coincides with a line of the file (with its '\n'); after \\ joining, one record contains several lines. The #include and #define directives are processed as whole records.

! comments

The ! sign anywhere in a line starts a comment: the text from ! to the end of the line is replaced by a space and a line feed (DeleteComment). This is done for every line of the task file and every line of an included file before all other steps. There are no quotes inside lines — a ! in a parameter value will also be treated as a comment.

The \\ line continuation

The continuation marker is exactly two backslashes \\ in a row (def_sl). When it finds one, the preprocessor removes the marker, the whole rest of the line after it and the record separator '\0', and puts a space and a line feed in their place. The next line of the file becomes a continuation of the same record. Consequences:

  • Text after \\ up to the end of the line is discarded — this is a place for a comment.
  • One backslash is not a continuation: the line remains a separate record. A multi-line #define with single \ breaks off at the first line, and the remaining lines of the body end up in the result as ordinary text with unsubstituted parameters; the task-file parser then reports an error.
  • The last line of a macro body has no continuation — this is how the end of the definition is recognised.
  • A line feed inside a record is kept, so the macro body is substituted as several lines.
  • The ! comment is removed before joining: if ! stands in a line before \\, the continuation marker is removed together with the comment and the continuation is lost.

The #include directive

#include file_name
  • The sequence #include followed by a space or tab is recognised (buf_cmpn2) — anywhere in the text; it is customary to write it at the beginning of a line.
  • The file name is the rest of the record after the directive without leading spaces. Trailing spaces are not cut off and become part of the name.
  • The full name is built as <task folder>\<name>: the included file is searched for only relative to the task folder. Subfolders are allowed (parts\step.h).
  • Forbidden (def_include_name_outside): any : (drive letter, NTFS stream) and a path element consisting only of dots (.., ...). Error: #include: the file must be in the task folder or in its subfolder.
  • The length of the full name is at most FILENAME_MAX (260 characters in the Windows build).
  • The directive line is deleted, and the file text is inserted in its place line by line; the ! comment is cut off each line. Then \\ joining is repeated throughout the text.
  • Scanning continues from the beginning of the inserted text, so nested #include directives work. The nesting depth is at most 64 (DEF_INCLUDE_DEPTH_MAX); exceeding it usually means a file that includes itself: #include: more than 64 nested files (does the file include itself?).

A typical use is to move the #STEP macro into an .h file next to the task file and include it before the macro calls.

The #define directive

#define NAME p1; p2; ... pN; @BODY
#define NAME @BODY

Header parsing — def_separ_mac_name(), a character-level finite-state machine after #define (followed by a space or tab):

  • The name is the first non-blank fragment up to a space or tab. If @ follows the name immediately, the macro has no parameters.
  • Each formal parameter ends with ;, including the last one before @. Spaces around parameters are allowed; a space inside a parameter name is an error.
  • @ (DEF_SEPARATOR) separates the header from the body. Everything after @ up to the end of the record is the body (including the lines joined with \\). The last character of the record (the line feed) is discarded.
  • There are at most 58 formal parameters (the array size BUF_PAR_MAX = 60 holds the name and the parameters; the check triggers on the 59th).

Body splitting — def_set_formal_param(). The body is divided into tokens (def_gets): an identifier of the letters A–Z, a–z, digits and _, or any other single character. Each token that matches the name of a formal parameter is cut out, and the text between such places is saved as fragments m1[k]; for each fragment the number of the parameter to be inserted before it is remembered (im1[k], -1 — nothing). Matching is checked on whole tokens: the parameter d will replace d in DELTA d;, but not a letter in the word DELTA.

An example from a training task file (file LR2_step.h, body shortened):

#define lr2step Freq__; Tfile__; Sfile__; @\\
#STEP\\
#PARM\\
 FREQ   Freq__;\\
 ...
#END_LINK

Macro call and substitution

NAME a1; a2; ... aN;

def_subst_mac() scans the text token by token (def_buf_gets_mac), starting from the place of the definition up to the end of the text. When it finds a token equal to the name:

  1. If the macro has parameters, exactly one character after the name is skipped (usually a space).
  2. N actual parameters are read (def_buf_gets_param): each is the text up to a ; standing outside round brackets. Therefore a parameter value may contain ; inside brackets. If the value is entirely enclosed in brackets ( … ), the outer brackets are replaced by spaces.
  3. The call is deleted, and the body fragments are written in its place, each preceded by the value of the corresponding parameter.
  4. Scanning continues from the beginning of the substituted text — calls inside the body are expanded in the same pass.

Substitution is purely textual, without evaluation. Expressions in the body must be enclosed in brackets: with #define Len @ 38+12 the text Len/2 turns into 38+12/2.

If the record ends before all N parameters have been read, the error is Fact parameter's (macro NAME) or Fact parameters: a parameter or ';' is missing (macro NAME). A macro whose body calls itself is expanded endlessly until the buffer runs out: Small buffer (is the macro recursive?) (macro NAME).

After expansion the #define line is removed from the text entirely and does not get into the result.

Macro substitution order

def_main_macro() first finds all definitions, then expands them from the last to the first. Combined with the fact that each macro is substituted only below its definition, this gives the rules:

  • A macro takes effect only in the text below its #define.
  • The body of a macro may use macros defined above it: the outer macro is expanded first, and the earlier one is then expanded in the already substituted text.
  • A macro defined below is not expanded in the body of an earlier macro — its name remains in the result as is.

That is why the training task files first have simple constant macros (#define a @ ( 60.0 )), then the #include of the file with the step macro, then the calls.

Repeated definitions

def_err_dec() parses the headers of all #define directives, sorts the names and looks for the first definition in the text whose name occurs again. A repetition is the error Redefined NAME, even if the bodies are identical. An error in the header of any #define is reported at the same step with the text of the line itself: Missing separator in: #define ....

Temporary macro file

load_vr_file() writes the texts of all #define directives (with a space) to the file $$vr$$s<PID>.prc in the task folder (PID is the kernel process number, so that two simultaneous runs do not interfere with each other; the name is built by vr_mac_file_name()). Multi-line definitions are written with the \\ continuation at the end of lines. dest_prep() deletes the file at the end of each pass. The file is not read by other parts of the package, but creating it requires write permission for the task folder — without it the preprocessor fails with the error Can't open file ... for writing.

Debug output ~$Prepr$~

The preprocessor result is a file next to the task file. The name is built by CTmcRTH_Indan::SetTplFileName():

<full task-file name>~$Prepr$~<PID>      for example  wg.tpl~$Prepr$~12345
<full task-file name>~$Prepr$~           if the full name with the number is longer than 259 characters

It is this file that the task-file parser reads, so it is the main tool for debugging macros: it shows whether each call has been expanded, how many #STEP sections there are, and whether any unsubstituted parameter names remain. The file is created when the kernel opens the task file and deleted when the kernel closes the task file (CTmcRTH_Indan::DeleteData); while the task file is open, it can be opened in any text editor. If the full name of the result file does not fit even without the number (259 characters), the kernel reports this and suggests moving the task file to a folder with a shorter path.

Limits

Quantity Limit Where it is set What happens when exceeded
The whole text after insertions and substitutions 30,000,000 characters NMAX Small buffer / Buffer is small
One #define or #include record (including \\ joining) 500,000 characters BUF_STR_N_MAX #define: the line is longer than 500000 characters ...
One line when reading a file 499,999 characters per fgets BUF_STR_INLINE_MAX the line is read in parts
#include nesting 64 DEF_INCLUDE_DEPTH_MAX #include: more than 64 nested files ...
Full name of an included file 260 characters (Windows) FILENAME_MAX #include: the file name with the task folder is too long ...
Name of the task file and of the result file 511 characters MainPrepr1 the task file name is too long ...
Formal parameters of a macro 58 BUF_PAR_MAX Number of formal parameters > BUF_PAR_MAX
Fragments of a macro body 799,999 BUF_MASKA_MAX Maska num

Error messages

The error text is assembled in szError by the function put_error_messege and returned from MainPrepr1(); the kernel shows it in the status bar. The main texts:

Text Cause
file X isn't open the task file failed to open or the result file cannot be created
can't open include file X the #include file was not found in the task folder
#include: the file must be in the task folder ... the name contains .. or :
Redefined NAME the macro is defined twice
Missing separator ..., Missing separator or mac name the #define has no @ or the name is empty
Missing formal parameter's a parameter is missing, there is no ; after the last parameter, a space in a parameter name
Fact parameter's (macro NAME) the call line ended before all parameters were read (no terminating ;)
Fact parameters: a parameter or ';' is missing (macro NAME) the next parameter starts with a line feed — the call has fewer parameters than the definition
Small buffer (is the macro recursive?) (macro NAME) the buffer overflowed during substitution, most often a recursive macro
preprocessor error N (...) a function returned a code without text; the text for the code is given by def_err_get()

The function return codes (BUF_NULL = 0 … ERROR_INIT = −11) are listed in prepr1.h; the table of their English names is in def_er.cpp.

Pitfalls

  • Continuation is only \\. A single backslash does not continue a line (see line continuation). When files are generated by scripts, backslashes are easily lost during escaping — check the result in the ~$Prepr$~ file.
  • ! before \\ kills the continuation. Put a comment in a macro body line after \\, not before it.
  • The last line of the file. A #define in the last line of a file without a line feed loses the last character of its body: it is discarded as a line feed.
  • Formal parameter names are replaced in the body wherever they occur as a whole token. Short names (d, L) easily coincide with words of the body — that is why in the package examples the parameters look like Freq__.
  • The macro name is also replaced everywhere below the definition where it stands as a whole token, including inside other task-file constructs. For macros with parameters each such occurrence is treated as a call and requires parameters.
  • Brackets in expressions. Substitution is textual: #define W @ ( 4*a/3 ), not #define W @ 4*a/3.
  • Order of definitions. A macro used in the body of another must be defined above it (see substitution order).
  • Write permission for the task folder is needed both for the temporary macro file and for the result file.
  • Single-threaded. The library keeps its state in global variables; within one process only one preprocessor pass can run at a time.