Skip to content

fix(types): разрешать См.-ссылку в описании возвращаемого значения функции#4183

Merged
nixel2007 merged 5 commits into
developfrom
claude/session-4178-2779ql
Jun 21, 2026
Merged

fix(types): разрешать См.-ссылку в описании возвращаемого значения функции#4183
nixel2007 merged 5 commits into
developfrom
claude/session-4178-2779ql

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jun 21, 2026

Copy link
Copy Markdown
Member

Проблема

Closes #4178

Тип возвращаемого значения функции, заданный через См.-ссылку в JsDoc:

// Возвращаемое значение:
//   см. СхемаОтвета - Структура с кодом и сообщением ответа.
Функция ОтправитьЗапрос()
	Возврат СхемаОтвета();
КонецФункции

не разворачивался в тип целевой функции — переменная, которой присвоен результат
(Ответ = ОтправитьЗапрос()), оставалась без типа.

Анализ

Поведение было воспроизведено тестом. Выяснилось, что:

  • наличие текстового описания после имени метода (см. Метод - описание) не влияет
    на разбор — парсер корректно отделяет имя ссылки (name=[СхемаОтвета]) от описания;
  • настоящая причина: HYPERLINK-описания возвращаемого значения не резолвились вовсе.
    SymbolTypeIndex#resolveTypeDescription для варианта HYPERLINK возвращает TypeSet.EMPTY,
    поэтому getDeclaredReturnTypes оставался пустым для любой функции с // Возвращаемое значение: см. Метод.
    Для параметров и висячих комментариев переменных аналогичная логика уже была, для возвращаемого
    значения — отсутствовала.

Решение

  • Добавлен общий метод SymbolTypeIndex#resolveSeeReference(link, owner, fileType),
    разворачивающий См.-ссылку в типы (квалифицированная Модуль.Метод — через индекс типов;
    неквалифицированная ссылка на функцию того же модуля — её возвращаемый тип с полями структуры/ТЗ;
    иначе — имя типа через TypeRegistry).
  • indexMethodsRecursive теперь разворачивает HYPERLINK-описания возвращаемого значения,
    если явный тип не указан, — результат доступен всем потребителям getDeclaredReturnTypes.
  • MemberTypeFromCommentResolver#hyperlinkTypes переведён на общий метод (убрано дублирование).

Проверка

  • Новый регрессионный тест SeeReturnValueRefInferenceTest (варианты с описанием и без) — проходит.
  • Полный набор тестов пакета types.* — без регрессий.
  • spotlessJavaCheck — проходит.

🤖 Generated with Claude Code


Generated by Claude Code

Summary by CodeRabbit

  • Refactor
    • Streamlined resolution of см. Метод documentation links for inferred method return-value types.
    • Expanded returned-value hyperlink handling during indexing and unified см. link resolution behavior across local and qualified references.
    • Updated parameter type inference to use the same unified см. resolution logic.
  • Tests
    • Added SeeReturnValueRefInferenceTest to verify Russian см. Метод references in returned-value descriptions (with and without trailing text) and correct propagation of described struct fields.

…нкции

Тип возвращаемого значения, заданный через `// Возвращаемое значение: см. Метод`
(в т.ч. с текстовым описанием после имени — `см. Метод - описание`), теперь
разворачивается в возвращаемый тип целевой функции. Раньше HYPERLINK-описание
возвращаемого значения не резолвилось вовсе, поэтому переменная, которой
присвоен результат такой функции, оставалась без типа.

Логика резолва См.-ссылки вынесена в общий метод SymbolTypeIndex#resolveSeeReference
и переиспользована в MemberTypeFromCommentResolver.

Closes #4178

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

coderabbitai Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@nixel2007, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 19 minutes and 25 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 41ebec07-f61d-4579-ba30-ecc8d7ad5bb6

📥 Commits

Reviewing files that changed from the base of the PR and between 240c9d8 and d45625b.

📒 Files selected for processing (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/SymbolTypeIndex.java
📝 Walkthrough

Walkthrough

Fixes a bug where // см. Method hyperlink references in BSL function return-value descriptions failed to resolve to types. Resolution logic is centralized into SymbolTypeIndex.resolveSeeReference, which gains handling for blank input, dotted names, local function lookup via MethodDescription, and TypeRegistry fallback. MemberTypeFromCommentResolver and ExpressionTypeInferencer are simplified to single delegation calls. A new test class verifies both trailing-comment and plain см. Метод variants resolve correctly to struct types with proper field propagation.

Changes

See-reference return type resolution

Layer / File(s) Summary
SymbolTypeIndex: enhanced hyperlink resolution
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/SymbolTypeIndex.java
Adds DocumentContext and MethodDescription imports; introduces resolveReturnedValueHyperlinks that iterates HYPERLINK type descriptions; expands resolveSeeReference to handle blank input, dotted references via resolveHyperlink, case-insensitive local function returned-value lookup, and TypeRegistry fallback; updates method-return-type indexing to fall back to hyperlink resolution when direct resolution yields empty types.
Delegating resolution paths
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/MemberTypeFromCommentResolver.java, src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/ExpressionTypeInferencer.java
MemberTypeFromCommentResolver removes MethodDescription import and replaces multi-branch hyperlinkTypes computation with a single delegation call to symbolTypeIndex.resolveSeeReference(...); ExpressionTypeInferencer updates the doc comment and simplifies parameterHyperlinkTypes to use the unified resolveSeeReference(...) path.
SeeReturnValueRefInferenceTest: end-to-end inference tests
src/test/java/com/github/_1c_syntax/bsl/languageserver/types/SeeReturnValueRefInferenceTest.java
New test class with two cases asserting см. Метод references resolve to Структура, covering with- and without-trailing-comment variants; includes struct field propagation assertions for field names and referenced types; adds at(marker, offset) and doc() helpers to map fixture positions and load test resources.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • 1c-syntax/bsl-language-server#4122: Expands returned-structure field description propagation; directly consumed by the expanded SymbolTypeIndex and resolveSeeReference logic that now resolves struct fields through см. hyperlinks in return-value descriptions.
  • 1c-syntax/bsl-language-server#4173: Earlier refactor of MemberTypeFromCommentResolver and SymbolTypeIndex.resolveDescribedTypes that establishes the returned-value resolution API now reused by the expanded resolveSeeReference logic in this PR.

Poem

🐇 A bunny once stared at a см. link,
And wondered what type it should think.
Now resolveSeeReference knows the way —
Local functions or registry, hip hooray!
Types flow like carrots on a spring day. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.45% 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 summarizes the main change: fixing type resolution for See-links in function return value descriptions.
Linked Issues check ✅ Passed The PR fully addresses issue #4178 by implementing See-link resolution for function return values, enabling proper type inference for variables assigned function results.
Out of Scope Changes check ✅ Passed All changes directly support the core objective of resolving See-links in return value descriptions; no out-of-scope modifications detected.

✏️ 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/session-4178-2779ql

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.

@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 (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/types/SeeReturnValueRefInferenceTest.java (1)

50-62: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Assert the propagated structure fields, not only the head type.

These tests would still pass if см. СхемаОтвета resolved to bare Структура but dropped the documented fields. Add assertions for the expected fields from the fixture so the regression covers the full return-value contract from the linked issue.

🤖 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/types/SeeReturnValueRefInferenceTest.java`
around lines 50 - 62, The test methods returnValueSeeRefWithTrailingComment()
and returnValueSeeRefWithoutTrailingComment() currently only verify that the see
reference resolves to the type "Структура", but do not validate that the
structure's documented fields are properly propagated. Add additional assertions
after the existing qualifiedName checks to extract and verify the expected
fields from the resolved structure reference using the fixture data, ensuring
the full return-value contract including field definitions is covered by the
test.
🤖 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/types/index/SymbolTypeIndex.java`:
- Around line 274-287: Modify the hyperlink resolution logic to not immediately
return when a link contains a dot. Instead, first attempt to resolve the link
using resolveHyperlink method, and only if that returns null or empty, fall back
to resolving the link through typeRegistry.resolve as a complete qualified type
name. This allows fully qualified platform type names to reach the TypeRegistry
fallback on line 287 when they are not valid member hyperlinks.

---

Nitpick comments:
In
`@src/test/java/com/github/_1c_syntax/bsl/languageserver/types/SeeReturnValueRefInferenceTest.java`:
- Around line 50-62: The test methods returnValueSeeRefWithTrailingComment() and
returnValueSeeRefWithoutTrailingComment() currently only verify that the see
reference resolves to the type "Структура", but do not validate that the
structure's documented fields are properly propagated. Add additional assertions
after the existing qualifiedName checks to extract and verify the expected
fields from the resolved structure reference using the fixture data, ensuring
the full return-value contract including field definitions is covered by the
test.
🪄 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: cb94c0d5-147d-4607-9a04-88d345c384df

📥 Commits

Reviewing files that changed from the base of the PR and between c9c7a9e and aa9c76c.

⛔ Files ignored due to path filters (1)
  • src/test/resources/types/SeeReturnValueRef.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/MemberTypeFromCommentResolver.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/SymbolTypeIndex.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/SeeReturnValueRefInferenceTest.java

…back на TypeRegistry для квалифицированных ссылок

По ревью CodeRabbit:
- resolveSeeReference: квалифицированная (с точкой) ссылка, не разрешившаяся
  как ссылка на член (Модуль.Метод / Тип.Член), теперь доходит до fallback
  через TypeRegistry — полные имена типов резолвятся корректно.
- SeeReturnValueRefInferenceTest: добавлены проверки переноса полей структуры
  (Код - Число, Сообщение - Строка) через См.-ссылку, а не только головного типа.

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

Copy link
Copy Markdown
Contributor

Test Results

 3 522 files  + 6   3 522 suites  +6   1h 28m 22s ⏱️ - 7m 3s
 3 457 tests + 2   3 439 ✅ + 2   18 💤 ±0  0 ❌ ±0 
20 742 runs  +12  20 630 ✅ +12  112 💤 ±0  0 ❌ ±0 

Results for commit 59e01eb. ± Comparison against base commit c9c7a9e.

claude added 3 commits June 21, 2026 21:45
…емых значений

По ревью @nixel2007: вместо параллельной логики вывод типа параметра по
См.-ссылке (ExpressionTypeInferencer#parameterHyperlinkTypes) теперь делегирует
в общий SymbolTypeIndex#resolveSeeReference.

resolveSeeReference для локальной функции предпочитает уже проиндексированный
возвращаемый тип (getDeclaredReturnTypes — раскрывает и цепочки см.), а на этапе
самой индексации (цель ещё не проиндексирована) резолвит напрямую из описания.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01E3nicquvAcTyP4X6Ymxq4F
- SeeReturnValueRefInferenceTest: лямбды `ref -> ref.qualifiedName()` заменены
  на ссылку на метод `TypeRef::qualifiedName`.
- SymbolTypeIndex#resolveSeeReference: параметр link помечен @nullable —
  проверка `link == null` больше не «всегда false» (S2589).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01E3nicquvAcTyP4X6Ymxq4F
Парсер не возвращает null: Hyperlink.create нормализует null-ссылку в "",
HyperlinkTypeDescription.name() = hyperlink.link(). Поэтому проверка на null
была мёртвой (S2589) — заменил @Nullable-костыль на проверку isBlank().

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01E3nicquvAcTyP4X6Ymxq4F
@nixel2007
nixel2007 merged commit a538ec8 into develop Jun 21, 2026
34 of 36 checks passed
@nixel2007
nixel2007 deleted the claude/session-4178-2779ql branch June 21, 2026 22:02
@sonarqubecloud

Copy link
Copy Markdown

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.

[BUG] Ссылка в описании возвращаемого значения не разрешается в тип

2 participants