Skip to content

fix(types): ссылки специализированных членов приводятся к каноническим - #4368

Merged
nixel2007 merged 5 commits into
developfrom
fix/types-canonical-refs
Aug 2, 2026
Merged

fix(types): ссылки специализированных членов приводятся к каноническим#4368
nixel2007 merged 5 commits into
developfrom
fix/types-canonical-refs

Conversation

@nixel2007

@nixel2007 nixel2007 commented Aug 2, 2026

Copy link
Copy Markdown
Member

Первый из трёх стека, выделенного из #4348.

Что было

Шаблон вида «СправочникСсылка.<Имя справочника>» приходит из синтакс-помощника платформенным, а конфигурационные типы регистрируются своим видом. Структурная специализация сохраняла вид шаблона, поэтому за одним именем оказывались две ссылки, различающиеся только видом: объединение наборов их не схлопывало и тип показывался дважды.

Что стало

Ссылки специализированных членов приводятся к зарегистрированным в реестре. Приведение:

  • не теряет декорации — поля объекта и типы элементов коллекции переезжают на новую ссылку, а если несколько исходных сходятся в одну каноническую, сливаются (TypeSet.mapRefs);
  • заходит внутрь декораций, включая вложенные наборы;
  • доходит до ленивых декораций — они оборачиваются, преобразование применяется к тому, что источник вернёт при чтении, форсить его не нужно;
  • применяется во всех местах специализации, а не только в registerSpecialization: перегрузка без приведения удалена, чтобы неканонические ссылки не попадали в members другими путями.

Проверка

TypeRegistrySpecializationTest, TypeSetTest (перенос декораций, вложенные наборы, ленивые), MemberDescriptorSpecializeTest. Прогнан пакет types.

🤖 Generated with Claude Code

https://claude.ai/code/session_01MnWpDdNSEFohPZHG6voe6y

Summary by CodeRabbit

  • Bug Fixes

    • Improved type specialization so equivalent type references consistently resolve to canonical definitions.
    • Improved handling of nested, decorated, and deferred type references during type mapping.
    • Prevented duplicate type references when specialized members match registered types.
  • Tests

    • Added coverage for canonical type reuse, reference mapping, lazy evaluation, and unchanged type sets.

nixel2007 and others added 4 commits August 2, 2026 08:30
Шаблон вида «СправочникСсылка.<Имя справочника>» приходит из синтакс-помощника
платформенным, а конфигурационные типы регистрируются своим видом. Структурная
специализация сохраняла вид шаблона, поэтому за одним именем оказывались две
ссылки, различающиеся только видом: объединение наборов их не схлопывало и тип
показывался дважды.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MnWpDdNSEFohPZHG6voe6y
Сборка результата через «TypeSet.of» оставляла одни ссылки: поля объекта и типы
элементов коллекции отбрасывались. Приведение переехало в «TypeSet.mapRefs»,
который переносит декорации на новую ссылку, а если несколько исходных ссылок
сходятся в одну каноническую — сливает их.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MnWpDdNSEFohPZHG6voe6y
…еским

Перегруз без приведения оставлял дверь, через которую в members попадали
неканонические ссылки: подстановка сохраняет вид шаблона, поэтому платформенный
шаблон давал платформенную ссылку и на конфигурационный тип. Приведение получили
и остальные места специализации — разворачивание generic-членов, регистры и
подстановка единственного плейсхолдера.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MnWpDdNSEFohPZHG6voe6y
Ленивая декорация оборачивается: преобразование применяется к тому, что её
источник вернёт при чтении, форсить его для этого не нужно. Ключ у обёртки
прежний, поэтому равенство и слияние ленивых ссылок не меняются.

Новые места специализации из типов форм переведены на единственную сигнатуру
с приведением — как и все остальные.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MnWpDdNSEFohPZHG6voe6y
@coderabbitai

coderabbitai Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@nixel2007, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 12 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

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.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 67d2206f-850c-4de7-b3c2-2bbf46122b37

📥 Commits

Reviewing files that changed from the base of the PR and between 06a67de and b6fb481.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/model/MemberDescriptor.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/registry/TypeRegistrySpecializationTest.java
📝 Walkthrough

Walkthrough

TypeSet now maps nested and lazy type references. MemberDescriptor.specialize accepts a canonicalizer. TypeRegistry and registry callers use canonical references during specialization. Tests cover mapping behavior and canonical reference reuse.

Changes

Type reference canonicalization

Layer / File(s) Summary
TypeSet reference mapping
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/model/TypeSet.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/types/model/TypeSetTest.java
TypeSet.mapRefs transforms eager, nested, and lazy references. It merges converging decoration keys and preserves unchanged instances.
Canonicalized member specialization
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/model/MemberDescriptor.java, src/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/...
MemberDescriptor.specialize applies a supplied canonicalizer to return types and parameter types. TypeRegistry and registry callers resolve specialized references to registered instances.
Canonicalization validation
src/test/java/com/github/_1c_syntax/bsl/languageserver/types/model/MemberDescriptorFactoryTest.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/types/model/MemberDescriptorSpecializeTest.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/types/registry/TypeRegistrySpecializationTest.java
Tests update specialization calls and verify nested mapping, lazy evaluation, no-op behavior, and canonical registry references.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant TypeRegistry
  participant MemberDescriptor
  participant TypeSet
  TypeRegistry->>MemberDescriptor: specialize with canonicalRef
  MemberDescriptor->>TypeSet: map parameter type references
  TypeSet-->>MemberDescriptor: return mapped TypeSet
  MemberDescriptor->>TypeRegistry: resolve specialized return references
  TypeRegistry-->>MemberDescriptor: return canonical TypeRef
Loading

Possibly related PRs

Suggested reviewers: sfaqer

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% 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 Заголовок точно описывает основное изменение: канонизацию ссылок специализированных членов типов.
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.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/types-canonical-refs

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/registry/TypeRegistry.java (1)

986-1004: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Canonicalize extension-sourced member references before caching them.

registerExtension passes Map.of() to copyMembers, so MemberDescriptor.specialize(Map, UnaryOperator) returns the descriptor unchanged and canonicalRef does not run. Extension call sites include form command/base type, form type/basic type, form module/forms, form module/ordinary form object, data type/base type, item kind/base type, collection row/base type, generic row, and generic collection. Canonicalize these member references before indexing them to avoid duplicate TypeRefs for the same extension member.

🤖 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/TypeRegistry.java`
around lines 986 - 1004, Update copyMembers so every extension-sourced
MemberDescriptor has its referenced TypeRefs canonicalized even when bindings is
empty, before memberMetadataIndex.index caches it. Apply canonicalRef to the
specialized descriptor or its member references while preserving generic-member
filtering and existing registerMemberSource behavior.
🤖 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/registry/TypeRegistry.java`:
- Around line 986-1004: Update copyMembers so every extension-sourced
MemberDescriptor has its referenced TypeRefs canonicalized even when bindings is
empty, before memberMetadataIndex.index caches it. Apply canonicalRef to the
specialized descriptor or its member references while preserving generic-member
filtering and existing registerMemberSource behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: f5b17fdf-347b-481f-b573-81fd7b7e6fba

📥 Commits

Reviewing files that changed from the base of the PR and between 5a6e8c1 and 06a67de.

📒 Files selected for processing (11)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/model/MemberDescriptor.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/model/TypeSet.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/FormParametersRegistrar.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/FormTypesProvider.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/PlaceholderBinder.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/RegisterTypesRegistrar.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/registry/TypeRegistry.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/model/MemberDescriptorFactoryTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/model/MemberDescriptorSpecializeTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/model/TypeSetTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/registry/TypeRegistrySpecializationTest.java

…ссылки

Специализация возвращала дескриптор как есть при пустых подстановках, а
расширение типа именно так и копирует члены — приведение ссылок к каноническим
у них не выполнялось.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MnWpDdNSEFohPZHG6voe6y
var newReturnTypes = TypeRef.specialize(returnTypes, bindings).mapRefs(canonicalizer);
var newSignatures = signatures;
boolean signaturesChanged = false;
if (!newSignatures.isEmpty()) {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По замечанию про члены расширения — верно. registerExtension копирует члены с пустыми подстановками, а specialize при пустых bindings возвращал дескриптор как есть, и приведение ссылок не выполнялось.

Ранний выход убрал: при пустых подстановках TypeRef.specialize и так ничего не меняет, а mapRefs теперь отрабатывает. Возврат this, когда ничего не изменилось, сохранился — он делается сравнением результата ниже.

Тест TypeRegistrySpecializationTest.extensionMemberTypesAreCanonicalRefsFromRegistry: тип-источник объявляет член с платформенной ссылкой, тип с тем же именем зарегистрирован конфигурационным, члены подмешиваются в цель — у подмешанного члена ожидается каноническая ссылка. Без правки тест красный, проверил.

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Test Results

 3 942 files  ± 0   3 942 suites  ±0   1h 7m 44s ⏱️ -41s
 4 063 tests + 8   3 997 ✅ + 8   66 💤 ±0  0 ❌ ±0 
24 378 runs  +48  23 978 ✅ +48  400 💤 ±0  0 ❌ ±0 

Results for commit b6fb481. ± Comparison against base commit 5a6e8c1.

@nixel2007
nixel2007 merged commit eba4f03 into develop Aug 2, 2026
40 checks passed
@nixel2007
nixel2007 deleted the fix/types-canonical-refs branch August 2, 2026 08:43
@sonarqubecloud

sonarqubecloud Bot commented Aug 2, 2026

Copy link
Copy Markdown

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.

2 participants