feat(types): bilingual hover/completion/signature + вариадик-параметры#3942
Conversation
Завершение bilingual-поддержки type-system v2 и вариадик-параметров. Зависимость bsl-context поднята до 0.4.0 (флаг ContextSignatureParameter.isVariadic()). Стандартные реквизиты MD-объектов (bilingual): - ConfigurationTypesProvider: attributeBilingualName() из MultiName (ru+en), bilingual имя/описание членов; completion отдаёт реквизиты в языке ScriptVariant. - AssignToReadOnlyPropertyDiagnostic: убран кривой pre-filter по имени — read-only резолвится по типу-владельцу, независимо от языка имени (Ссылка/Ref). - builtin-platform-types.json: bilingual стандартные реквизиты Справочник/ДокументСсылка. Унификация bilingual-модели членов: - BuiltinPlatformTypesProvider.mergeBilingualPairs: соседние ru/en-члены OneScript-дампа склеиваются в один bilingual MemberDescriptor при загрузке. - CompletionProvider: удалён filterMembersByLanguage; язык через member.displayName/ displayDescription(scriptVariant); документация и сигнатура итемов следуют языку. Язык интерфейса (hover/signature help) = настройки LS (configuration.getLanguage()), а не ScriptVariant (язык исходников): - VariableSymbolMarkupContentBuilder.renderRef, SyntheticSymbolMarkupContentBuilder, SignatureHelpProvider — имена типов/параметров через displayName(lang), разделитель коллекции «из»/«Of» локализован; TypeService.displayName(ref, lang). - DocumentContext.getScriptVariantLanguage(): мягкий fallback на UI-язык при UNKNOWN. Вариадик-параметры (Структура/ФиксСтруктура/СтрШаблон/Макс/Мин/Массив/ФорматированнаяСтрока): - ParameterDescriptor.variadic + JSON-поле variadic; SignatureSelection по флагу. - Инлей-хинты и signature help разворачивают вариадик-хвост в нумерованные Значение1/Значение2/… по фактическим аргументам. Co-Authored-By: Claude Opus 4.7 <[email protected]>
…адик Review-замечания к PR #3940: - CompletionProvider.formatSignaturesCount: для language=EN возвращает «N overloads» вместо русского «N вариантов синтаксиса» (detail completion-итема мульти-сигнатурного метода следует языку проекта). - SignatureSelection.acceptsArity: нижняя граница вариадик-ветки — required, а не total-1 (обязательный вариадик-хвост, например Макс(Значение…), требует минимум один аргумент; раньше пропускался вызов без аргументов). Тесты: multiSignatureDetailFollowsConfiguredLanguage, pickIndexByTypesRequiredVariadicRejectsTooFewArgs; ТаблицаЗначений.Скопировать в JSON-fallback получил вторую сигнатуру (реальная перегрузка). Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ерка detail - ParameterDescriptor: компактный конструктор нормализует null-поля через Objects.requireNonNullElse (восстановлено; чинит canonicalConstructorNormalizesNulls). - CompletionProviderTest: EN-detail мульти-сигнатур проверяется паттерном «N overload(s)». Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR makes the server UI language-aware, adds variadic parameter support and numbering across UI features, enriches and merges bilingual builtin platform metadata, consolidates registry null/blank handling, and updates tests and a dependency. ChangesLanguage-aware APIs and bilingual metadata support
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
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: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/util/SignatureSelection.java (1)
51-68:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMake
pickIndexByArityvariadic-aware.The method still enforces a fixed upper bound (
argCount <= total), so valid variadic calls can be rejected in arity-only selection paths.Proposed fix
public static int pickIndexByArity(List<SignatureDescriptor> signatures, int argCount) { if (signatures.isEmpty() || argCount < 0) { return -1; } int fallback = -1; for (int i = 0; i < signatures.size(); i++) { var sig = signatures.get(i); - int total = sig.parameters().size(); - int required = (int) sig.parameters().stream().filter(p -> !p.optional()).count(); - if (argCount >= required && argCount <= total) { + if (acceptsArity(sig, argCount)) { return i; } + int total = sig.parameters().size(); if (fallback == -1 && total == argCount) { fallback = i; } } return fallback; }Also applies to: 120-143
🤖 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/main/java/com/github/_1c_syntax/bsl/languageserver/types/util/SignatureSelection.java` around lines 51 - 68, pickIndexByArity currently rejects calls that exceed the fixed total parameter count even when a signature is variadic; update the logic to detect a variadic parameter (e.g., check the last parameter's variadic flag via parameter.variadic() or similar) and allow argCount >= required when the signature is variadic (treat total as unbounded in that case). Adjust the matching condition in pickIndexByArity to accept signatures when (argCount >= required && (argCount <= total || hasVariadic)), and ensure the fallback assignment (fallback = i when total == argCount) does not override a variadic match—only use fallback for non-variadic exact-total matches.src/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/BuiltinPlatformTypesProvider.java (1)
435-463:⚠️ Potential issue | 🟠 Major | ⚡ Quick winParse bilingual signature descriptions too.
readSignaturesstill only consumes the monodescriptionfield, so the new JSON constructor/overload docs can only ever be Russian in fallback mode. That leaves English signature help incomplete even thoughSignatureDescriptoralready supports bilingual descriptions elsewhere in this provider.💡 Suggested direction
for (var sig : raw) { - var description = (String) sig.getOrDefault("description", ""); + var description = (String) sig.getOrDefault("description", ""); + var descriptionRu = stringField(sig, "descriptionRu"); + var descriptionEn = stringField(sig, "descriptionEn"); var returnTypeName = (String) sig.get("returnType"); var returnType = returnTypeName == null ? fallbackReturnType : new TypeRef(TypeKind.PLATFORM, returnTypeName); @@ - result.add(new SignatureDescriptor(params, returnType, description)); + var ru = descriptionRu.isEmpty() ? description : descriptionRu; + result.add(new SignatureDescriptor(params, returnType, BilingualString.of(ru, descriptionEn))); }Then the JSON signatures added in this PR can move to
descriptionRu/descriptionEn.🤖 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/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/BuiltinPlatformTypesProvider.java` around lines 435 - 463, readSignatures currently only reads mono "description" and so always produces a single-language signature; update it to parse "descriptionRu" and "descriptionEn" (using the existing stringField helper similar to pNameRu/pNameEn) and construct a BilingualString for the signature description, then pass that bilingual description into the SignatureDescriptor (use the overload/constructor that accepts a BilingualString or setDescription accordingly) instead of the mono description variable so both Russian and English signature help are emitted.
🤖 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/providers/CompletionProvider.java`:
- Line 283: The code computes scriptVariant via
documentContext.getScriptVariantLanguage() but filterNamesByLanguage(...) still
uses configuration.getLanguage(); update the call site so that
filterNamesByLanguage and any helper isInConfiguredLanguage reference the
scriptVariant (the per-document script variant) instead of
configuration.getLanguage(), i.e. pass or use scriptVariant where language
selection for no-dot alias filtering occurs (look around the variable
scriptVariant, filterNamesByLanguage(...), and isInConfiguredLanguage to
replace/globalize the language source).
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SignatureHelpProvider.java`:
- Around line 574-577: argCount currently counts all parser-produced callParam
nodes including empty ones; update argCount(DoCallContext doCall) to iterate
over paramList.callParam() and count only those entries that are non-empty
(e.g., filter out params whose getText().trim().isEmpty() or that lack an
expression child) so signature help uses the true number of provided arguments;
modify the method to return 0 when callParamList is null and otherwise return
the count of callParam elements passing the non-empty check.
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/types/model/ParameterDescriptor.java`:
- Around line 69-72: The compat constructor for ParameterDescriptor can NPE
because it calls bilingualName.isEmpty() before record-level normalization;
change that check to be null-safe (e.g., treat null the same as empty) so the
ternary becomes (bilingualName == null || bilingualName.isEmpty()) ?
BilingualString.of(name) : bilingualName and keep the rest of the parameters the
same (types, optional, BilingualString.of(description), defaultValue) to ensure
null bilingualName is handled consistently in the constructor.
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/ConfigurationTypesProvider.java`:
- Around line 473-476: The helper registerWithAlias currently registers an empty
English alias when callers pass ""—prevent this by checking the alias string
before calling typeRegistry.registerConfigurationTypeAlias: in
registerWithAlias(String qualifiedRu, String qualifiedEn) only call
typeRegistry.registerConfigurationTypeAlias(qualifiedEn, ref) if qualifiedEn is
not null and not blank (e.g., !qualifiedEn.isBlank() or !qualifiedEn.isEmpty()
after trimming); leave the original
typeRegistry.registerConfigurationType(qualifiedRu) behavior unchanged.
In
`@src/main/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-platform-types.json`:
- Around line 433-436: The overload for "Скопировать/Copy" only includes Russian
parameter names ("Строки", "Колонки"); add English equivalents by supplying
nameEn for the signature and for each parameter in that overload (use nameEn:
"Rows" and nameEn: "Columns"), or replace the parameter objects to include both
nameRu and nameEn fields so the parser can show English names in fallback mode;
update the parameters array in the existing overload entry (the objects
containing "Строки" and "Колонки") to include nameEn properties accordingly.
---
Outside diff comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/BuiltinPlatformTypesProvider.java`:
- Around line 435-463: readSignatures currently only reads mono "description"
and so always produces a single-language signature; update it to parse
"descriptionRu" and "descriptionEn" (using the existing stringField helper
similar to pNameRu/pNameEn) and construct a BilingualString for the signature
description, then pass that bilingual description into the SignatureDescriptor
(use the overload/constructor that accepts a BilingualString or setDescription
accordingly) instead of the mono description variable so both Russian and
English signature help are emitted.
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/types/util/SignatureSelection.java`:
- Around line 51-68: pickIndexByArity currently rejects calls that exceed the
fixed total parameter count even when a signature is variadic; update the logic
to detect a variadic parameter (e.g., check the last parameter's variadic flag
via parameter.variadic() or similar) and allow argCount >= required when the
signature is variadic (treat total as unbounded in that case). Adjust the
matching condition in pickIndexByArity to accept signatures when (argCount >=
required && (argCount <= total || hasVariadic)), and ensure the fallback
assignment (fallback = i when total == argCount) does not override a variadic
match—only use fallback for non-variadic exact-total matches.
🪄 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: cf3ea5a4-6519-43e9-bce0-bbbd7fe85752
⛔ Files ignored due to path filters (1)
src/test/resources/diagnostics/AssignToReadOnlyPropertyDiagnostic.bslis excluded by!src/test/resources/**
📒 Files selected for processing (23)
build.gradle.ktssrc/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AssignToReadOnlyPropertyDiagnostic.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/hover/SyntheticSymbolMarkupContentBuilder.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilder.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/PlatformMethodCallInlayHintSupplier.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CompletionProvider.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SignatureHelpProvider.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/TypeService.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/model/ParameterDescriptor.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/BslContextPlatformTypesProvider.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/BuiltinPlatformTypesProvider.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/ConfigurationTypesProvider.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/util/SignatureSelection.javasrc/main/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-platform-types.jsonsrc/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AssignToReadOnlyPropertyDiagnosticTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/hover/SyntheticSymbolMarkupContentBuilderTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/PlatformMethodCallInlayHintSupplierTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CompletionProviderTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SignatureHelpProviderTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/types/registry/BuiltinPlatformTypesProviderTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/types/registry/ConfigurationTypesProviderTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/types/util/SignatureSelectionTest.java
Test Results 2 844 files ± 0 2 844 suites ±0 1h 17m 31s ⏱️ + 3m 49s Results for commit 8136a69. ± Comparison against base commit a0ec2f7. This pull request removes 1 and adds 10 tests. Note that renamed tests count towards both.♻️ This comment has been updated with latest results. |
Review-замечания: - CompletionProvider: filterNamesByLanguage/isInConfiguredLanguage используют язык ScriptVariant документа (как остальной completion), а не configuration.getLanguage(); убран инлайн-FQN FileType (импорт). - SignatureHelpProvider.argCount: считает только непустые аргументы; убран FQN Tuple (импорт). - ParameterDescriptor: null-safe компат-конструктор (nameOrFallback), порядок конструкторов. - ConfigurationTypesProvider.registerWithAlias: не регистрирует пустой en-алиас. - SignatureSelection.pickIndexByArity: учитывает вариадик (argCount >= required без верхней границы). - BuiltinPlatformTypesProvider.readSignatures: двуязычное описание сигнатуры (descriptionRu/En). - ТаблицаЗначений.Скопировать (JSON-fallback): nameEn параметров + вторая перегрузка. Sonar: - appendHints разбит на paramAt/appendHint (Cognitive Complexity, break/continue, var). - scoreByTypes разбит на scoreOne/scoreVariadicTail (вложенность). - isLatin/isCyrillic через chars() (число операторов в выражении). - Убраны неиспользуемые импорты (TypeService, CompletionProvider), упрощены always-false проверки, var вместо явных типов, parens для precedence, isZero()/join-assertions/text-block в тестах. Co-Authored-By: Claude Opus 4.7 <[email protected]>
- AssignToReadOnlyPropertyDiagnostic: резолв read-only-свойства вынесен в readOnlyProperty(...) — число return'ов ≤5 (S1142); propertyName убран (S1941). - TypeService.TypedMember: компат-конструкторы помечают owner как @nullable (S4449). - BuiltinPlatformTypesProvider: магическое 2 → константа PAIR_SIZE (S109). - CompletionProvider: объявление scriptVariant перенесено ближе к использованию (S1941). Co-Authored-By: Claude Opus 4.7 <[email protected]>
| // У платформенных/конфигурационных членов source-символа нет, поэтому | ||
| // берём bilingual-описание в языке ScriptVariant, иначе документация | ||
| // всегда оставалась бы на русском (primary). | ||
| var sourceDoc = member.getSourceSymbol().isPresent() |
- BuiltinPlatformTypesProvider: isBilingualPair разбит (isCyrillicName/isLatinName) — число операторов (S1067); isLatin через блок BASIC_LATIN вместо магического 128 (S109); bilingualOrMono вынесен из вложенного тернара readSignatures (S3358). - SignatureSelection.pickIndexByArity переиспользует acceptsArity (Cyclomatic Complexity, S1541). - CompletionProvider.isInConfiguredLanguage сделан static, классификация символов вынесена в isCyrillic/isAsciiLetter (S1541, S2325). - SignatureHelpProvider: argCount через ParseTree::getText (S1612), счётчики циклов var (S6212). - PlatformMethodCallInlayHintSupplier.paramAt помечен @nullable (S2637/S2583/S2589). Co-Authored-By: Claude Opus 4.7 <[email protected]>
…449) positionInside получал результат повторного accessProperty.IDENTIFIER(), который анализатор считал возможно-null. Резолвим propertyId один раз через тернар — без повторного вызова и без лишнего return (≤5). Co-Authored-By: Claude Opus 4.7 <[email protected]>
- CompletionProvider.isInConfiguredLanguage: явные скобки в тернаре (S864). - PlatformMethodCallInlayHintSupplier.appendHint: убрана always-false проверка callParam.getText() == null (getText() не возвращает null) (S2589). Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ingualOrMono) Сигнатура Скопировать(Строки, Колонки) получила descriptionRu/descriptionEn — покрывает bilingual-ветку readSignatures и даёт английское описание варианта в hover/signature help. Co-Authored-By: Claude Opus 4.7 <[email protected]>
|



Завершение bilingual-поддержки type-system v2 и вариадик-параметров. Зависимость
bsl-contextподнята до 0.4.0 (новый флагContextSignatureParameter.isVariadic()).Стандартные реквизиты MD-объектов (bilingual)
ConfigurationTypesProvider: имя/описание стандартных реквизитов — двуязычные (изMultiName), completion отдаёт реквизиты в языкеScriptVariantбез дублей ru+en.AssignToReadOnlyPropertyDiagnostic: убран pre-filter по имени — read-only резолвится по типу-владельцу, независимо от языка имени (Ссылка/Ref).Унификация bilingual-модели членов
BuiltinPlatformTypesProvider.mergeBilingualPairs: соседние ru/en-члены дампа OneScript склеиваются в один двуязычныйMemberDescriptorпри загрузке.CompletionProvider: удалёнfilterMembersByLanguage; лейбл, документация и сигнатура итемов следуют языку.Язык интерфейса (hover / signature help) = настройки LS
ScriptVariant — язык исходников (форматтер, completion-итемы), а интерфейсные подсказки опираются на
configuration.getLanguage():VariableSymbolMarkupContentBuilder,SyntheticSymbolMarkupContentBuilder,SignatureHelpProvider— имена типов/параметров черезdisplayName(lang), разделитель коллекциииз/Ofлокализован.Вариадик-параметры
Новый Структура("Ключи", З1, З2),СтрШаблон("%1 %2", a, b),Макс/Мин/Массив/ФорматированнаяСтрока:ParameterDescriptor.variadic+ JSON-полеvariadic; подбор сигнатуры по флагу.Значение1/Значение2/…по фактическим аргументам; detail мульти-сигнатур и подсказки следуют языку.Тесты обновлены/добавлены.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Improvements
Tests
Chores