Repository navigation
feat(types): метод Свойство типизирует переменную-приёмник - #4406
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughДобавлена flow-sensitive типизация переменных во втором параметре ChangesТипизация параметров
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: применяет сужение по проверке ключа
Possibly related PRs
🚥 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.
🧹 Nitpick comments (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/GuardConditionNarrowing.java (1)
105-110: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider centralizing the
Свойствоmethod-name rule.Three components in this PR now encode the same rule with different representations:
- Here:
PROPERTY_RU = "СВОЙСТВО"andPROPERTY_EN = "PROPERTY", compared aftertoUpperCase(Locale.ROOT).PropertyMethodCallIndexLines 59-60:"Свойство"and"Property", compared withequalsIgnoreCase.- 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 winBuild the index outside
computeIfAbsent.
build(ast)walks the whole document AST withTrees.findAllRuleNodes. InsidecomputeIfAbsent, that walk runs while theConcurrentHashMapbin 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.layoutOfandGuardConditionNarrowing.compilecompute the value first and then publish it withputIfAbsent, 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
📒 Files selected for processing (8)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/CLAUDE.mdsrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/DereferenceLocator.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/PropertyMethodCallIndex.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/ExpressionTypeInferencer.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/GuardConditionNarrowing.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/PropertyMethodInference.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/VariableFlowAnalyzer.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/types/PropertyMethodInferenceTest.java
|
Замечания Sonar разобраны. Что исправлено и что осознанно оставлено. Исправлено:
Оставлено осознанно — Речь про Уйти от них можно только заменив позиционные ключи по всему расчёту по потоку — это отдельная работа и не в этом реквесте. Если считаешь, что её стоит завести, скажу спасибо за наводку. Гейт при этом зелёный: он падал только по надёжности, и эти шесть багов исправлены. 🤖 Generated with Claude Code |
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/PropertyMethodInference.java (1)
135-139: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winDo not infer properties from unsupported union branches.
readsNamedPropertiesaccepts aTypeSetwhen only one reference is supported.propertyTypesthen scans every reference, including unsupported receivers. A property declared only on an unsupported receiver can therefore replaceincomingwith an incorrect type.When
receivercontains an unsupported reference, preserveincomingor 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
📒 Files selected for processing (3)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/PropertyMethodCallIndex.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/GuardConditionNarrowing.javasrc/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
`Стр.Свойство("Ключ", Приёмник)` кладёт значение ключа во второй параметр, а
возвращает признак «нашлось ли». Обычным выводом типа такое присваивание не видно
вовсе: справа от знака равенства переменная-приёмник не стоит ни разу.
Это изменение типа на месте — наравне с `Х.Вставить(…)` и присваиванием вида
элементу формы, — но с разворотом: переменная тут не получатель вызова, а его
аргумент, и типизирует её чужой объект. Работает у структуры, фиксированной
структуры и трёх типов данных формы, в обоих написаниях имени метода.
Тип берётся тот же, что дало бы обращение к ключу через точку: сначала поля,
накопленные по коду, затем объявленные члены типа. `Неопределено` не
подмешивается — раз тип значения известен, известно и что ключ есть.
Ветки условия разведены: истинная даёт значение ключа, ложная — ровно
`Неопределено` (`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>
3c1e7a2 to
54b339c
Compare
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/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
📒 Files selected for processing (3)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/ExpressionTypeInferencer.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/PropertyMethodInference.javasrc/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>
|



Что делает
Стр.Свойство("Ключ", Приёмник)кладёт значение ключа во второй параметр, а возвращаетпризнак «нашлось ли». Обычным выводом типа такое присваивание не видно вовсе: справа от знака
равенства переменная-приёмник не стоит ни разу.
Работает у
Структура,ФиксированнаяСтруктура,ДанныеФормыСтруктура,ДанныеФормыСтруктураСКоллекцией,ДанныеФормыЭлементКоллекции, в обоих написаниях имени.Как устроено
Это изменение типа на месте — наравне с
Х.Вставить(…)и присваиванием вида элементуформы, — но с разворотом: переменная тут не получатель вызова, а его аргумент, и типизирует её
чужой объект.
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
Свойство/Propertycalls.Bug Fixes
Documentation