Стандарт комментирования исходного кода TMC Suite (Qt6-версия)
Документ задаёт, как в коде пакета описываются файлы, классы, функции, поля и макросы. Цель — чтобы программист, впервые открывший файл, за минуту понял, что делает каждая сущность и как ею пользоваться, а за подробностями (физика, формулы, алгоритм) перешёл по одной ссылке на сайт.
Основа — Doxygen (стиль ///), близкий к правилам Google C++ Style Guide и
Microsoft/Cloudflare: короткая точка входа в коде, полная теория — в документации.
1. Язык и символы
- Комментарии пишутся по-русски. Имена из кода (
CTmcRTHNodeDiel,nNumNode) не переводятся и выделяются обратными кавычками:`nNumNode`. - Только символы, которые есть в кодировке CP1251: кириллица, ASCII,
«»,—,–,№,°,±,·. Нельзя: греческие буквы и математические знаки (ε λ Δ μ ω τ σ → ≈ × ² ∞ ≤). Вместо них —eps,lambda,Delta,mu,omega,tau,sigma,->,~,*,^2,inf,<=. Причина: часть исходников хранится в CP1251, и одинаковые правила для всех файлов исключают порчу кодировки. - Формулы в коде — только простые, в строку (
dT = dDelta / (c * sqrt(2))). Вывод формул и обозначения — на сайте.
2. Что разрешено менять
Только комментарии. Код, пробелы внутри кода, порядок строк, строковые литералы, существующие комментарии (в том числе закомментированный старый код и английские пояснения) остаются как есть. Новые комментарии добавляются отдельными строками.
Проверка: python tools/docs/verify_comments.py <папка> — сравнивает поток лексем
без комментариев с эталоном docs_work/baseline/ и ловит любое изменение кода.
⚠️ Строка комментария // не должна оканчиваться обратной косой чертой \ —
она приклеит к комментарию следующую строку кода.
3. Где пишется документация
| Сущность | Где | Что |
|---|---|---|
| Файл | первые строки файла (после существующей шапки, до #include/охранника) |
@file, @brief, роль файла в модуле, ссылка на страницу модуля |
| Класс, структура, объединение, перечисление | перед объявлением | @brief, назначение, кто создаёт и кто владеет, жизненный цикл, потокобезопасность, ссылка |
| Поле класса/структуры, элемент перечисления | строкой /// над полем |
смысл, единицы, допустимые значения, кто заполняет |
| Метод, объявленный в заголовке | в заголовке, перед объявлением | полное описание (см. §4) |
Тот же метод в .cpp |
перед определением — не дублируется; внутри тела — обычные // комментарии к шагам нетривиального алгоритма |
|
Функция/класс, существующие только в .cpp (static, локальные) |
перед определением в .cpp |
полное описание (см. §4) |
Макрос #define, typedef, глобальная переменная |
перед объявлением | смысл, единицы, где используется |
Обработчики сообщений MFC (OnPaint, OnCalc …) |
в заголовке | какое событие/команда меню вызывает, что делает |
Если метод объявлен внутри класса прямо в определении (inline в заголовке) — описание перед ним, как для обычного объявления.
4. Описание функции
/// @brief Строит узлы диэлектрического блока и заносит их в общую топологию.
///
/// Перебирает узлы сетки, попавшие в контур блока, вычисляет для каждого
/// проводимость шлейфа `rY` по eps блока и записывает номер узла в топологию.
/// Вызывается один раз на шаг #STEP до начала расчёта во времени.
///
/// @param[in] pcNextBlockList описание блока из задания (.tpl после препроцессора)
/// @param[in] cParam параметры сетки: шаг dDelta (м), размеры nX, nY
/// @param[out] prYNode массив проводимостей узлов, длина 6*nNumNode
/// @param[in] pbStopFlag флаг остановки из интерфейса; TRUE — прервать
/// @return Ссылка на объект ошибки; `IsError()` == FALSE — успех.
/// @note Потоки: вызывается из расчётного потока ядра.
/// @see https://www.tamic.ru/docs/theory/h-mode.html#dielectric
Обязательно: @brief (одно предложение, глагол в 3-м лице: «Строит», «Возвращает»),
@param для каждого параметра с направлением [in], [out], [in,out],
@return (для не-void). Для параметров и возврата указываются единицы (м, с, Гц,
Тл, м^-3, См/м, дБ, градусы/радианы), допустимые значения, особые значения
(-1 — не задано, NULL — …), кто владеет памятью.
По необходимости: @details (или абзац после пустой строки ///), @pre, @post,
@retval, @note (потоки, производительность), @warning (подводные камни),
@see (ссылка на сайт).
Тривиальные методы (GetX(), конструктор по умолчанию) — одной строкой /// @brief …,
но без пропусков: каждая функция имеет описание.
5. Описание класса
/// @brief Диэлектрический блок сетки H-ядра: узлы, их проводимости и обход во времени.
///
/// Один объект — один блок задания (RECT, CIRC, POLY, FILE …). Хранит список узлов
/// `pcNodeDielOne`, выполняет рассеяние волн в узлах на каждом подтакте.
/// Создаётся `CPlanRT_HDoc` при чтении задания, удаляется при закрытии документа.
/// @see https://www.tamic.ru/docs/code/kernel-h.html#blocks
class CTmcRTHNodeDiel : public CWnd
6. Описание поля и перечисления
/// Напряжение падающей волны на шлейфе диэлектрика, В (условные единицы сетки).
_ELEM_VAL_RTH rU;
Существующие хвостовые комментарии (rU; // falling voltage) не трогаются; русское
описание ставится строкой /// над полем.
Группа однотипных сущностей (набор макросов-флагов, координаты x, y, перегрузки
одной функции) описывается одним комментарием на всю группу — блоком Doxygen, чтобы
описание получил каждый член группы:
/// @name Модификаторы памяти 16-битных компиляторов (здесь — пустые макросы)
///@{
#define _near
#define _far
///@}
Перегрузка, отличающаяся только типом, описывается полностью или через
@copydoc основной функции с пояснением отличия:
/// @copydoc DDX_Text(CDataExchange*, int, int&)
/// @note Вариант для `long` (обмен через `int`).
void DDX_Text(CDataExchange* pDX, int id, long& value);
7. Шапка файла
/// @file tmcrthnodediel.cpp
/// @brief Расчёт узлов диэлектрических блоков H-ядра (рассеяние и передача волн).
///
/// Часть модуля «Счётное ядро H». Содержит построение узлов по блокам задания,
/// граничные условия на краях сетки и основной цикл обхода во времени.
/// @see https://www.tamic.ru/docs/code/kernel-h.html
Файлы, не входящие в сборку Qt6-версии (наследие TAMIC/MFC), получают только шапку с пометкой:
/// @file mainfrm.cpp
/// @brief Главное окно MFC-версии ядра. В сборку Qt6-версии не входит.
///
/// Заменено оболочкой `apps/planarrt_common`. Оставлено для сверки с MFC-версией.
8. Ссылки на сайт
- Только полные адреса
https://www.tamic.ru/docs/...— по ним можно перейти прямо с GitHub. Список страниц и якорей —SITE_MAP.md. Новые якоря допускаются только на странице своего модуля (docs/code/<модуль>.html#<якорь>), и они обязаны появиться на этой странице. - Ссылки на диссертацию, книги, методички в коде не даются — литература указана на
сайте (
docs/theory/references.html). - Ссылка ставится там, где без теории не понять код: схема узла, коэффициенты, граничные условия, порт, преобразование Фурье, ДН. Тривиальным функциям ссылка не нужна.
9. Чего не писать
- Не выдумывать. Если назначение не следует из кода — описать, что код делает,
без догадок о замысле; вопрос вынести в
docs/code-docs/ВОПРОСЫ_АВТОРУ.md(в коде — никаких пометок «уточнить»). - Не пересказывать код построчно («увеличивает i на 1»). Комментарий отвечает на вопросы «что», «зачем», «в каких единицах», «что будет при ошибке».
- Не упоминать людей (кроме автора пакета в шапке, где она уже есть), инструменты разработки и историю переписки. История изменений — в журнале git.
- Не писать дат и «временных» пометок («пока», «сейчас», «новое»).
- Известные ошибки не исправлять в рамках документирования. Если поведение
подтверждено и важно для вызывающего кода —
@warningс фактом.
10. Проверка
python tools/docs/verify_comments.py src— 0 нарушений.doxygen docs/code-docs/Doxyfile— предупреждения о недокументированных сущностях (docs_work/doxygen-warnings.txt) разбираются.- Сборка
build/build_win.shи регрессия — результаты расчёта побайтно не меняются.
Source code commenting standard of TMC Suite (Qt6 version)
This document defines how files, classes, functions, fields and macros are described in the package code. The goal is that a programmer opening a file for the first time understands within a minute what each entity does and how to use it, and can reach the details (physics, formulas, algorithm) through a single link to the site.
The basis is Doxygen (/// style), close to the rules of the Google C++ Style Guide and
Microsoft/Cloudflare: a short entry point in the code, the full theory in the documentation.
1. Language and characters
- Comments are written in Russian. Names from the code (
CTmcRTHNodeDiel,nNumNode) are not translated and are enclosed in backticks:`nNumNode`. - Only characters that exist in the CP1251 encoding: Cyrillic, ASCII,
«»,—,–,№,°,±,·. Not allowed: Greek letters and mathematical symbols (ε λ Δ μ ω τ σ → ≈ × ² ∞ ≤). Use insteadeps,lambda,Delta,mu,omega,tau,sigma,->,~,*,^2,inf,<=. Reason: some of the sources are stored in CP1251, and identical rules for all files rule out encoding corruption. - Formulas in the code — only simple, inline ones (
dT = dDelta / (c * sqrt(2))). Derivations of formulas and notation are on the site.
2. What may be changed
Only comments. Code, whitespace inside code, line order, string literals, existing comments (including commented-out old code and English explanations) remain as they are. New comments are added as separate lines.
Check: python tools/docs/verify_comments.py <folder> — compares the token stream
without comments against the reference docs_work/baseline/ and catches any change to the code.
⚠️ A // comment line must not end with a backslash \ —
it would glue the next line of code to the comment.
3. Where documentation is written
| Entity | Where | What |
|---|---|---|
| File | first lines of the file (after the existing header, before #include/the include guard) |
@file, @brief, role of the file in the module, link to the module page |
| Class, structure, union, enumeration | before the declaration | @brief, purpose, who creates and who owns it, life cycle, thread safety, link |
| Class/structure field, enumeration member | a /// line above the field |
meaning, units, allowed values, who fills it |
| Method declared in a header | in the header, before the declaration | full description (see §4) |
The same method in .cpp |
before the definition — not duplicated; inside the body — ordinary // comments on the steps of a non-trivial algorithm |
|
Function/class existing only in .cpp (static, local) |
before the definition in .cpp |
full description (see §4) |
#define macro, typedef, global variable |
before the declaration | meaning, units, where it is used |
MFC message handlers (OnPaint, OnCalc …) |
in the header | which event/menu command invokes it, what it does |
If a method is declared inside the class right in its definition (inline in the header), the description goes before it, as for an ordinary declaration.
4. Function description
/// @brief Builds the nodes of a dielectric block and adds them to the common topology.
///
/// Iterates over the grid nodes that fall inside the block contour, computes for each
/// the stub conductance `rY` from the block eps and writes the node number to the topology.
/// Called once per #STEP before the time-domain computation starts.
///
/// @param[in] pcNextBlockList block description from the task file (.tpl after the preprocessor)
/// @param[in] cParam grid parameters: step dDelta (m), sizes nX, nY
/// @param[out] prYNode array of node conductances, length 6*nNumNode
/// @param[in] pbStopFlag stop flag from the interface; TRUE — abort
/// @return Reference to the error object; `IsError()` == FALSE — success.
/// @note Threads: called from the computation thread of the kernel.
/// @see https://www.tamic.ru/docs/theory/h-mode.html#dielectric
Mandatory: @brief (one sentence, verb in the 3rd person: "Builds", "Returns"),
@param for every parameter with the direction [in], [out], [in,out],
@return (for non-void). For parameters and the return value, state the units (m, s, Hz,
T, m^-3, S/m, dB, degrees/radians), allowed values, special values
(-1 — not set, NULL — …), and who owns the memory.
As needed: @details (or a paragraph after an empty /// line), @pre, @post,
@retval, @note (threads, performance), @warning (pitfalls),
@see (link to the site).
Trivial methods (GetX(), default constructor) — a single line /// @brief …,
but without omissions: every function has a description.
5. Class description
/// @brief Dielectric grid block of the H kernel: nodes, their conductances and time stepping.
///
/// One object is one block of the task file (RECT, CIRC, POLY, FILE …). Stores the list of nodes
/// `pcNodeDielOne`, performs wave scattering at the nodes on every sub-step.
/// Created by `CPlanRT_HDoc` when the task file is read, deleted when the document is closed.
/// @see https://www.tamic.ru/docs/code/kernel-h.html#blocks
class CTmcRTHNodeDiel : public CWnd
6. Field and enumeration description
/// Voltage of the incident wave on the dielectric stub, V (arbitrary grid units).
_ELEM_VAL_RTH rU;
Existing trailing comments (rU; // falling voltage) are left untouched; the Russian
description is placed as a /// line above the field.
A group of entities of the same kind (a set of flag macros, the coordinates x, y, overloads
of one function) is described by one comment for the whole group — a Doxygen group, so that
every member of the group gets the description:
/// @name Memory modifiers of 16-bit compilers (empty macros here)
///@{
#define _near
#define _far
///@}
An overload that differs only in type is described in full or through
@copydoc of the main function with an explanation of the difference:
/// @copydoc DDX_Text(CDataExchange*, int, int&)
/// @note Variant for `long` (exchange through `int`).
void DDX_Text(CDataExchange* pDX, int id, long& value);
7. File header
/// @file tmcrthnodediel.cpp
/// @brief Computation of the nodes of dielectric blocks of the H kernel (wave scattering and transfer).
///
/// Part of the "Compute kernel H" module. Contains building the nodes from the task file blocks,
/// boundary conditions at the grid edges and the main time-stepping loop.
/// @see https://www.tamic.ru/docs/code/kernel-h.html
Files not included in the build of the Qt6 version (TAMIC/MFC legacy) get only a header with a remark:
/// @file mainfrm.cpp
/// @brief Main window of the MFC version of the kernel. Not included in the Qt6 version build.
///
/// Replaced by the `apps/planarrt_common` shell. Kept for comparison with the MFC version.
8. Links to the site
- Only full addresses
https://www.tamic.ru/docs/...— they can be followed directly from GitHub. The list of pages and anchors is inSITE_MAP.md. New anchors are allowed only on the page of the module itself (docs/code/<module>.html#<anchor>), and they must appear on that page. - Links to the dissertation, books or teaching materials are not given in the code — the literature is listed on
the site (
docs/theory/references.html). - A link is placed where the code cannot be understood without the theory: node circuit, coefficients, boundary conditions, port, Fourier transform, RP. Trivial functions do not need a link.
9. What not to write
- Do not invent. If the purpose does not follow from the code, describe what the code does,
without guessing at the intent; put the question into
docs/code-docs/ВОПРОСЫ_АВТОРУ.md(no "to be clarified" remarks in the code). - Do not retell the code line by line ("increments i by 1"). A comment answers the questions "what", "why", "in what units", "what happens on an error".
- Do not mention people (except the package author in the header where it already exists), development tools or the history of correspondence. The change history is in the git log.
- Do not write dates or "temporary" remarks ("for now", "currently", "new").
- Known bugs are not fixed as part of documenting. If the behavior is
confirmed and important for the calling code — a
@warningstating the fact.
10. Verification
python tools/docs/verify_comments.py src— 0 violations.doxygen docs/code-docs/Doxyfile— warnings about undocumented entities (docs_work/doxygen-warnings.txt) are reviewed.build/build_win.shbuild and regression — computation results remain byte-for-byte identical.