Skip to content

feat(completion): паритет completion item — пользовательские методы и конструкторы как платформенные#4129

Merged
nixel2007 merged 3 commits into
developfrom
feat/completion-local-method-signature
Jun 16, 2026
Merged

feat(completion): паритет completion item — пользовательские методы и конструкторы как платформенные#4129
nixel2007 merged 3 commits into
developfrom
feat/completion-local-method-signature

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jun 16, 2026

Copy link
Copy Markdown
Member

Цель

Сделать completion item'ы пользовательских/source-defined символов визуально идентичными платформенным (сигнатура, тип возврата, документация, раскладка labelDetails).

Что сделано

1. Локальные методы текущего модуля (no-dot completion).
Раньше показывали только имя. Теперь — сигнатура (Пар1, Пар2?) из MethodSymbol.getParameters(), тип возврата из doc-comment'а (Возвращаемое значение:) и документация (назначение + причина устаревания), через те же applyDetail/setDocumentation, что и платформенные методы.

2. Конструкторы после Новый.
Сигнатура форматировалась вручную: без ? у необязательных параметров, только параметры первой перегрузки, detail напрямую (минуя labelDetails). Теперь — теми же applyDetail/formatParameterList/formatSignaturesCount, что и методы: (Пар?), N вариантов при нескольких перегрузках, labelDetails при поддержке клиентом. Тип возврата не показываем (результат конструктора — сам класс, дублирует label).

Аудит остальных веток

Перебрал все места создания CompletionItem. Ветки, порождающие методы, теперь все богатые:

  • платформенные глобальные функции (no-dot) — были;
  • локальные методы (no-dot) — этот PR;
  • члены типа в dot-completion, включая source-методы общих/OScript-модулей (MemberDescriptor/buildMemberItem) — были богатыми, добавлен тест-страж.

Бедными осознанно остаются не-методы: локальные переменные (в BSL не типизированы — нужен вывод типов, отдельная задача), ключевые слова, имена типов/неймспейсов.

Тесты

  • noDotCompletionLocalMethodHasSignatureAndDocumentationLikePlatform — локальный метод: (Имя, Приветствие?): Строка + документация (red→green).
  • dotCompletionCommonModuleMethodHasSignatureAndDocumentationLikePlatform — метод общего модуля: (Значение): Массив + документация (страж паритета).
  • newCompletionConstructorSignatureMatchesPlatformMethodFormat(КоличествоЭлементов?) (red→green).
  • newCompletionConstructorOverloadsShownAsCountLikePlatformMethod — несколько перегрузок → счётчик вариантов (red→green).
  • newCompletionConstructorUsesLabelDetailsWhenClientSupportsThem — labelDetails при поддержке клиентом (red→green).

Весь CompletionProviderTest зелёный.

🤖 Generated with Claude Code

Локальные (source-defined) процедуры/функции в no-dot completion показывали
только имя, тогда как платформенные (Сообщить и пр.) — сигнатуру «(Пар1, Пар2?)»,
тип возврата и документацию. Теперь пользовательские методы выглядят так же:
сигнатура строится из MethodSymbol.getParameters() (необязательные помечаются
«?»), тип возврата — из doc-comment'а (Возвращаемое значение:), документация —
из назначения метода (+ причина устаревания). Используются те же
applyDetail/setDocumentation, что и для платформенных методов, поэтому раскладка
по labelDetails/detail идентична.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

CompletionProvider is extended so that no-dot local method completion items now include a formatted parameter signature with optional-parameter markers, an extracted return type from the doc-comment, and documentation text built from the deprecation notice and purpose description. Four private helper methods implement this logic; two call sites are added in the existing local-methods loop.

Changes

Local method completion: detail and documentation enrichment

Layer / File(s) Summary
Imports and helper methods for completion enrichment
src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CompletionProvider.java
Imports for MethodSymbol, parser description types, and java.util.Arrays are added. Four new private helpers implemented: one formats parameter lists with ? for optional parameters, one extracts and joins comma-separated return-type names from the doc-comment's returned-value section, one builds and sets the full detail string with signature and return type, and one builds and sets the documentation string from deprecation info and purpose.
Loop wiring and test verification
src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CompletionProvider.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CompletionProviderTest.java
Two calls to the new helpers are inserted in the local-methods completion loop before existing deprecation/sort/commit logic. A dot-completion test verifies Common Module method completion items carry platform-like detail and documentation. A no-dot completion test constructs an in-memory exported function with a doc-comment, triggers completion, and asserts CompletionItemKind.Function, a platform-style detail with signature and return type, and documentation text from the doc-comment.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • 1c-syntax/bsl-language-server#4070: Both PRs modify no-dot local method completion generation in CompletionProvider—this PR adds detail and documentation from the method symbol's doc-comment, while that PR adjusts completion-item sortText ranking.
  • 1c-syntax/bsl-language-server#4082: Both PRs implement method-parameter signature formatting with optional-parameter markers (?) for method symbols—this PR for completion items, that PR for DocumentSymbol in DocumentSymbolProvider.
  • 1c-syntax/bsl-language-server#3969: Both PRs modify the no-dot local-method completion-item construction in CompletionProvider—this PR adds detail and documentation enrichment, while that PR adjusts insertion text and cursor placement based on parameter presence.

Poem

🐇 Hop, hop, a method appears,
With parameters listed and types declared clear!
Optional args wear a ? with pride,
Doc-comments now jump to the completion's side.
Return types emerge from the comment's embrace—
This rabbit has brightened the IDE's face! 🌸

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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
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 The title accurately describes the main change: adding completion item parity between user-defined (local) methods and platform methods by enriching local method completions with signatures and documentation.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/completion-local-method-signature

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.

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

251-293: ⚡ Quick win

Add a local-method test for the labelDetailsSupport=true branch.

Line 287 currently asserts only flat detail. Since the new local-method path now routes through applyDetail, add a companion assertion/test where enableLabelDetailsSupport(true) is enabled and verify labelDetails.detail/description are populated while detail is null.

As per coding guidelines, “Always run tests before submitting changes and maintain or improve test coverage using appropriate test frameworks (JUnit, AssertJ, Mockito)”.

🤖 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/providers/CompletionProviderTest.java`
around lines 251 - 293, Add a new test method similar to
noDotCompletionLocalMethodHasSignatureAndDocumentationLikePlatform that tests
the labelDetailsSupport enabled path. Enable labelDetailsSupport to true before
calling completionProvider.getCompletion, then assert that the completion item's
labelDetails field (specifically labelDetails.detail and
labelDetails.description) contains the expected signature and documentation,
while the flat detail field is null. This ensures the local method completion
properly populates structured label details when support is enabled.

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.

Nitpick comments:
In
`@src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CompletionProviderTest.java`:
- Around line 251-293: Add a new test method similar to
noDotCompletionLocalMethodHasSignatureAndDocumentationLikePlatform that tests
the labelDetailsSupport enabled path. Enable labelDetailsSupport to true before
calling completionProvider.getCompletion, then assert that the completion item's
labelDetails field (specifically labelDetails.detail and
labelDetails.description) contains the expected signature and documentation,
while the flat detail field is null. This ensures the local method completion
properly populates structured label details when support is enabled.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 70bd5ac9-12d3-4531-8d63-f37cd695d197

📥 Commits

Reviewing files that changed from the base of the PR and between 460c56d and f1b0f47.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CompletionProvider.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CompletionProviderTest.java

nixel2007 and others added 2 commits June 16, 2026 07:19
Регрессионный тест: dot-completion метода общего модуля (source-defined)
показывает сигнатуру, тип возврата и документацию так же, как платформенные
методы (ОбщегоНазначения.ЗначениеВМассиве → «(Значение): Массив» + описание).
Эта ветка (member через MemberDescriptor/buildMemberItem) уже была богатой —
тест фиксирует паритет, чтобы он не сломался.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Конструкторы после `Новый` форматировали сигнатуру вручную: без пометки «?» у
необязательных параметров, показывали параметры только первой перегрузки и писали
detail напрямую (минуя labelDetails). Теперь — теми же
applyDetail/formatParameterList/formatSignaturesCount, что и методы:
«(Пар?)», «N вариантов» при нескольких перегрузках и раскладка в labelDetails
при поддержке клиентом. Тип возврата не показываем — результат конструктора это
сам класс, он уже дублируется label'ом.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@nixel2007 nixel2007 changed the title feat(completion): сигнатура и документация у локальных методов feat(completion): паритет completion item — пользовательские методы и конструкторы как платформенные Jun 16, 2026
@nixel2007
nixel2007 merged commit 3f8d1d8 into develop Jun 16, 2026
33 checks passed
@nixel2007
nixel2007 deleted the feat/completion-local-method-signature branch June 16, 2026 05:39
@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.

1 participant