fix(types): разрешать См.-ссылку в описании возвращаемого значения функции#4183
Conversation
…нкции Тип возвращаемого значения, заданный через `// Возвращаемое значение: см. Метод` (в т.ч. с текстовым описанием после имени — `см. Метод - описание`), теперь разворачивается в возвращаемый тип целевой функции. Раньше 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
|
Warning Review limit reached
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughFixes a bug where ChangesSee-reference return type resolution
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 winAssert 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
⛔ Files ignored due to path filters (1)
src/test/resources/types/SeeReturnValueRef.bslis excluded by!src/test/resources/**
📒 Files selected for processing (3)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/MemberTypeFromCommentResolver.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/SymbolTypeIndex.javasrc/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
…емых значений По ревью @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
|



Проблема
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
см. Методdocumentation links for inferred method return-value types.см.link resolution behavior across local and qualified references.см.resolution logic.SeeReturnValueRefInferenceTestto verify Russianсм. Методreferences in returned-value descriptions (with and without trailing text) and correct propagation of described struct fields.