Skip to content

feat(types): метод Свойство типизирует переменную-приёмник - #4406

Merged
nixel2007 merged 5 commits into
developfrom
feat/types-property-method-out-parameter
Aug 8, 2026
Merged

nixel2007 merged 5 commits into
developfrom
feat/types-property-method-out-parameter

Conversation

@sfaqer

@sfaqer sfaqer commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

Что делает

Стр.Свойство("Ключ", Приёмник) кладёт значение ключа во второй параметр, а возвращает
признак «нашлось ли». Обычным выводом типа такое присваивание не видно вовсе: справа от знака
равенства переменная-приёмник не стоит ни разу.

Структура = Новый Структура("Ключ", 1);
Приемник = "А";

Если Структура.Свойство("Ключ", Приемник) Тогда
    А = Приемник;   // Число
Иначе
    Б = Приемник;   // Неопределено
КонецЕсли;

В = Приемник;       // Число, Неопределено

Работает у Структура, ФиксированнаяСтруктура, ДанныеФормыСтруктура,
ДанныеФормыСтруктураСКоллекцией, ДанныеФормыЭлементКоллекции, в обоих написаниях имени.

Как устроено

Это изменение типа на месте — наравне с Х.Вставить(…) и присваиванием вида элементу
формы, — но с разворотом: переменная тут не получатель вызова, а его аргумент, и типизирует её
чужой объект.

  • PropertyMethodCallIndex — вызовы по имени переменной-приёмника. Индексируется methodCall,
    а не callStatement: у метода есть возвращаемое значение, и в реальном коде вызов почти
    всегда стоит внутри условия — индекс по операторам его бы не увидел.
  • PropertyMethodInference — знание про 1С. Тип берётся тот же, что дало бы обращение к ключу
    через точку: сначала поля, накопленные по коду (Вставить, литеральный конструктор), затем
    объявленные члены типа — так реквизиты отдают данные формы.
  • Неопределено не подмешивается: раз тип значения известен, известно и что ключ есть.
    Случай «ключа нет» даёт ложная ветка, а на слиянии обе возможности объединяются сами.

Ветки разведены в GuardConditionNarrowing: он научился читать этот вызов как проверку.
Информативна ровно одна ветка — ложная. Из истины следует только «ключ нашёлся»:
Вставить("Ключ", Неопределено) даёт истину при Неопределено в приёмнике, поэтому убирать
его с истинной ветки нельзя. Отсюда у утверждения признак provesInequality — доказывает ли
проверка отсутствие типа на противоположной ветке.

Ограничения, сделанные сознательно: ключ — только строковым литералом, приёмник — только голая
переменная, получатель — только структуроподобный. Во всех этих случаях тип не выдумывается.

Попутный фикс общего дефекта

Тип выражения, посчитанный изнутри незавершённого расчёта по потоку, оседал в
InferredExpressionTypeIndex и дальше подменял собой посчитанный ответ. Условие кэширования
проверяло только рекурсию символов и про идущий расчёт не знало.

Правая часть каждого присваивания вычисляется как раз изнутри расчёта, поэтому при вложенном
условии про ту же переменную слияние за внешним КонецЕсли теряло целую ветку — при том что
окружение перед оператором расчёт считал верно. Кэш больше не пишется, пока расчёт идёт
(FlowSession.computing).

Дефект общий и старше этой ветки, но воспроизвести его удалось только через новую фичу:
она создаёт форму, где тип в точке слияния меняется между проходами. Отдельным реквестом
без теста отдавать было нечего — тесты nestedCheckInside* покрывают именно его.

Проверка

13 тестов в PropertyMethodInferenceTest на реальной фикстуре конфигурации: обе ветки,
слияние, ранний выход Если НЕ …Тогда Возврат, вложенные проверки, данные формы, путь hover'а
(он ходит через ссылку, а не через выражение) и четыре негативных случая.

Полный check: 667 классов, 4157 тестов, 0 падений.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Improved type inference for variables assigned through Свойство/Property calls.
    • Added support for property lookups on structure-like values, including calls involving other objects.
    • Improved recognition of property existence checks in conditional expressions.
  • Bug Fixes

    • More accurately handles missing keys, undefined values, computed keys, and merged conditional branches.
    • Preserves reliable type information when property keys or receiver types cannot be determined.
  • Documentation

    • Added guidance on property-call type inference and its limitations.

@coderabbitai

coderabbitai Bot commented Aug 5, 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 Plus

Run ID: b7216840-5887-4e44-a14b-c66955fabdff

📥 Commits

Reviewing files that changed from the base of the PR and between 54b339c and 70da02a.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/PropertyMethodInference.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/PropertyMethodInferenceTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/PropertyMethodInference.java

📝 Walkthrough

Walkthrough

Добавлена flow-sensitive типизация переменных во втором параметре Свойство/Property. Реализованы индекс вызовов, вывод типов структуроподобных получателей, сужение типов в условиях и тесты для поддерживаемых и неподдерживаемых случаев.

Changes

Типизация параметров Свойство

Layer / File(s) Summary
Индексирование и вывод типов
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/DereferenceLocator.java, src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/PropertyMethodCallIndex.java, src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/PropertyMethodInference.java
DereferenceLocator и locate стали публичными. Добавлен URI-индекс вызовов Свойство/Property. PropertyMethodInference выводит типы свойств для строковых литералов и структуроподобных получателей.
Интеграция с flow analysis
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/ExpressionTypeInferencer.java, src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/GuardConditionNarrowing.java, src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/VariableFlowAnalyzer.java
ExpressionTypeInferencer учитывает вызовы с выходными параметрами и исключает промежуточное кэширование во время flow analysis. GuardConditionNarrowing обрабатывает проверки наличия ключей и сужает только ложную ветвь до Неопределено.
Проверки и документация
src/test/java/com/github/_1c_syntax/bsl/languageserver/types/PropertyMethodInferenceTest.java, src/main/java/com/github/_1c_syntax/bsl/languageserver/types/CLAUDE.md
Добавлены тесты для ветвления, отрицания, порядка вызовов, неизвестных и вычисляемых ключей, английского имени, форм и неподдерживаемых получателей. Документация описывает индекс и ограничения вывода типов.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ExpressionTypeInferencer
  participant PropertyMethodCallIndex
  participant PropertyMethodInference
  participant GuardConditionNarrowing
  ExpressionTypeInferencer->>PropertyMethodCallIndex: находит вызовы с выходным параметром
  PropertyMethodCallIndex-->>PropertyMethodInference: возвращает вызовы в порядке документа
  ExpressionTypeInferencer->>PropertyMethodInference: выводит тип переменной-получателя
  PropertyMethodInference-->>ExpressionTypeInferencer: применяет тип свойства
  GuardConditionNarrowing->>ExpressionTypeInferencer: применяет сужение по проверке ключа
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.43% 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 feat/types-property-method-out-parameter

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.

🧹 Nitpick comments (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/GuardConditionNarrowing.java (1)

105-110: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider centralizing the Свойство method-name rule.

Three components in this PR now encode the same rule with different representations:

  • Here: PROPERTY_RU = "СВОЙСТВО" and PROPERTY_EN = "PROPERTY", compared after toUpperCase(Locale.ROOT).
  • PropertyMethodCallIndex Lines 59-60: "Свойство" and "Property", compared with equalsIgnoreCase.
  • Both files also declare their own OUT_PARAMETER_INDEX = 1.

The two sides must agree. The index decides which calls are recorded as mutation positions, and this class decides which conditions narrow the receiver. If one spelling rule changes and the other does not, the drift is silent: a condition would narrow a receiver whose call the index never recorded, or the reverse.

A shared constant holder for the method names and the out-parameter index would remove that coupling risk.

🤖 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/GuardConditionNarrowing.java`
around lines 105 - 110, Centralize the `Свойство`/`Property` method-name
constants and `OUT_PARAMETER_INDEX` in a shared holder, then update
`GuardConditionNarrowing` and `PropertyMethodCallIndex` to reference it. Remove
the duplicated local constants while preserving case-insensitive matching and
the existing index value.
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/PropertyMethodCallIndex.java (1)

84-90: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Build the index outside computeIfAbsent.

build(ast) walks the whole document AST with Trees.findAllRuleNodes. Inside computeIfAbsent, that walk runs while the ConcurrentHashMap bin is locked, so concurrent batch-analysis threads that hash to the same bin block on it.

Neighboring caches in this subsystem already avoid this. VariableFlowAnalyzer.layoutOf and GuardConditionNarrowing.compile compute the value first and then publish it with putIfAbsent, citing the same reason. The comment on Line 86 states the same race model as the neighbors, but the locking model differs.

Duplicate work during a race is harmless here, because the built index depends only on the AST.

♻️ Proposed change to publish after building
   public List<BSLParser.MethodCallContext> byOutParameter(URI uri, BSLParser.FileContext ast,
                                                           String variableName) {
     // Та же модель гонки clear<->computeIfAbsent, что у соседних индексов: осевший индекс
     // по прежнему AST уберёт следующая инвалидация.
-    var index = byUri.computeIfAbsent(uri, k -> build(ast));
-    return index.getOrDefault(variableName.toLowerCase(Locale.ROOT), List.of());
+    // Построение идёт ВНЕ computeIfAbsent: обход всего AST под замком корзины выстраивал бы
+    // на нём потоки пакетного анализа. Двойная работа при гонке безвредна — индекс зависит
+    // только от AST.
+    var index = byUri.get(uri);
+    if (index == null) {
+      var built = build(ast);
+      var previous = byUri.putIfAbsent(uri, built);
+      index = previous == null ? built : previous;
+    }
+    return index.getOrDefault(variableName.toLowerCase(Locale.ROOT), List.of());
   }
🤖 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/index/PropertyMethodCallIndex.java`
around lines 84 - 90, Update byOutParameter to call build(ast) before accessing
byUri, then publish the completed index with putIfAbsent and use the resulting
index for the lookup. Preserve the existing URI and variable-name normalization
behavior and the current empty-list fallback, while retaining the documented
clear-versus-compute race model.
🤖 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.

Nitpick comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/PropertyMethodCallIndex.java`:
- Around line 84-90: Update byOutParameter to call build(ast) before accessing
byUri, then publish the completed index with putIfAbsent and use the resulting
index for the lookup. Preserve the existing URI and variable-name normalization
behavior and the current empty-list fallback, while retaining the documented
clear-versus-compute race model.

In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/GuardConditionNarrowing.java`:
- Around line 105-110: Centralize the `Свойство`/`Property` method-name
constants and `OUT_PARAMETER_INDEX` in a shared holder, then update
`GuardConditionNarrowing` and `PropertyMethodCallIndex` to reference it. Remove
the duplicated local constants while preserving case-insensitive matching and
the existing index value.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 56dd9ef6-27b7-4e18-815e-7103d1b975a4

📥 Commits

Reviewing files that changed from the base of the PR and between a86d262 and 47817b3.

📒 Files selected for processing (8)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/CLAUDE.md
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/DereferenceLocator.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/PropertyMethodCallIndex.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/GuardConditionNarrowing.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/PropertyMethodInference.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/VariableFlowAnalyzer.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/PropertyMethodInferenceTest.java

@github-actions

github-actions Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

 4 044 files  + 6   4 044 suites  +6   49m 31s ⏱️ + 1m 12s
 4 203 tests +15   4 132 ✅ +15   71 💤 ±0  0 ❌ ±0 
25 218 runs  +90  24 788 ✅ +90  430 💤 ±0  0 ❌ ±0 

Results for commit 70da02a. ± Comparison against base commit 163d0d9.

♻️ This comment has been updated with latest results.

@sfaqer

sfaqer commented Aug 5, 2026

Copy link
Copy Markdown
Member Author

Замечания Sonar разобраны. Что исправлено и что осознанно оставлено.

Исправлено:

  • шесть багов надёжности (java:S2637) — outParameterName возвращал null без @Nullable в @NullMarked-пакете. Заодно ушло S2589 («выражение всегда истинно»): оно следовало из того же неверного контракта. Метод разложен на три по смыслу, попутно закрылось S1142;
  • S3242 ×2 — тип параметра сужен до SourceDefinedSymbol;
  • замечания CodeRabbit: константы Свойство/позиция приёмника сведены в одно место (разъехавшись, индекс и сужение по условию молча разошлись бы в том, какие вызовы считать), построение индекса вынесено из-под замка корзины ConcurrentHashMap — как у VariableFlowAnalyzer.layoutOf и GuardConditionNarrowing.compile.

Оставлено осознанно — java:S6411 ×9, «типы-ключи Map должны реализовывать Comparable».

Речь про Map<Position, …> и Map<VariableSymbol, …>. Так написан весь этот механизм: mutatorsOf, kindAssignmentsOf и раскладка тела уже возвращают карты по Position, и мой outParameterCallsOf просто третий такой же. Из девяти замечаний четыре — на новых объявлениях, ещё пять Sonar подсветил потому, что сигнатуры mutationPositions/applyMutation получили лишний параметр и строки попали в диф.

Уйти от них можно только заменив позиционные ключи по всему расчёту по потоку — это отдельная работа и не в этом реквесте. Если считаешь, что её стоит завести, скажу спасибо за наводку.

Гейт при этом зелёный: он падал только по надёжности, и эти шесть багов исправлены.

🤖 Generated with Claude Code

@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/inferencer/PropertyMethodInference.java (1)

135-139: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not infer properties from unsupported union branches.

readsNamedProperties accepts a TypeSet when only one reference is supported. propertyTypes then scans every reference, including unsupported receivers. A property declared only on an unsupported receiver can therefore replace incoming with an incorrect type.

When receiver contains an unsupported reference, preserve incoming or explicitly handle that branch as unknown. Add a mixed-receiver regression test.

Proposed fix
-    if (receiver == null || !readsNamedProperties(receiver)) {
+    if (receiver == null || !allRefsReadNamedProperties(receiver)) {
       return incoming;
     }

+  private static boolean allRefsReadNamedProperties(TypeSet receiver) {
+    var refs = receiver.refs();
+    if (refs.isEmpty()) {
+      return false;
+    }
+    for (var ref : refs) {
+      var qualifiedName = ref.qualifiedName();
+      var dot = qualifiedName.indexOf('.');
+      var family = (dot < 0 ? qualifiedName : qualifiedName.substring(0, dot))
+          .toLowerCase(Locale.ROOT);
+      if (!PROPERTY_BEARING_FAMILIES.contains(family)) {
+        return false;
+      }
+    }
+    return true;
+  }

Also applies to: 159-189

🤖 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/PropertyMethodInference.java`
around lines 135 - 139, Update the property inference flow around
readsNamedProperties and propertyTypes so unsupported references in a mixed
receiver do not contribute inferred property types or replace incoming; preserve
incoming or treat those branches as unknown while retaining supported-branch
inference. Apply the same guard to the related logic around the later property
inference block, and add a regression test covering a property declared only on
an unsupported union receiver.
🤖 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/PropertyMethodInference.java`:
- Around line 135-139: Update the property inference flow around
readsNamedProperties and propertyTypes so unsupported references in a mixed
receiver do not contribute inferred property types or replace incoming; preserve
incoming or treat those branches as unknown while retaining supported-branch
inference. Apply the same guard to the related logic around the later property
inference block, and add a regression test covering a property declared only on
an unsupported union receiver.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 0951ce31-0dcd-4e74-9c57-ee2da9a4c204

📥 Commits

Reviewing files that changed from the base of the PR and between 47817b3 and 18b89d3.

📒 Files selected for processing (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/PropertyMethodCallIndex.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/GuardConditionNarrowing.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/PropertyMethodInference.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/PropertyMethodCallIndex.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/GuardConditionNarrowing.java

sfaqer and others added 4 commits August 8, 2026 14:53
`Стр.Свойство("Ключ", Приёмник)` кладёт значение ключа во второй параметр, а
возвращает признак «нашлось ли». Обычным выводом типа такое присваивание не видно
вовсе: справа от знака равенства переменная-приёмник не стоит ни разу.

Это изменение типа на месте — наравне с `Х.Вставить(…)` и присваиванием вида
элементу формы, — но с разворотом: переменная тут не получатель вызова, а его
аргумент, и типизирует её чужой объект. Работает у структуры, фиксированной
структуры и трёх типов данных формы, в обоих написаниях имени метода.

Тип берётся тот же, что дало бы обращение к ключу через точку: сначала поля,
накопленные по коду, затем объявленные члены типа. `Неопределено` не
подмешивается — раз тип значения известен, известно и что ключ есть.

Ветки условия разведены: истинная даёт значение ключа, ложная — ровно
`Неопределено` (`GuardConditionNarrowing` научился читать этот вызов как проверку).
Из истины при этом ничего не следует: `Вставить("Ключ", Неопределено)` даёт истину
при `Неопределено` в приёмнике, поэтому убирать его с истинной ветки нельзя —
у утверждения появился признак `provesInequality`.

Попутный фикс общего дефекта: тип выражения, посчитанный изнутри незавершённого
расчёта по потоку, оседал в кэше и подменял собой посчитанный ответ. Правая часть
каждого присваивания считается как раз оттуда, поэтому при вложенном условии про ту
же переменную слияние за внешним `КонецЕсли` теряло ветку. Кэш больше не пишется,
пока идёт расчёт (`FlowSession.computing`). Дефект общий, но воспроизводится только
через эту фичу — отдельным реквестом без теста отдавать нечего.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sonar, надёжность (шесть багов одной причины): `outParameterName` возвращает `null`,
а тип возврата не был помечен `@Nullable` в `@NullMarked`-пакете. Заодно ушло
седьмое замечание — «выражение всегда истинно» следовало из того же неверного
контракта. Метод разложен на три по смыслу, попутно закрыв S1142.

CodeRabbit:

- имя `Свойство` и позиция приёмника объявлялись дважды — в индексе вызовов и в
  сужении по условию. Разойдись правила, расхождение было бы молчаливым: условие
  сузило бы приёмник, вызов которого индекс не записал. Сведено к константам индекса;
- обход всего AST шёл внутри `computeIfAbsent`, то есть под замком корзины — на
  пакетном анализе потоки выстраивались бы на нём. Построение вынесено наружу,
  публикация через `putIfAbsent`, как у `VariableFlowAnalyzer.layoutOf` и
  `GuardConditionNarrowing.compile`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`outParameterCallsOf` и `apply` используют только то, что есть у
`SourceDefinedSymbol` — имя и владельца. Тип параметра сужен до `VariableSymbol`
без нужды (java:S3242).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…учателя

В смешанном наборе (`Структура, ДокументОбъект.Заказ`) проверка «получатель
структуроподобен» отвечала «да» по одному подходящему типу, а чтение шло по всем.
Одноимённый член неподдержанной части уезжал в приёмник — хотя метода `Свойство`
у неё нет вовсе и платформа туда ничего такого не кладёт.

Получатель сужается до поддержанной части, и уже она идёт в чтение; пустота этой
части заменила прежнюю проверку. Уточнения, накопленные по коду, переезжают вместе
со своими типами.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@sfaqer
sfaqer force-pushed the feat/types-property-method-out-parameter branch from 3c1e7a2 to 54b339c Compare August 8, 2026 04:59

@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.

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/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/PropertyMethodInference.java`:
- Around line 227-229: Update the key-return logic in PropertyMethodInference to
preserve the original literal from
OpenDataObjectInference.stringLiteralOf(tree): retain the null and blank checks,
but return key without trimming so inference uses the exact property name
received by Свойство.
- Around line 103-114: Update PropertyMethodInference.outParameterCallsOf and
the propertyMethodCallIndex.byOutParameter query to preserve method/symbol scope
instead of matching only the lowercased variable name; index or filter results
by the owning symbol so same-named variables in different methods cannot
cross-match. Add a regression test covering same-named receiver variables in two
methods and verify each returns only its own calls.
🪄 Autofix

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: 82a588bc-a6c5-4f5d-ac0f-253bef5098ff

📥 Commits

Reviewing files that changed from the base of the PR and between 18b89d3 and 54b339c.

📒 Files selected for processing (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/ExpressionTypeInferencer.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/PropertyMethodInference.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/PropertyMethodInferenceTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/ExpressionTypeInferencer.java

Индекс ищет вызовы по имени переменной, а имена в разных методах повторяются
сплошь и рядом. Чужие позиции до сих пор отбрасывала раскладка тела — в неё
попадают только операторы своего тела, — но защита была неявной, и в расчёт зря
уезжали позиции со всего модуля.

Теперь отбор явный, как у `OpenDataObjectInference` с операторами-мутаторами.
У переменной модуля область — весь модуль, туда по-прежнему попадают вызовы из
всех его тел.

Тип параметра вернулся к `VariableSymbol`: область объявления есть только у него,
и прежнее замечание Sonar о слишком узком типе больше не применимо.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@sonarqubecloud

sonarqubecloud Bot commented Aug 8, 2026

Copy link
Copy Markdown

@nixel2007
nixel2007 merged commit 4879d10 into develop Aug 8, 2026
36 of 37 checks passed
@nixel2007
nixel2007 deleted the feat/types-property-method-out-parameter branch August 8, 2026 06:53
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