Skip to content

Fix trailing variable description links and semantic token positions#4165

Merged
nixel2007 merged 6 commits into
developfrom
claude/trailing-comment-highlighting-kxwwas
Jun 19, 2026
Merged

Fix trailing variable description links and semantic token positions#4165
nixel2007 merged 6 commits into
developfrom
claude/trailing-comment-highlighting-kxwwas

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jun 19, 2026

Copy link
Copy Markdown
Member

Описание

Исправлены два связанных бага при обработке висячих (trailing) комментариев после объявления переменных:

  1. Ссылки в висячих комментариях переменных не обрабатывались: Висячий комментарий (например, Перем П; // См. ДругойМетод) хранится в отдельном VariableDescription через метод getTrailingDescription(), но эти ссылки не попадали в обработку. Добавлена рекурсивная обработка висячих описаний в методе addLinksFromDescription().

  2. Неправильное позиционирование семантических токенов в висячих комментариях: При обработке элементов описания, начинающегося не с начала строки, происходило двойное смещение позиций (прибавление charOffset к уже абсолютным координатам от парсера). Исправлена логика в addBslDocTokensForLine() для работы с абсолютными координатами файла.

Изменения:

  • SeeReferenceDocumentLinkSupplier.java: Извлечена логика обработки ссылок в новый метод addLinksFromDescription(), который рекурсивно обрабатывает висячие описания переменных
  • BslDocSemanticTokensSupplier.java: Исправлена логика позиционирования токенов для корректной работы с висячими комментариями, начинающимися не с начала строки
  • Тесты: Добавлены тесты для проверки обработки ссылок в висячих комментариях и корректного позиционирования семантических токенов

Связанные задачи

Closes

Чеклист

Общие

  • Ветка PR обновлена из develop
  • Отладочные, закомментированные и прочие, не имеющие смысла участки кода удалены
  • Изменения покрыты тестами
  • Обязательные действия перед коммитом выполнены

Дополнительно

Добавлены два новых теста:

  • testTrailingVariableDescriptionReferenceProducesLink() — проверяет, что ссылки в висячих комментариях переменных корректно обрабатываются
  • testElementsInDescriptionStartingAtNonZeroColumn() — проверяет корректное позиционирование семантических токенов в описаниях, начинающихся не с начала строки

https://claude.ai/code/session_016DL8j9ZCc6WCiKeL4uMBFs

Summary by CodeRabbit

  • New Features
    • Added document links from documentation “type name” references to their defining type locations, including references inside trailing variable descriptions.
  • Bug Fixes
    • Restored missing “См.” document links in trailing variable documentation comments.
    • Improved semantic token generation for documentation elements: correct absolute positioning, more consistent line splitting, and type-resolution validation (unresolved types are no longer highlighted).
  • Tests
    • Added/updated coverage for trailing-variable links, non-zero-column description layouts, and unresolved type highlighting behavior.
  • Chores
    • Updated the BSL parser dependency.

…переменных

В описаниях переменных, заданных висячим (trailing) комментарием, не работали
два механизма, потому что такие комментарии начинаются не с начала строки.

Семантические токены (BslDocSemanticTokensSupplier): позиции элементов
(типы, имена параметров, ключевые слова) приходят от парсера в абсолютных
координатах файла, но к ним повторно прибавлялся отступ описания (charOffset).
Из-за двойного смещения подсветка типов «съезжала» вправо в любом описании,
которое не начинается со столбца 0 (висячие комментарии и комментарии, ставшие
описанием следующего метода). Теперь обработка строки ведётся в абсолютных
координатах без повторного прибавления отступа.

Document links (SeeReferenceDocumentLinkSupplier): ссылки «См.» из висячего
описания переменной хранятся в отдельном VariableDescription
(getTrailingDescription) и не попадают в getLinks() основного описания,
поэтому кликабельные ссылки не создавались. Теперь висячее описание
обходится явно.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016DL8j9ZCc6WCiKeL4uMBFs
@coderabbitai

coderabbitai Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Two independent improvements in BSL documentation processing: document link extraction is extended to variable trailing descriptions and a new type-definition document link supplier is added; semantic token emission for variables now validates type resolution and uses absolute character coordinates, eliminating double-offset shifts for indented descriptions.

Changes

Document links for trailing references and type definitions

Layer / File(s) Summary
Trailing description link extraction
src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/SeeReferenceDocumentLinkSupplier.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/documentlink/SeeReferenceDocumentLinkSupplierTest.java
Imports added for SourceDefinedSymbolDescription and VariableDescription; getDocumentLinks delegates to new addLinksFromDescription helper that processes description.getLinks() and recurses into getTrailingDescription() for VariableDescription instances. Test asserts a trailing reference comment produces one DocumentLink with correct range and target.
Type definition document link supplier
src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/TypeDefinitionDocumentLinkSupplier.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/documentlink/TypeDefinitionDocumentLinkSupplierTest.java
New component generates DocumentLinks to source symbols for TYPE_NAME elements in doc descriptions. Iterates method/variable describables, extracts type names, resolves via TypeService, and filters to types with defining source symbols. Handles trailing descriptions recursively for variables. Helper methods reconstruct element text from absolute coordinates and format LSP targets using 1-based line/character offsets. Tests verify links are produced for source-defined types and absent for platform types.

Semantic token type validation and coordinate system

Layer / File(s) Summary
Type service setup and variable description validation
src/main/java/com/github/_1c_syntax/bsl/languageserver/semantictokens/BslDocSemanticTokensSupplier.java
TypeService is injected and used to validate type resolution; getSemanticTokens passes validateTypeResolution flag (enabled for variable descriptions and their trailing descriptions, disabled for method descriptions); addBslDocDescriptionTokens filters TYPE_NAME tokens to emit SemanticTokenTypes.Type only for types that resolve via typeService.resolve(...).
Absolute coordinate scheme in addBslDocTokensForLine
src/main/java/com/github/_1c_syntax/bsl/languageserver/semantictokens/BslDocSemanticTokensSupplier.java
lineStart, lineEnd, and currentPos are computed in absolute file coordinates from charOffset without re-application; element token starts and comment ranges use corrected absolute positions; typeName documentation clarifies absolute coordinate interpretation and per-line column offset rules.
Tests and parser dependency update
src/test/java/com/github/_1c_syntax/bsl/languageserver/semantictokens/BslDocSemanticTokensSupplierTest.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SemanticTokensProviderTest.java, build.gradle.kts
Adds three tests validating token placement and type resolution for non-zero-column and trailing variable descriptions. Updates SemanticTokensProviderTest expected tokens to split trailing comment into Comment and Type components. Bumps bsl-parser dependency from 0.36.0 to 0.37.1.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • theshadowco

Poem

🐇 A trailing comment whispers "См." with pride,
Now found by the linker, no longer to hide!
Type definitions emerge with absolute care,
While tokens count columns with coordinates fair.
The rabbit confirms all descriptions align—
Both trailing and nested, semantically fine! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.54% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the two main bugs being fixed: trailing variable description links and semantic token position issues.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/trailing-comment-highlighting-kxwwas

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 and usage tips.

@github-actions

github-actions Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Test Results

 3 504 files  ± 0   3 504 suites  ±0   1h 32m 29s ⏱️ - 5m 57s
 3 445 tests + 4   3 427 ✅ + 4   18 💤 ±0  0 ❌ ±0 
20 670 runs  +24  20 558 ✅ +24  112 💤 ±0  0 ❌ ±0 

Results for commit fc6eae3. ± Comparison against base commit 3500410.

♻️ This comment has been updated with latest results.

…писаниях

bsl-parser 0.37.0 отдаёт TYPE_NAME-элемент для типа переменной (нотация
«тип в начале»: первый токен до « - »). Благодаря исправлению координат в
BslDocSemanticTokensSupplier тип теперь корректно подсвечивается и в висячих
(trailing) комментариях, и в ведущих описаниях переменных.

Тесты:
- BslDocSemanticTokensSupplierTest: тип «Строка» в висячем комментарии
  переменной подсвечивается как Type на реальной позиции;
- SemanticTokensProviderTest.variableDescriptionComments: первый токен висячего
  описания теперь трактуется как тип (актуализированы ожидаемые токены).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016DL8j9ZCc6WCiKeL4uMBFs

@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

🤖 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 `@build.gradle.kts`:
- Line 99: The bsl-parser dependency in build.gradle.kts is using version 0.37.0
which does not exist. Update the api dependency declaration for
io.github.1c-syntax:bsl-parser by changing the version string from 0.37.0 to
0.35.0, which is the latest available version as of June 2026. Ensure the
dependency line reads api("io.github.1c-syntax:bsl-parser:0.35.0").
🪄 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

Run ID: 8e442f92-9262-4ebc-aa7c-3df1d92942d6

📥 Commits

Reviewing files that changed from the base of the PR and between bec27d8 and 001443f.

📒 Files selected for processing (3)
  • build.gradle.kts
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SemanticTokensProviderTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/semantictokens/BslDocSemanticTokensSupplierTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/semantictokens/BslDocSemanticTokensSupplierTest.java

Comment thread build.gradle.kts Outdated
claude added 2 commits June 19, 2026 09:10
…сли он резолвится

Тип переменной берётся из первого токена описания (нотация «тип в начале»),
поэтому любой свободный текст в висячем комментарии (// трейл, // счётчик ...)
парсер отдаёт TYPE_NAME-элементом. Чтобы не подсвечивать как тип произвольные
слова, BslDocSemanticTokensSupplier теперь проверяет резолв имени через
TypeService и красит элемент как Type только при успешном резолве.

Проверка применяется только к описаниям переменных (ведущим и висячим). Типы
параметров/возврата в описаниях методов задаются структурно и подсвечиваются
без проверки — иначе конфигурационные типы теряли бы подсветку без загруженных
метаданных.

Тесты:
- BslDocSemanticTokensSupplierTest: нерезолвящийся первый токен висячего
  комментария не подсвечивается как тип (остаётся комментарием);
- SemanticTokensProviderTest.variableDescriptionComments: возврат к одному
  токену-комментарию для «// трейл».

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016DL8j9ZCc6WCiKeL4uMBFs
Имена типов в doc-комментариях (типы параметров/возврата методов и тип
переменной по нотации «тип в начале») теперь становятся кликабельными
document link на объявление типа.

Новый TypeDefinitionDocumentLinkSupplier обходит TYPE_NAME-элементы описаний
методов и переменных (включая висячие), резолвит имя через TypeService и, если
у типа есть объявляющий исходный символ (TypeService.definingSymbol —
USER/CONFIGURATION), формирует ссылку на его местоположение. Платформенные и
примитивные типы объявляющего символа не имеют и пропускаются; это же служит
гвардом для описаний переменных — произвольный текст в висячем комментарии
не резолвится в тип и ссылку не порождает.

Также поднята зависимость bsl-parser до 0.37.1.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016DL8j9ZCc6WCiKeL4uMBFs

@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.

🧹 Nitpick comments (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/documentlink/TypeDefinitionDocumentLinkSupplierTest.java (1)

77-104: 💤 Low value

Consider adding range assertion for completeness.

The test verifies the link target but not the range. Adding a range assertion would make the test more thorough and help catch potential regressions in coordinate handling for trailing descriptions.

💡 Optional enhancement
   // then
   assertThat(documentLinks)
     .hasSize(1)
     .first()
-    .satisfies(documentLink ->
+    .satisfies(documentLink -> {
+      assertThat(documentLink.getRange()).isEqualTo(Ranges.create(1, 17, 23));
       assertThat(documentLink.getTarget()).isEqualTo(symbolTarget(documentContext, targetSymbol.getSelectionRange()))
-    );
+    });

Note: Verify the exact range values match the parsed element coordinates.

🤖 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/test/java/com/github/_1c_syntax/bsl/languageserver/documentlink/TypeDefinitionDocumentLinkSupplierTest.java`
around lines 77 - 104, In the trailingVariableTypeWithSourceSymbolProducesLink
test method, add a range assertion to verify the document link's range
coordinates in addition to the target assertion. Within the satisfies callback
block where you currently assert documentLink.getTarget(), add an additional
assertion to verify that documentLink.getRange() matches the expected range of
the "МойТип" text in the trailing comment. This will ensure both the target
location and the range coordinates are correctly handled for trailing variable
type descriptions.
🤖 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.

Nitpick comments:
In
`@src/test/java/com/github/_1c_syntax/bsl/languageserver/documentlink/TypeDefinitionDocumentLinkSupplierTest.java`:
- Around line 77-104: In the trailingVariableTypeWithSourceSymbolProducesLink
test method, add a range assertion to verify the document link's range
coordinates in addition to the target assertion. Within the satisfies callback
block where you currently assert documentLink.getTarget(), add an additional
assertion to verify that documentLink.getRange() matches the expected range of
the "МойТип" text in the trailing comment. This will ensure both the target
location and the range coordinates are correctly handled for trailing variable
type descriptions.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 733065e9-c79c-401f-99ab-ab04903457ae

📥 Commits

Reviewing files that changed from the base of the PR and between fc6eae3 and 8ab48aa.

📒 Files selected for processing (3)
  • build.gradle.kts
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/TypeDefinitionDocumentLinkSupplier.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/documentlink/TypeDefinitionDocumentLinkSupplierTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • build.gradle.kts

Добавлена проверка range у document link для типа в висячем комментарии
переменной (помимо target) — страхует корректность координат для trailing-описаний.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016DL8j9ZCc6WCiKeL4uMBFs
@sonarqubecloud

Copy link
Copy Markdown

…координат

Вместо восстановления текста типа по координатам элемента описания используются
семантические аксессоры bsl-parser, дающие идентичность типа для резолва:
MethodDescription.getParameters()/getReturnedValue(), VariableDescription.getTypes()
→ TypeDescription.name() (SIMPLE) и CollectionTypeDescription.collectionName()
(COLLECTION, т.к. name() отдаёт полную запись «Массив<Число>»).

Общая логика вынесена в утилиту DescriptionTypes (typesOf/resolveName). Убраны
дублирующиеся помощники извлечения текста по координатам (typeName в
BslDocSemanticTokensSupplier и elementText в TypeDefinitionDocumentLinkSupplier):
- подсветка типа переменной теперь решается по множеству резолвящихся
  диапазонов типов (element().range());
- document link на тип строится по name()/collectionName() и element().range().

Поведение не меняется — тесты подсветки и document link остаются зелёными.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016DL8j9ZCc6WCiKeL4uMBFs
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