Skip to content

feat(oscript): регистрировать &Обходимое-классы OneScript как коллекции#4134

Merged
nixel2007 merged 3 commits into
developfrom
feature/oscript-user-collections
Jun 18, 2026
Merged

feat(oscript): регистрировать &Обходимое-классы OneScript как коллекции#4134
nixel2007 merged 3 commits into
developfrom
feature/oscript-user-collections

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jun 16, 2026

Copy link
Copy Markdown
Member

Что

Пользовательские OneScript-классы, помеченные аннотацией &Обходимое (&Iterable) на ПриСозданииОбъекта, теперь регистрируются в TypeRegistry как коллекции, обходимые через Для Каждого … Цикл. Диагностики и инференс, опирающиеся на supportsForEach, начинают видеть пользовательские коллекции наравне с платформенными.

Closes #4033

Как устроен маркер в OneScript

&Обходимое — маркер итерируемости стандартной библиотеки самого OneScript (не библиотеки extends): класс с ним движок оборачивает в UserIterableContextInstance и требует функцию ПолучитьИтератор(). Ставится на ПриСозданииОбъекта. Именно этот механизм использует collectionos (&Обходимое + ПолучитьИтератор, итератор помечен &Итератор с ТекущийЭлемент()).

Про тип элемента (важно по объёму)

В исходниках OneScript тип элемента коллекции нигде не объявлен: итератор возвращает нетипизированное значение, движок отдаёт Произвольный. Даже в collectionos ТекущийЭлемент() нетипизирован. Поэтому здесь реализовано распознавание коллекции (supportsForEach=true), а тип элемента остаётся «любым» — ровно как у платформенного Массив. Это согласованный объём.

Follow-up — выведено в отдельную задачу #4138 (откуда брать тип элемента коллекции).

Изменения

  • TypeRegistry.setUserTypeIterable(ref, iterable) — императивная пометка USER-типа supportsForEach (+ очистка в unregisterUserType); идемпотентна, пригодна для hot-reload (снятие аннотации снимает признак).
  • OScriptIterable.isIterable(dc) — отдельный компонент (механизм стандартной библиотеки OneScript), детектит &Обходимое/&Iterable на конструкторе ПриСозданииОбъекта.
  • OScriptModuleMembersProvider — проводка при каждой регистрации типа.

Тесты

  • OScriptIterableTest — детект ru/en маркера, отрицательные кейсы (обычный класс, bsl, аннотация на не-конструкторе).
  • OScriptModuleMembersProviderTest — проводка setUserTypeIterable (true/false).
  • OScriptIterableCollectionTest + фикстура iterable-lib — интеграционно: &Обходимое-класс → supportsForEach=true, тип элемента пуст; обычный класс → false.

Прогон целевых тестов: BUILD SUCCESSFUL.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added detection of OneScript iterable collections in the language server.
    • Types annotated with Обходимое or Iterable are now recognized as supporting forEach iteration (with correct default element type handling).
  • Bug Fixes
    • Improved iterable registration so annotation changes are reflected reliably during reloads.
    • Ensured iterable capability flags are properly removed when iterable-capable user types are unregistered.
  • Tests
    • Added unit tests covering iterable-marker detection, ignoring non-constructor placement, and registration/cleanup outcomes.

@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d930a92b-8afd-4257-b81c-00062667cf68

📥 Commits

Reviewing files that changed from the base of the PR and between 2fe245c and 4dac84b.

📒 Files selected for processing (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/OScriptModuleMembersProvider.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/TypeRegistry.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/OScriptModuleMembersProviderTest.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/OScriptModuleMembersProviderTest.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/OScriptModuleMembersProvider.java

📝 Walkthrough

Walkthrough

Introduces OScriptIterable, a Spring component that detects whether an .os document declares an iterable class by scanning constructor annotations for Обходимое/Iterable. OScriptModuleMembersProvider is wired to call this on every type registration. TypeRegistry gains setUserTypeIterable and cleans up iterable state on unregistration.

Changes

OScript iterable collection registration

Layer / File(s) Summary
TypeRegistry iterable API and unregister cleanup
src/main/java/com/.../types/registry/TypeRegistry.java
Adds setUserTypeIterable(TypeRef, boolean, FileType) to imperatively set/clear the supportsForEach flag for USER types per language. Extends unregisterUserType to also remove entries from supportsForEach and defaultElementTypes during cleanup.
OScriptIterable component and provider wiring
src/main/java/com/.../types/oscript/OScriptIterable.java, src/main/java/com/.../types/oscript/OScriptModuleMembersProvider.java
New OScriptIterable Spring component defines RU/EN annotation constants (Обходимое, Iterable) and implements isIterable by scanning OS-file constructors for matching annotations. OScriptModuleMembersProvider injects it and calls typeRegistry.setUserTypeIterable on every registration to support hot-reload of annotation changes.
Unit and integration tests
src/test/java/com/.../types/oscript/OScriptIterableTest.java, src/test/java/com/.../types/oscript/OScriptModuleMembersProviderTest.java, src/test/java/com/.../types/oscript/OScriptIterableCollectionTest.java
OScriptIterableTest covers positive/negative isIterable cases for both annotation names and non-constructor placement. OScriptModuleMembersProviderTest adds mock-based tests verifying setUserTypeIterable is called with correct flags. OScriptIterableCollectionTest verifies end-to-end supportsForEach resolution against fixture library types.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 Hop-hop through the .os files I go,
Sniffing &Обходимое high and low!
A constructor marked—the flag is set,
supportsForEach won't be missed, I bet.
The registry knows who loops with grace,
Each iterable type finds its proper place! 🌿

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.81% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check ❓ Inconclusive PR implements iterable marking and registration (#4033 requirement 2), but does not implement element type extraction/inference from class metadata or type inference in for-each loops (#4033 requirements 1 & 3). Clarify whether this PR is a partial implementation addressing only iterable marking, with element type inference deferred to #4138, or if requirements 1 & 3 should be completed in this PR.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Title clearly describes the main change: registering OneScript classes marked with &Обходимое as iterable collections, which aligns with the changeset's implementation.
Out of Scope Changes check ✅ Passed All changes directly support iterable marking feature: OScriptIterable detection, TypeRegistry integration, provider registration, and comprehensive test coverage with no unrelated modifications.

✏️ 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/oscript-user-collections

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

Copy link
Copy Markdown
Contributor

Test Results

 3 480 files  +12   3 480 suites  +12   1h 41m 49s ⏱️ + 12m 46s
 3 491 tests +15   3 473 ✅ +15   18 💤 ±0  0 ❌ ±0 
20 946 runs  +90  20 834 ✅ +90  112 💤 ±0  0 ❌ ±0 

Results for commit a4a3bbd. ± Comparison against base commit 3dd3a91.

This pull request removes 1 and adds 16 tests. Note that renamed tests count towards both.
com.github._1c_syntax.bsl.languageserver.types.model.MemberDescriptorFactoryTest ‑ withLocalizedNamesAcceptsRuAndEnAtOnce()
com.github._1c_syntax.bsl.languageserver.semantictokens.PlatformMemberMethodCallSemanticTokensSupplierTest ‑ testManagerModuleExportMethodNotColoredAsDefaultLibrary()
com.github._1c_syntax.bsl.languageserver.semantictokens.PlatformMemberMethodCallSemanticTokensSupplierTest ‑ testModifiersForAsyncConfigurationDescriptor()
com.github._1c_syntax.bsl.languageserver.semantictokens.PlatformMemberMethodCallSemanticTokensSupplierTest ‑ testModifiersForConfigurationDescriptor()
com.github._1c_syntax.bsl.languageserver.semantictokens.PlatformMemberMethodCallSemanticTokensSupplierTest ‑ testPlatformManagerMethodKeepsDefaultLibrary()
com.github._1c_syntax.bsl.languageserver.semantictokens.PlatformMemberPropertyAccessSemanticTokensSupplierTest ‑ testOwnAttributeColoredAsPlainProperty()
com.github._1c_syntax.bsl.languageserver.semantictokens.PlatformMemberPropertyAccessSemanticTokensSupplierTest ‑ testStandardAttributeColoredAsDefaultLibrary()
com.github._1c_syntax.bsl.languageserver.types.model.MemberDescriptorFactoryTest ‑ withBilingualNameAcceptsRuAndEnAtOnce()
com.github._1c_syntax.bsl.languageserver.types.oscript.OScriptIterableCollectionTest ‑ classWithIterableAnnotationIsRegisteredAsForEachCollection()
com.github._1c_syntax.bsl.languageserver.types.oscript.OScriptIterableCollectionTest ‑ iterableCollectionHasNoDefaultElementType()
com.github._1c_syntax.bsl.languageserver.types.oscript.OScriptIterableCollectionTest ‑ plainClassIsNotRegisteredAsForEachCollection()
…

♻️ This comment has been updated with latest results.

nixel2007 and others added 2 commits June 18, 2026 08:52
Пользовательские OneScript-классы, помеченные аннотацией &Обходимое
(&Iterable) на ПриСозданииОбъекта, теперь регистрируются в TypeRegistry как
коллекции, обходимые через `Для Каждого … Цикл`. Это движковый маркер
итерируемости (UserIterableContextInstance), который использует, например,
collectionos.

Тип элемента при этом не задаётся: в исходниках OneScript он нигде не
объявлен (итератор возвращает нетипизированное значение), поэтому элемент
остаётся «любым» — ровно как у платформенного Массив. Вывод конкретного
типа элемента вынесен в отдельный follow-up.

- TypeRegistry.setUserTypeIterable(ref, iterable): императивная пометка
  USER-типа supportsForEach (+ очистка в unregisterUserType), идемпотентна
  и пригодна для hot-reload.
- OScriptExtends.isIterable(dc): детект &Обходимое/&Iterable на конструкторе
  (переиспользует чтение аннотаций ПриСозданииОбъекта).
- OScriptModuleMembersProvider: проводка при каждой регистрации типа.

Closes #4033

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
&Обходимое — маркер стандартной библиотеки самого OneScript (движковый
UserIterableContextInstance), к библиотеке extends отношения не имеет.
Перенёс isIterable из OScriptExtends в новый компонент OScriptIterable
(пакет types.oscript), самодостаточный (сканирует аннотации конструктора
через Methods.isOscriptClassConstructorName). OScriptModuleMembersProvider
теперь зависит от OScriptIterable.

Тесты isIterable переехали в OScriptIterableTest.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@nixel2007
nixel2007 force-pushed the feature/oscript-user-collections branch from a4a3bbd to 2fe245c Compare June 18, 2026 06:53
…лишний null-чек

По ревью: скоуп языка протаскивается параметром (как в остальных методах
регистрации TypeRegistry), а не хардкодится FileType.OS внутри; убрана
лишняя проверка ref на null — registerUserType всегда возвращает TypeRef.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@sonarqubecloud

Copy link
Copy Markdown

@nixel2007
nixel2007 merged commit 9d9ca1b into develop Jun 18, 2026
35 checks passed
@nixel2007
nixel2007 deleted the feature/oscript-user-collections branch June 18, 2026 07:24
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.

Регистрировать пользовательские коллекции OneScript как коллекции в системе типов

1 participant