Skip to content

Обработчики событий формы: стандартные области модуля и подсказка - #4347

Merged
nixel2007 merged 9 commits into
feat/form-types-supportfrom
feat/form-event-handler-regions
Aug 1, 2026
Merged

Обработчики событий формы: стандартные области модуля и подсказка#4347
nixel2007 merged 9 commits into
feat/form-types-supportfrom
feat/form-event-handler-regions

Conversation

@sfaqer

@sfaqer sfaqer commented Aug 1, 2026

Copy link
Copy Markdown
Member

Стековый PR поверх #4337 (типы форм) — сами по себе эти правки к системе типов не относятся, но опираются на её знание о том, кем объявлен обработчик.

Области модуля формы. Стандарт std455 разводит обработчики по четырём областям, а диагностика EventHandlerOutsideEventRegion знала одну — «ОбработчикиСобытийФормы» с проверкой по префиксу. Теперь область берётся по роли обработчика (событие формы, событие элемента шапки, событие элемента таблицы, действие команды), включая шаблонное имя ОбработчикиСобытийЭлементовТаблицыФормы<Имя таблицы>, и попадает в текст сообщения — раньше пользователю не говорили, куда переносить. Имя области и директива берутся в варианте встроенного языка конфигурации, а сопоставление принимает оба написания.

Quick fix не падает. Диагностика — prototype-бин, и codeAction приходит на экземпляр, который ещё ничего не проверял: документ там передаётся аргументом, а поле пустое. Обращение к полю давало NPE на каждый вызов; тесты этого не ловили, потому что звали quick fix у того же экземпляра, что уже проверял документ.

Подсказка обработчика. Шапка «Обработчик события платформы» у обработчика команды была неправдой — команда событием не является. Плюс секция «Параметры»: имя бралось из кода по позиции (у ПередЗакрытием это читалось как два СтандартнаяОбработка), а тип печатался внутренним qualifiedName — отсюда Any при русской раскладке и ПолеФормы.ПолеВвода вместо ПолеФормы.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Improved event-handler diagnostics for form events, form elements, table elements, and commands.
    • Added language-aware region names and more accurate quick fixes for placing handlers.
    • Enhanced hover information for form command handlers, including localized labels, parameter names, descriptions, and types.
  • Documentation

    • Expanded English and Russian guidance with placement rules, fallback behavior, and correct/incorrect examples.
  • Bug Fixes

    • Improved handling when handler roles or configuration details cannot be determined.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 5687e170-31f1-4252-b305-d0a0a5feaf73

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The diagnostic now selects localized standard regions from form-handler roles, module type, script variant, and configuration. Quick fixes use the selected region. Hover output identifies form commands and localizes command names, parameter names, types, and descriptions.

Changes

Event-handler region and hover updates

Layer / File(s) Summary
Role-based diagnostic region resolution
src/main/java/.../EventHandlerOutsideEventRegionDiagnostic.java, src/main/resources/.../EventHandlerOutsideEventRegionDiagnostic_*.properties
The diagnostic resolves role-specific regions, supports bilingual names and table suffixes, selects script variants, and applies the computed region to messages and quick fixes.
Diagnostic validation and documentation
src/test/java/.../EventHandlerOutsideEventRegionDiagnosticTest.java, docs/diagnostics/EventHandlerOutsideEventRegion.md, docs/en/diagnostics/EventHandlerOutsideEventRegion.md
Tests cover localized, command, and owner-specific regions. Documentation describes the rules and form-command placement.
Form command hover and localized metadata
src/main/java/.../DescriptionFormatter.java, src/main/resources/.../DescriptionFormatter_*.properties, src/test/java/.../MethodSymbolMarkupContentBuilderEventHandlerTest.java
Hover output identifies form command handlers and localizes command names, parameter names, types, and descriptions.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant EventHandlerOutsideEventRegionDiagnostic
  participant FormHandlerRoleIndex
  participant LanguageServerConfiguration
  participant Module
  EventHandlerOutsideEventRegionDiagnostic->>FormHandlerRoleIndex: resolve handler role
  EventHandlerOutsideEventRegionDiagnostic->>LanguageServerConfiguration: select language and script variant
  LanguageServerConfiguration-->>EventHandlerOutsideEventRegionDiagnostic: provide localized region settings
  EventHandlerOutsideEventRegionDiagnostic->>Module: validate or insert target region directive
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Заголовок точно отражает основные изменения: стандартные области обработчиков событий формы и подсказки.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/form-event-handler-regions

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Test Results

 3 936 files  ± 0   3 936 suites  ±0   1h 7m 35s ⏱️ - 3m 52s
 4 048 tests + 9   3 982 ✅ + 9   66 💤 ±0  0 ❌ ±0 
24 288 runs  +54  23 888 ✅ +54  400 💤 ±0  0 ❌ ±0 

Results for commit 4e7e34d. ± Comparison against base commit 4f9957c.

♻️ This comment has been updated with latest results.

@sfaqer
sfaqer force-pushed the feat/form-event-handler-regions branch 4 times, most recently from e9c82a4 to 2749728 Compare August 1, 2026 07:29
@sfaqer
sfaqer force-pushed the feat/form-event-handler-regions branch 2 times, most recently from 8aaf894 to d6220d5 Compare August 1, 2026 09:16
@sfaqer

sfaqer commented Aug 1, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@sfaqer
sfaqer marked this pull request as ready for review August 1, 2026 09:55

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter.java (1)

148-157: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the public method contract.

Line 157 exposes a public overload. Its JavaDoc does not define the method and event parameters, the returned Markdown section, or the null behavior. Add @param and @return contract details.

As per coding guidelines, “Javadoc классов и методов должен описывать контракт: параметры, результат, инварианты и побочные эффекты.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter.java`
around lines 148 - 157, Update the JavaDoc for the public
getEventHandlerSection(MethodSymbol, MemberDescriptor) overload to document the
method and event parameters, the returned Markdown section, and the behavior
when method is null; preserve the existing description and accurately state the
method’s contract without introducing unrelated changes.

Source: Coding guidelines

src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EventHandlerOutsideEventRegionDiagnostic.java (1)

162-172: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Javadoc describes a caller's code path, not this method's contract.

Lines 167-168 explain that the field is unfilled "на пути quick fix'а" (on the quick fix's path). This documents a specific caller scenario and calling order, not the parameter/result/invariant contract of expectedRegion itself.

Move this caller-specific rationale to the quick-fix call site or to the test, and keep this Javadoc limited to the contract of expectedRegion.

As per coding guidelines: "Javadoc классов и методов должен описывать контракт: параметры, результат, инварианты и побочные эффекты, но не вызывающие стороны, порядок вызовов или CLI-сценарии; сведения о вызовах хранить у вызывающей стороны, в тестах, package-info или документации."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EventHandlerOutsideEventRegionDiagnostic.java`
around lines 162 - 172, Remove the quick-fix-specific explanation about the
uninitialized field and argument-based context from the Javadoc of
expectedRegion. Keep that documentation focused on the method’s input, returned
region, and fallback behavior, and move the caller rationale to the quick-fix
call site or relevant test.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EventHandlerOutsideEventRegionDiagnostic.java`:
- Around line 135-145: Extract a shared fallback target-region helper for the
null result of expectedRegion in EventHandlerOutsideEventRegionDiagnostic, using
the form event-handlers region required for unknown form handler roles. Update
checkMethod and the quick-fix logic near the target-region construction to reuse
this helper, keeping the diagnostic message and quick fix consistent.

---

Nitpick comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EventHandlerOutsideEventRegionDiagnostic.java`:
- Around line 162-172: Remove the quick-fix-specific explanation about the
uninitialized field and argument-based context from the Javadoc of
expectedRegion. Keep that documentation focused on the method’s input, returned
region, and fallback behavior, and move the caller rationale to the quick-fix
call site or relevant test.

In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter.java`:
- Around line 148-157: Update the JavaDoc for the public
getEventHandlerSection(MethodSymbol, MemberDescriptor) overload to document the
method and event parameters, the returned Markdown section, and the behavior
when method is null; preserve the existing description and accurately state the
method’s contract without introducing unrelated changes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c159cc95-8df5-44c3-adfd-5f4468c5de41

📥 Commits

Reviewing files that changed from the base of the PR and between bd0edaf and d6220d5.

📒 Files selected for processing (10)
  • docs/diagnostics/EventHandlerOutsideEventRegion.md
  • docs/en/diagnostics/EventHandlerOutsideEventRegion.md
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EventHandlerOutsideEventRegionDiagnostic.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter.java
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/EventHandlerOutsideEventRegionDiagnostic_en.properties
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/EventHandlerOutsideEventRegionDiagnostic_ru.properties
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter_en.properties
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter_ru.properties
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EventHandlerOutsideEventRegionDiagnosticTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilderEventHandlerTest.java

@sfaqer
sfaqer force-pushed the feat/form-event-handler-regions branch 3 times, most recently from acc2c7b to eded79b Compare August 1, 2026 10:59
sfaqer and others added 8 commits August 1, 2026 21:57
… роли

Стандарт std455 разводит обработчики модуля формы по четырём областям, а
диагностика знала только одну — «ОбработчикиСобытийФормы» с проверкой по
префиксу. Теперь область берётся по роли обработчика (`FormHandlerRoleIndex`),
включая шаблонное имя `ОбработчикиСобытийЭлементовТаблицыФормы<Имя таблицы>`,
и попадает в текст сообщения — раньше пользователю не говорили, куда переносить.

Там же hover: обработчик команды формы событием не является, и «Обработчик
события платформы» в шапке был неправдой. Теперь — «Обработчик команды формы»
с именем самой команды.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Диагностика — prototype-бин, и quick fix прилетает на экземпляр, который ещё
ничего не проверял: документ там приходит аргументом, а поле documentContext
пустое. Расчёт ожидаемой области читал поле — и codeAction валился с NPE.

Документ теперь передаётся параметром; тест воспроизводит путь LSP — quick fix
запрашивается у экземпляра, полученного из DiagnosticObjectProvider.
…платформа

Два репорта об одном месте — секции «Параметры» в hover обработчика:

- имя параметра бралось из кода по позиции, поэтому у
  `ПередЗакрытием(Отказ, СтандартнаяОбработка)` второй параметр контракта
  (`ЗавершениеРаботы`) выводился под именем из кода и читался как второй
  `СтандартнаяОбработка`. Теперь имя берётся из контракта, а из кода — только
  когда контракт своего не знает;
- тип печатался внутренним `qualifiedName`: отсюда `Any` при русской раскладке
  и `ПолеФормы.ПолеВвода` вместо `ПолеФормы` (имя нашей специализации
  «база + расширение вида» наружу не показывается). Теперь — отображаемое имя
  на языке конфигурации.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…роекта

Диагностика и её quick fix называли области только по-русски, а директиву
вставляли как `#Область` независимо от конфигурации. Теперь имя области —
`MultiName` из `Keywords`, а вариант встроенного языка берётся так же, как в
`GenerateStandardRegionsSupplier`: у конфигурации — её собственный, у одиночного
файла и OneScript — язык сервера. Сопоставление с уже существующей областью
по-прежнему принимает оба написания.

Заодно hover обработчика: имя параметра, его описание и описание параметра в
подсказке брались из русского слота контракта — теперь через `forLanguage`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Ожидаемая область передаётся как `@Nullable`, а не `Optional` в параметре
(`java:S3553`), проверка «лежит ли метод где положено» стала статической
(`java:S2325`), `spy` в тесте — через статический импорт, из hover'а убран
импорт, оставшийся без пользователя после перехода на отображаемые имена.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Тернарник с проверкой на null внутри вызова сбивал анализатор (java:S2259):
проверка и разыменование в одном выражении читаются хуже, чем локальная
переменная с говорящим именем.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`expectedRegion` возвращает пусто только для модуля формы с неизвестным объявителем
обработчика. В этом случае сообщение звало в `ОбработчикиСобытий` (область не-формных
модулей), а quick fix создавал `ОбработчикиСобытийФормы` — то есть исправление уносило
метод не туда, куда указывала диагностика.

Отступной вариант теперь один на оба пути (`orFallback`), и он же — область событий
самой формы: из четырёх форменных областей эта общая.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sonar: связность `DescriptionFormatter` доросла до 24 классов при пороге 20, а
диагностика областей — до 21. Оба класса тянули в себя по два источника сразу.

`EventContractFormatter` берёт всё про контракт платформенного события: шапку
обработчика, параметры с типами и описаниями из синтакс-помощника, имя команды формы.
В `DescriptionFormatter` остаётся то, что человек написал в шапке-комментарии, — вместе
с этим уходят реестр типов, индекс контрактов и роли обработчиков формы.

`EventHandlerTargetRegion` вынесена из диагностики отдельной записью: имена областей
std455, выбор по роли обработчика и отступной вариант — знание про стандарт, а не про
обход дерева символов.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@sfaqer
sfaqer force-pushed the feat/form-event-handler-regions branch from eded79b to 87a23b2 Compare August 1, 2026 12:04
… с контрактными

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

Заодно убраны две перегрузки без единого вызывающего: непокрытый публичный API тянет
ту же метрику вниз.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@sonarqubecloud

sonarqubecloud Bot commented Aug 1, 2026

Copy link
Copy Markdown

* и у OneScript — язык интерфейса сервера. Написание в самом модуле роли не играет:
* платформа понимает оба, а проект пишет на своём.
*/
private ScriptVariant scriptVariantOf(DocumentContext documentContext) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кажется, этот расчёт уже где-то есть.

@nixel2007
nixel2007 merged commit 50d66d6 into develop Aug 1, 2026
40 checks passed
@nixel2007
nixel2007 deleted the feat/form-event-handler-regions branch August 1, 2026 16:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants