Skip to content

feat(semantictokens): подсветка платформенных member-методов через accessCall#3950

Merged
nixel2007 merged 4 commits into
developfrom
feature/platform-member-method-semantic-tokens
May 27, 2026
Merged

feat(semantictokens): подсветка платформенных member-методов через accessCall#3950
nixel2007 merged 4 commits into
developfrom
feature/platform-member-method-semantic-tokens

Conversation

@nixel2007

@nixel2007 nixel2007 commented May 26, 2026

Copy link
Copy Markdown
Member

Summary

  • Новый PlatformMemberMethodCallSemanticTokensSupplier подсвечивает вызовы методов на типизированных переменных вида receiver.method(...) для платформенных типов как Method+defaultLibrary.
  • Источник истины — TypeService.findMemberAt(...) (тот же путь, что hover/go-to-definition): вывод типа ресивера через ExpressionTypeInferencer, поиск member через TypeRegistry.getMembers.
  • Source-defined вызовы (общие модули, OScript-library, локальные методы) остаются за MethodCallSemanticTokensSupplier — этот сапплаер пропускает позиции, уже зарегистрированные в ReferenceIndex, чтобы не дублировать токен.
  • Async-модификатор для платформенных member-методов пока не выставляется: у MemberDescriptor нет поля async. Отдельная задача — расширение PlatformMetadata + парсера платформенных контекстов.
  • Follow-up issue Подсветка accessProperty платформенных типов (Property+defaultLibrary) #3949 — симметричный сапплаер для accessProperty (Стр.Имя сейчас тоже не подсвечивается).

Закрывает баг из юзер-репорта «не красится метод после Ждать»: корень был в том, что СертификатКриптографии.ИнициализироватьАсинх(...) — это вызов метода платформенного типа, который ни один существующий сапплаер не покрывал.

Test plan

  • PlatformMemberMethodCallSemanticTokensSupplierTest:
    • testPlatformMethodOnTypedVariableМ.Добавить(...) (Массив) → Method+DefaultLibrary
    • testPlatformMethodAfterAwaitЖдать М.Добавить(...) (юзер-репорт)
    • testAccessPropertyIgnoredСтр.Имя не подсвечивается (это для follow-up)
    • testUnknownTypeReceiverProducesNoToken — без типа пусто
  • ./gradlew test --tests "...semantictokens.*" --tests "...SemanticTokensProviderTest" — зелёно, регрессий нет
  • ./gradlew bootJar — собирается

Draft

PR оформлен как draft: жду подтверждения подхода (через TypeService.findMemberAt против самостоятельного построения BslExpression) и решения по сопутствующему issue #3949 — публиковать оба супплаера вместе одним PR или отдельно.

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced semantic token recognition for method calls on typed variables, providing improved syntax highlighting with proper token classification.
    • Better support for semantic highlighting of platform method calls even when expressions follow await operations.
  • Tests

    • Added comprehensive test coverage for semantic token behavior across multiple scenarios including typed variable method calls, post-await expressions, and edge cases with property access and untyped receivers.

Review Change Stack

…cessCall

Новый PlatformMemberMethodCallSemanticTokensSupplier: для каждого
accessCall выводит тип ресивера через TypeService.findMemberAt (тот же
путь, что hover/go-to-definition) и, если резолвится платформенный
member типа METHOD, выдаёт Method+DefaultLibrary.

Source-defined вызовы (общие модули, OScript-library, локальные методы)
обрабатываются MethodCallSemanticTokensSupplier по ReferenceIndex —
этот сапплаер пропускает позиции, уже зарегистрированные в индексе,
чтобы не дублировать токен.

Async-модификатор для платформенных member-методов не выставляется —
у MemberDescriptor сейчас нет флага async; это отдельная задача
(расширение PlatformMetadata + парсера платформенных контекстов).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@coderabbitai

coderabbitai Bot commented May 26, 2026

Copy link
Copy Markdown
Contributor

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

A new PlatformMemberMethodCallSemanticTokensSupplier class produces semantic tokens for platform type method calls (receiver.method(...)). It traverses AST nodes, excludes source-defined method references using ReferenceIndex, resolves member types via TypeService, and emits Method tokens with DefaultLibrary modifiers. Comprehensive tests verify behavior on typed receivers, awaited expressions, property filtering, and unknown types.

Changes

Platform Member Method Call Semantic Tokens

Layer / File(s) Summary
Class structure and dependencies
src/main/java/com/github/_1c_syntax/bsl/languageserver/semantictokens/PlatformMemberMethodCallSemanticTokensSupplier.java
Package, imports, class-level documentation, and Spring-injected dependencies (TypeService, ReferenceIndex, SemanticTokensHelper) plus DefaultLibrary modifier constant.
Token generation and member resolution
src/main/java/com/github/_1c_syntax/bsl/languageserver/semantictokens/PlatformMemberMethodCallSemanticTokensSupplier.java
Core getSemanticTokens() traverses accessCall nodes, extracts method identifier ranges, excludes source-defined call-sites via ReferenceIndex lookups, resolves member types using TypeService, and emits Method tokens; helper methods compute method-name ranges, check platform method resolution, and collect already-tokenized source-defined positions.
Test coverage for platform methods
src/test/java/com/github/_1c_syntax/bsl/languageserver/semantictokens/PlatformMemberMethodCallSemanticTokensSupplierTest.java
Test class verifies semantic token production for platform method calls on typed receivers, preservation of tokens in awaited expressions, filtering of property access without call semantics, and suppression of tokens for unresolved receiver types.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related issues

  • Issue #3949: Proposes symmetric property semantic tokens supplier using the same TypeService and pattern to highlight platform PROPERTY on accessProperty nodes, complementing this method-focused supplier.

Poem

A hop through syntax trees we go,
🐰 Finding methods with a glow,
Platform calls now brightly tagged,
With DefaultLibrary flag,
Tests confirm each leap is true! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main feature: platform semantic token highlighting for member method calls via accessCall syntax.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/platform-member-method-semantic-tokens

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.

nixel2007 and others added 2 commits May 27, 2026 00:04
Замечания PR #3950:
- В сапплаере используем typed-вариант Trees.<AccessCallContext>findAllRuleNodes(...)
  и убираем лишний instanceof-каст.
- В тесте убираем @CleanupContextBeforeClassAndAfterClass: все 4 теста
  работают с in-memory исходниками через helper.getDecodedTokens(...),
  ServerContext не инициализируем — очищать тоже нечего.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Закрытие 4 Sonar issues на PR #3950:
- S2583 (MAJOR): убран мёртвый `if (ast == null)` — DocumentContext.getAst()
  не возвращает null;
- S3776 (CRITICAL) и S135 (MINOR): тело цикла вынесено в Optional-чейн
  + два хелпера (methodNameRange через Optional.ofNullable().map().map(),
  isPlatformMethodAt). Когнитивная сложность падает <15, один continue
  на цикл больше нет;
- S6212 (INFO): Range заменён на var.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@github-actions

github-actions Bot commented May 26, 2026

Copy link
Copy Markdown
Contributor

Test Results

 2 874 files  + 6   2 874 suites  +6   1h 14m 28s ⏱️ - 5m 46s
 2 505 tests + 4   2 505 ✅ + 4  0 💤 ±0  0 ❌ ±0 
15 030 runs  +24  15 030 ✅ +24  0 💤 ±0  0 ❌ ±0 

Results for commit 751a58e. ± Comparison against base commit 8b04731.

♻️ This comment has been updated with latest results.

@sonarqubecloud

Copy link
Copy Markdown

@nixel2007
nixel2007 marked this pull request as ready for review May 27, 2026 05:58
Copilot AI review requested due to automatic review settings May 27, 2026 05:58
@nixel2007
nixel2007 merged commit 00b62a7 into develop May 27, 2026
39 of 41 checks passed
@nixel2007
nixel2007 deleted the feature/platform-member-method-semantic-tokens branch May 27, 2026 06:01
@nixel2007
nixel2007 removed the request for review from Copilot May 27, 2026 06:23
pull Bot pushed a commit to theshadowco/bsl-language-server that referenced this pull request May 27, 2026
В develop добавили MemberDescriptor.async (1c-syntax#3950+followup). Используем
его в PlatformMemberMethodCallSemanticTokensSupplier:
- async-метод платформы (descriptor.async() == true) теперь получает
  Method + DefaultLibrary + Async на сайте вызова;
- обычный метод — Method + DefaultLibrary, без Async (как и было).

Реализовано через flatMap-пару (range, descriptor) в виде Resolved-record
и кэшированных статических массивов модификаторов
(DEFAULT_LIBRARY_MODIFIERS / DEFAULT_LIBRARY_ASYNC_MODIFIERS).

В тест добавлены два unit-кейса (testModifiersForAsyncDescriptor /
testModifiersForRegularDescriptor) на package-private modifiers(...) —
производственные платформенные типы пока async-методов не несут, поэтому
покрытие через type-инференс в integration-тесте сейчас невозможно.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
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