feat(types): типы объектов XDTO-пакетов и фабрика XDTO - #4381
Conversation
Ссылка «См. XDTOПакет.<Пакет>.<Тип>» разрешается в тип: на каждый объектный тип пакета заводится тип с тем же именем, что пишут в ссылке, а его члены — свойства из схемы пакета. Имена XML-схемы отображаются в примитивы 1С, простые типы пакета читаются по их базе, ссылки на типы пакета — в его типы. Схемы пакетов больше не пропускаются при чтении конфигурации: без них у пакета есть только имя и пространство имён. На ssl_3_1 (56 пакетов, 14826 объектных типов) чтение конфигурации дорожает с ~2.9 до ~3.1-3.6 с. Платформенная часть XDTO (ОбъектXDTO, ФабрикаXDTO, типы и списки) добавлена в словарь встроенных типов: синтакс-помощник её отдаёт, но он есть не везде.
|
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:
📝 WalkthroughWalkthroughThe change adds built-in XDTO types, registers XDTO package object types from configuration metadata, preserves described type metadata, and infers types from XDTO factory calls. Tests cover references, schema properties, chained access, factory creation, and completion. ChangesXDTO type inference
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant ConfigurationTypesProvider
participant XdtoTypesProvider
participant TypeRegistry
participant ExpressionTypeInferencer
participant XdtoFactoryInference
ConfigurationTypesProvider->>XdtoTypesProvider: register configuration XDTO packages
XdtoTypesProvider->>TypeRegistry: register object types and members
ExpressionTypeInferencer->>XdtoFactoryInference: refine XDTO factory call
XdtoFactoryInference->>XdtoTypesProvider: resolve namespace and type
XdtoTypesProvider-->>XdtoFactoryInference: return resolved object type
XdtoFactoryInference-->>ExpressionTypeInferencer: return refined type set
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 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 |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-platform-types.json`:
- Around line 6103-6109: Register the missing XDTO return types referenced by
ObjectXDTO, ТипОбъектаXDTO, and ФабрикаXDTO: СвойствоXDTO,
ПоследовательностьXDTO, КоллекцияСвойствXDTO, and КоллекцияПакетовXDTO. Add
corresponding kind TYPE entries in the builtin platform type registry, or update
the affected method returnType values to existing registered types while
preserving their intended API types.
In
`@src/test/java/com/github/_1c_syntax/bsl/languageserver/types/XdtoPackageTypesTest.java`:
- Around line 127-135: Update the at helper’s Position construction to use the
zero-based character offset required by Position, removing the extra +1 from the
column calculation while preserving the existing line calculation and target
offset handling.
🪄 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 Plus
Run ID: c80e7b95-e19a-4524-84cb-85d6e4dcf18b
⛔ Files ignored due to path filters (3)
src/test/resources/metadata/designer/Configuration.xmlis excluded by!src/test/resources/**src/test/resources/metadata/designer/XDTOPackages/ПакетТест.xmlis excluded by!src/test/resources/**src/test/resources/metadata/designer/XDTOPackages/ПакетТест/Ext/Package.binis excluded by!**/*.bin,!src/test/resources/**
📒 Files selected for processing (7)
src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/ConfigurationTypesProvider.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/XdtoTypesProvider.javasrc/main/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-globals.jsonsrc/main/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-platform-types.jsonsrc/test/java/com/github/_1c_syntax/bsl/languageserver/types/XdtoPackageTypesTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/types/registry/ConfigurationTypesProviderHelpersTest.java
💤 Files with no reviewable changes (1)
- src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java
«ФабрикаXDTO.Тип(URI, Имя)» отдаёт дескриптор, помеченный найденным типом объекта, а «Создать(Тип)» эту пометку снимает — так пишут, когда пакет адресуется в коде, без ссылок в комментариях. Пакет ищется по пространству имён: в ссылке пишут имя пакета, в коде — URI, поэтому провайдер держит связку одного с другим. Когда пространство имён вычисляется, литерала нет и пометки не возникает: тип задаётся строчной ссылкой на объект пакета, и работает общий механизм комментариев.
Свойства схемы видны после точки и у параметра со ссылкой на объект пакета, и у объекта, созданного фабрикой, и у вложенного свойства-объекта.
Словарь встроенных типов работает заменителем синтакс-помощника там, где его нет, поэтому объявления должны совпадать с платформенными: «Создать» возвращает ЗначениеXDTO, «Тип» — ТипЗначенияXDTO, ТипОбъектаXDTO либо Неопределено.
«Создать» создаёт значение по типу значения (из значения либо по лексическому представлению) и объект — по типу объекта, поэтому возврат у метода составной, а у каждой сигнатуры свой. «Тип» ищется по URI и имени, по расширенному имени XML либо по типу данных XML. Состав снят с синтакс-помощника.
Test Results 3 984 files +12 3 984 suites +12 44m 26s ⏱️ - 2m 52s Results for commit c86caa8. ± Comparison against base commit 7f1e814. This pull request removes 3 and adds 11 tests. Note that renamed tests count towards both.♻️ This comment has been updated with latest results. |
«Новый ОписаниеТипов(…)» и «ФабрикаXDTO.Тип(…)» — значения-описатели: они несут типы, о которых говорят, но сами ими не являются. Раньше эти типы клались в элементы коллекции, и обход описателя выдавал их так, будто он коллекция. Теперь у набора есть отдельная декорация describedTypes со своими withDescribed и getDescribedTypes; читают её «ПривестиЗначение», «ФабрикаXDTO.Создать» и разбор колонок таблицы значений.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/OpenDataObjectInference.java (1)
246-276: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUpdate stale "types элементов" references after the described-types refactor. This PR moves type-description content from
elementTypesto the dedicateddescribedTypesmap (TypeSet.withDescribed/getDescribedTypes), but three comments in this file still describe the old storage location.
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/OpenDataObjectInference.java#L246-L276: update the Javadoc forapplyTypeDescriptionTypes— it still says names are attached "как типы элементов," but the method callsbase.withDescribed(...).src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/OpenDataObjectInference.java#L278-L307: update the Javadoc foradjustedValueTypes— it still says the composition "лежит в типах элементов," but the method callsreceiver.getDescribedTypes(ref).src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/OpenDataObjectInference.java#L461-L512: update the inline comment inaddedColumn— it still says the content "лежит в типах элементов," but thedescribedTypes()helper it relies on callsinferred.getDescribedTypes(ref).As per coding guidelines, "keep documentation up to date with code changes."
🤖 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/inferencer/OpenDataObjectInference.java` around lines 246 - 276, Update the stale documentation in OpenDataObjectInference.java at lines 246-276, 278-307, and 461-512: revise the Javadoc for applyTypeDescriptionTypes and adjustedValueTypes, plus the inline comment in addedColumn, to describe describedTypes/withDescribed and getDescribedTypes rather than element types; no code behavior changes are needed.Source: Coding guidelines
🧹 Nitpick comments (1)
src/main/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-platform-types.json (1)
6396-6459: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd per-signature
returnTypeforФабрикаXDTO.Тип, matchingСоздать.
Создатьdeclares a distinct"returnType"for each signature (ЗначениеXDTO,ЗначениеXDTO,ОбъектXDTO).Типonly declares the aggregate"returnTypes"at the method level, so the JSON signatures do not narrow the result type per overload. Add"returnType"entries to theТипsignatures, withТипЗначенияXDTOfor XML data-type signatures and the appropriateТипОбъектаXDTOvariants for URI/name and XML qualified name signatures.🤖 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/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-platform-types.json` around lines 6396 - 6459, Add per-signature returnType fields to the ФабрикаXDTO.Тип method: use ТипОбъектаXDTO for the URI/name and XML qualified-name overloads, and ТипЗначенияXDTO for the XML data-type overload. Keep the existing method-level returnTypes unchanged.
🤖 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.
Outside diff comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/OpenDataObjectInference.java`:
- Around line 246-276: Update the stale documentation in
OpenDataObjectInference.java at lines 246-276, 278-307, and 461-512: revise the
Javadoc for applyTypeDescriptionTypes and adjustedValueTypes, plus the inline
comment in addedColumn, to describe describedTypes/withDescribed and
getDescribedTypes rather than element types; no code behavior changes are
needed.
---
Nitpick comments:
In
`@src/main/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-platform-types.json`:
- Around line 6396-6459: Add per-signature returnType fields to the
ФабрикаXDTO.Тип method: use ТипОбъектаXDTO for the URI/name and XML
qualified-name overloads, and ТипЗначенияXDTO for the XML data-type overload.
Keep the existing method-level returnTypes unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: f9f3f366-224a-40a5-b507-d4f9da13298c
📒 Files selected for processing (6)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/OpenDataObjectInference.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/XdtoFactoryInference.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/model/TypeSet.javasrc/main/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-platform-types.jsonsrc/test/java/com/github/_1c_syntax/bsl/languageserver/types/TypeDescriptionConstructorInferenceTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/types/XdtoPackageCompletionTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/XdtoFactoryInference.java
Регистрация пакета разобрана на шаги, имена примитивов вынесены в константы, сняты проверки на null у полей схемы — mdclasses их не отдаёт пустыми. Уточнения вызова вынесены из refinedMemberTypes отдельным методом. В словарь добавлены типы, на которые ссылались объявления XDTO: свойство, последовательность, коллекции свойств и пакетов, сам пакет.
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 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/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-platform-types.json`:
- Around line 6372-6374: Add Неопределено to the returnTypes for
ПолучитьСвойство in ПоследовательностьXDTO and Получить in КоллекцияСвойствXDTO,
using ["СвойствоXDTO", "Неопределено"] so inference preserves possible undefined
results. Apply the change at both affected sites in
src/main/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-platform-types.json:6372-6374
and 6384-6386.
- Around line 6389-6399: Update the ПакетXDTO type definition by renaming the
Свойства member to КорневыеСвойства with the English name RootProperties, and
add a Зависимости member named Dependencies with return type
КоллекцияПакетовXDTO. Preserve the existing property kind and appropriate
descriptions.
- Around line 6365-6376: Update the ПоследовательностьXDTO type definition by
renaming the Получить member to ПолучитьЗначение and adding the
УстановитьЗначение, Добавить, and Удалить methods with the corresponding
platform API names and metadata. Preserve the existing Количество and
ПолучитьСвойство members.
- Around line 6351-6364: Extend the СвойствоXDTO members list with bilingual
metadata entries for ВозможноПустое, ЗначениеПоУмолчанию, and ТипВладелец.
Assign each member its documented XDTO return type and preserve the existing
PROPERTY metadata structure so completion and type inference expose all three
members.
🪄 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 Plus
Run ID: 36f33dc6-ca25-4412-81f2-1874aeba3a40
📒 Files selected for processing (6)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/ExpressionTypeInferencer.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/XdtoFactoryInference.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/XdtoTypesProvider.javasrc/main/resources/com/github/_1c_syntax/bsl/languageserver/types/registry/builtin-platform-types.jsonsrc/test/java/com/github/_1c_syntax/bsl/languageserver/types/XdtoPackageCompletionTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/types/XdtoPackageTypesTest.java
💤 Files with no reviewable changes (1)
- src/test/java/com/github/_1c_syntax/bsl/languageserver/types/XdtoPackageTypesTest.java
🚧 Files skipped from review as they are similar to previous changes (4)
- src/test/java/com/github/_1c_syntax/bsl/languageserver/types/XdtoPackageCompletionTest.java
- src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/ExpressionTypeInferencer.java
- src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/XdtoFactoryInference.java
- src/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/XdtoTypesProvider.java
Свойство, последовательность, коллекции и пакет описаны так, как их отдаёт платформа: у последовательности «ПолучитьЗначение» вместо «Получить» и полный набор операций, у пакета «КорневыеСвойства» и «Зависимости», у поисковых методов в возврате есть «Неопределено». Слияние декораций набора вынесено в два хелпера, объединение условий в mapRefs разложено по смыслу, метод «все описанные типы» переименован, чтобы не спорить с методом доступа записи.
Копирование, слияние, замена ключей и отбор устроены одинаково для всех декораций и к самому значению отношения не имеют. Набор перестал быть сборником утилит, а типы в лямбдах записаны явно.
Пакет модели помечен @NullMarked, карты декораций пустыми, а не null, — проверка никогда не срабатывала.
|



Пункт 3.26 рекомендации «Типизация кода»: тип можно задать ссылкой на объект XDTO-пакета.
Так пишут и в реальном коде: в ssl_3_1 такие ссылки стоят и на возвращаемом значении (
см. XDTOПакет.КонтактнаяИнформация.КонтактнаяИнформация), и в строке (Состав = XDTOКонтактнаяИнформация.Состав; // см. XDTOПакет.КонтактнаяИнформация.Адрес).Что было
Тип не выводился вовсе: XDTO-пакеты в систему типов не попадали. Причин две.
skipXdtoPackage(true), поэтому у пакета были только имя и пространство имён, а схема изExt/Package.binне разбиралась. Флаг снят.ОбъектXDTO,ФабрикаXDTO,ТипОбъектаXDTO, …) не было в словаре встроенных типов. Синтакс-помощник её отдаёт — проверено на HBK 8.3.26 через bsl-context, — но он есть не в каждой установке, а в тестах отключён.Что сделано
XdtoTypesProviderзаводит тип на каждый объектный тип пакета — под тем же именем, что пишут в ссылке:XDTOПакет.<Пакет>.<Тип>(англоязычный псевдонимXDTOPackage.<Пакет>.<Тип>). Благодаря этому ссылка разрешается реестром напрямую, отдельной нотации не нужно.Члены типа — свойства из схемы пакета, считаются лениво: в крупных конфигурациях объектных типов десятки тысяч. Типы свойств:
xs:string→Строка,xs:dateTime→Дата,xs:decimal→Число,xs:boolean→Булево,xs:base64Binary→ДвоичныеДанные);<valueType name="ТипИндекса" base="xs:decimal"/>) читается по своей базе;Наследование
baseвнутри пакета переносится в реестр, платформенная часть подмешивается отОбъектXDTO.В словарь встроенных типов добавлены
ОбъектXDTO,ЗначениеXDTO,СписокXDTO,ТипОбъектаXDTO,ТипЗначенияXDTO,ФабрикаXDTO(состав снят с HBK 8.3.26) и глобальная переменнаяФабрикаXDTO.Цена
Чтение конфигурации ssl_3_1 (56 пакетов, 21 МБ схем, 14 826 объектных типов) — замер на трёх прогонах:
То есть +0.2…0.7 с однократно при загрузке конфигурации. Память не мерил.
Проверки
XdtoPackageTypesTest: ссылка на объектный тип даёт этот тип; свойства типизированы по схеме (строка, булево, число через простой тип пакета); свойство типа того же пакета даёт его тип, и через него доступны его свойства. В тестовую конфигурацию добавлен пакетПакетТест.Прогоны
*types.*,*context.*,*BuiltinTypesJsonLoaderTest,*GlobalScope*— зелёные.Фабрика XDTO (пункты 3.27 и 3.28)
ФабрикаXDTO.Тип(URI, Имя)отдаёт дескрипторТипОбъектаXDTO, помеченный найденным типом объекта (как коллекция помечается типом элемента), аФабрикаXDTO.Создать(Тип)эту пометку снимает и отдаёт сам тип объекта — так типизируется код без ссылок в комментариях. Пакет ищется по пространству имён: в ссылке пишут имя пакета, в коде — URI.Когда пространство имён вычисляется в рантайме, литерала нет и пометки не возникает — тогда тип задаётся строчной ссылкой (
// См. XDTOПакет.Пакет.Тип), и работает общий механизм типизирующих комментариев: он расчётный тип не заменяет, а дополняет.Покрыто тестами
factoryCreatesObjectOfTypeAddressedByNamespaceиinlineSeeRefTypesObjectWhenNamespaceIsComputed.Summary by CodeRabbit
New Features
ФабрикаXDTO/XDTOFactoryglobal.Tests