perf(references): хелпер Positions и отказ от лишних Range при взятии позиции#4258
Merged
Merged
Conversation
…ookup The default ReferenceFinder.findReference(uri, TerminalNode) computed the terminal's start position via Ranges.create(terminal).getStart(), allocating a Range (two Position objects) only to keep one and discard the rest. The non-overriding finders include the hottest one (ReferenceIndexReferenceFinder), so every source-symbol terminal lookup allocated on that path — in a workspace whose heap is already dominated by Position/Range objects (issue #4248). Add a small Positions utility (mirroring Ranges) that builds a bare Position from a Token/TerminalNode — the token->LSP-position conversion (line - 1, charPositionInLine) previously inlined in several places — and use it in the default overload. Result is identical to the previous start position (covered by PositionsTest parity assertions against Ranges.create(...).getStart()). Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01BSiRGLm633B4EmvG3vkk4V
Contributor
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughChangesPosition conversion
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 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 |
Contributor
Extend the Positions helper with create(ParserRuleContext) plus createEnd (Token/TerminalNode), and route the remaining "build a Range only to take one endpoint" and inline "new Position(token.getLine()-1, charPositionInLine)" sites through it: - Ranges.create(x).getStart()/.getEnd() -> Positions.create/createEnd in SelectionRangeProvider, LinkedEditingRangeProvider, ExtractStructure ConstructorSupplier, VariableTypeInlayHintSupplier; - inline start-position construction in SignatureHelpProvider, PlatformMethodCallHintRenderer, PlatformMethodCallInlayHintCollector. Behaviour is unchanged (createEnd mirrors Ranges' end math; PositionsTest adds parity assertions against Ranges.create(...).getStart()/.getEnd()). Verified by 119 tests across the touched providers/inlay-hint/code-action suites. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01BSiRGLm633B4EmvG3vkk4V
Replace the terminal-node lambda with Positions::create (SonarCloud java:S1612); the TerminalNode element resolves the overload unambiguously. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01BSiRGLm633B4EmvG3vkk4V
|
This was referenced Jul 11, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Описание
Часть общей оптимизации из #4248 (раздел «Лишние Position/Range в новом terminal SPI»): убираем аллокацию
Rangeтам, где нужна всего однаPosition.1. Терминальный
ReferenceFinderДефолтный
ReferenceFinder.findReference(uri, TerminalNode)вычислял стартовую позицию черезRanges.create(terminal).getStart()— создавалRange(двеPosition), брал одну и выбрасывал остальное. Оверлоуд не переопределён у самых частых finder'ов (ReferenceIndexReferenceFinder@Order(40),SourceDefinedSymbolDeclarationReferenceFinder,AnnotationReferenceFinder), поэтому каждый терминальный lookup сорсового символа (горячий путь инференсера и диагностик) аллоцировал на ровном месте — в конфигурации, чей heap и так доминируетсяPosition/Range.2. Утилити-класс
PositionsДобавлен
utils/Positions(по образцуRanges) — сборка однойPositionиз координат /Token/TerminalNode/ParserRuleContext, плюсcreateEnd(Token/TerminalNode). Конвертация ANTLR→LSP (line - 1,charPositionInLine) теперь в одном месте.3. Переезд остальных мест на
PositionsПереведены все места, где
Rangeстроился только ради одного конца, и inline-конструирование позиции из токена:Ranges.create(x).getStart()/.getEnd()→Positions.create/createEnd:SelectionRangeProvider,LinkedEditingRangeProvider,ExtractStructureConstructorSupplier,VariableTypeInlayHintSupplier;new Position(token.getLine()-1, token.getCharPositionInLine()):SignatureHelpProvider,PlatformMethodCallHintRenderer,PlatformMethodCallInlayHintCollector.Поведение не меняется:
createEndповторяет арифметику конца изRanges, аPositionsTestпроверяет парити противRanges.create(...).getStart()/.getEnd().Связанные задачи
Пункт из архитектурного разбора #4248. Продолжение серии #4249–#4257.
Closes
Чеклист
Общие
PositionsTest; парити подтверждён 119 тестами затронутых провайдеров/inlay-hint/code-action, а такжеReferenceIndexTest/ReferencesProviderTest/DefinitionProviderTest/RenameProviderTest)Дополнительно
Rangesне тронут (у него уже есть импортorg.eclipse.lsp4j.util.Positions— не стал смешивать имена внутри него). Место с нестандартной колонкой (PlatformMethodCallInlayHintCollector, центрирование по токену) намеренно оставлено наnew Position.Summary by CodeRabbit
(0, 0)), parser contexts, and end-position calculation.