Skip to content

fix(inlayhints): показывать значения по умолчанию пропущенных аргументов#4077

Closed
nixel2007 wants to merge 4 commits into
developfrom
claude/inlayhint-defaults-and-perf
Closed

fix(inlayhints): показывать значения по умолчанию пропущенных аргументов#4077
nixel2007 wants to merge 4 commits into
developfrom
claude/inlayhint-defaults-and-perf

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jun 12, 2026

Copy link
Copy Markdown
Member

Проблема

Две связанные проблемы в inlay-подсказках вызовов методов:

  1. Пропущенные значения по умолчанию. В PlatformMethodCallInlayHintSupplier любой пустой callParam отбрасывался целиком (защита от Новый Тип() с единственным пустым аргументом). Из-за этого ветка showDefaultValues в buildLabel была недостижима для ПРОПУЩЕННЫХ аргументов (Метод(а,,б) и опущенных хвостовых) — подсказка со значением по умолчанию не показывалась.

  2. Квадратичный обход AST. SourceDefinedMethodCallInlayHintSupplier на КАЖДУЮ ссылку метода вызывал Trees.findAllRuleNodes по всему AST документа (O(ссылки × узлы)). На файлах с множеством вызовов это давало заметную деградацию.

Решение

Часть 1 — значения по умолчанию (commit cfa9f3f).
Пустой довод трактуется как пропущенный аргумент только при наличии нескольких callParam'ов (есть запятая). Для такого аргумента при включённом showDefaultValues показывается hint со значением по умолчанию из сигнатуры. Единственный пустой callParam (Метод() / Новый Тип() — ноль аргументов) по-прежнему хинтов не даёт.

Часть 2 — перформанс (commit 5f4550a).
Все doCall-узлы документа собираются за ОДИН обход AST в Map<Range, DoCallContext> по диапазону имени вызываемого метода (для конструктора — по диапазону имени типа). Этот диапазон совпадает с Reference#selectionRange(), поэтому вызов резолвится по ссылке за O(1)-лукап вместо обхода AST на каждую ссылку. Поведение не изменено.

Тесты

  • Новый PlatformMethodCallInlayHintSupplierUnitTest (часть 1): пропущенный аргумент со значением по умолчанию, отсутствие хинтов для Метод()/Новый Тип().
  • Новый testHintsAreEmittedForEveryCallSiteOfSameMethod в SourceDefinedMethodCallInlayHintSupplierTest (часть 2): подтверждает, что подсказки эмитятся для каждого из 8 вызовов одного метода (16 хинтов) и позиции не схлопываются — гарантия, что O(1)-лукап не теряет вызовы. Дополнение, не ослабление существующих ассертов.
  • Зелёные: SourceDefinedMethodCallInlayHintSupplierTest, PlatformMethodCallInlayHintSupplierTest, PlatformMethodCallInlayHintSupplierUnitTest, InlayHintProviderTest.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Inlay hints for calls with skipped or blank arguments now correctly show parameter names and default values only when appropriate.
    • Empty single-argument call forms no longer produce spurious inlay hints.
  • Performance

    • Improved resolution so inlay hints for source-defined methods are generated without scanning the entire document for each reference.
  • Tests

    • Added unit tests verifying skipped-argument hint behavior and that hints are emitted for every call site.

@coderabbitai

coderabbitai Bot commented Jun 12, 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 14 minutes and 6 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

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

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

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: cfeb2e45-df3b-4c00-bdb8-cc671d72dbb5

📥 Commits

Reviewing files that changed from the base of the PR and between 985700e and 2f99c37.

📒 Files selected for processing (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/DoCallRangeIndex.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/SourceDefinedMethodCallInlayHintSupplier.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/PlatformMethodCallInlayHintSupplierUnitTest.java
📝 Walkthrough

Walkthrough

Inlay-hint suppliers add nuanced argument handling: platform calls distinguish truly absent from skipped arguments to conditionally display default-value hints, while source-defined calls replace per-reference AST scans with pre-computed lookup maps for performance.

Changes

Inlay Hint Generation Refinements

Layer / File(s) Summary
Platform Method - Skipped Argument Differentiation
src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/PlatformMethodCallInlayHintSupplier.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/PlatformMethodCallInlayHintSupplierUnitTest.java
Argument iteration computes whether skipped arguments are possible and passes a flag to appendHint. Blank-argument logic now shows parameter-name inlays only when skipping is allowed, showDefaultValues() is enabled, and the parameter has a non-blank default. New unit tests cover skipped-argument defaults and empty single-argument calls.
Source-Defined Method - Pre-collected AST Lookup Optimization
src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/SourceDefinedMethodCallInlayHintSupplier.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/SourceDefinedMethodCallInlayHintSupplierTest.java
Imports updated to include Range, HashMap, and related types. getInlayHints pre-collects doCall nodes keyed by method-name range and performs O(1) lookups per reference. Added rangeKey and collectDoCallsByMethodNameRange; toInlayHints refactored to accept a resolved doCall. Replaced isRightMethod with methodNameRange. Test verifies hints emitted for every call site with no duplicate positions.

Sequence Diagram(s)

sequenceDiagram
  participant Client as getInlayHints
  participant Collector as collectDoCallsByMethodNameRange
  participant Map as HashMap_methodName->doCall
  participant Generator as toInlayHints
  Client->>Collector: traverse AST and collect doCall nodes
  Collector->>Map: insert doCall keyed by method-name Range
  Client->>Map: lookup doCall for each reference via rangeKey
  Map-->>Generator: resolved doCall context
  Generator-->>Client: InlayHint list
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

A rabbit hops through hints with care,
Skipped arguments now show their flair,
Maps pre-built make lookups bright,
No duplicate calls escape the sight! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.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 directly addresses the main changes: displaying default values for skipped/omitted arguments in inlay hints, which is the primary functional improvement across both modified supplier classes.
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/inlayhint-defaults-and-perf

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 13, 2026

Copy link
Copy Markdown
Contributor

Test Results

 3 270 files  ± 0   3 270 suites  ±0   1h 32m 46s ⏱️ + 14m 20s
 3 179 tests +10   3 164 ✅ +10  15 💤 ±0  0 ❌ ±0 
19 074 runs  +60  18 984 ✅ +60  90 💤 ±0  0 ❌ ±0 

Results for commit 2f99c37. ± Comparison against base commit bdbda86.

♻️ This comment has been updated with latest results.

nixel2007 and others added 3 commits June 13, 2026 08:42
В PlatformMethodCallInlayHintSupplier любой пустой callParam отбрасывался
целиком (защита от `Новый Тип()` с единственным пустым аргументом), из-за
чего ветка showDefaultValues в buildLabel была недостижима для ПРОПУЩЕННЫХ
аргументов (`Метод(а,,б)` и опущенных хвостовых).

Теперь пустой довод трактуется как пропущенный аргумент только при наличии
нескольких callParam'ов (есть запятая). Для такого аргумента при включённом
showDefaultValues показывается hint со значением по умолчанию из сигнатуры.
Единственный пустой callParam (`Метод()` / `Новый Тип()` — ноль аргументов)
по-прежнему хинтов не даёт.

Co-Authored-By: Claude Fable 5 <[email protected]>
- S6411/S6485: ключ карты вызовов заменён на String (Comparable),
  HashMap создаётся через HashMap.newHashMap
- S2583: удалён мёртвый null-guard для getAst() (@NullMarked -> non-null)
- S2589/S2637: methodNameRange теперь возвращает Optional<Range>
  вместо null; вызов через ifPresent вместо проверки != null
- S4449: nullable methodName() передаётся в Ranges.create только после
  проверки на null
- S126: добавлен завершающий else в methodNameRange и appendHint
- S1941: объявление parameters перенесено ближе к использованию
- S125/S1612: тест — убрана код-подобная строка из комментария,
  лямбда заменена на Either::getLeft
- покрытие: добавлены тесты на значения по умолчанию, нехватку
  аргументов и пустой диапазон

Co-Authored-By: Claude Fable 5 <[email protected]>
@nixel2007
nixel2007 force-pushed the claude/inlayhint-defaults-and-perf branch from 5f4550a to 985700e Compare June 13, 2026 06:56
@sonarqubecloud

Copy link
Copy Markdown

@nixel2007

Copy link
Copy Markdown
Member Author

Раздели на два PR

@nixel2007

Copy link
Copy Markdown
Member Author

Разделено на два независимых PR по просьбе ревью: #4106 — значения по умолчанию пропущенных аргументов; #4107 — перформанс (индекс doCall). Файлы непересекающиеся.

@nixel2007 nixel2007 closed this Jun 14, 2026
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