Skip to content

fix(types): не расширять тип строки-аккумулятора до «Строка, Число» (#4205)#4239

Merged
nixel2007 merged 2 commits into
developfrom
claude/string-concat-inference-bug-yfsylp
Jul 2, 2026
Merged

fix(types): не расширять тип строки-аккумулятора до «Строка, Число» (#4205)#4239
nixel2007 merged 2 commits into
developfrom
claude/string-concat-inference-bug-yfsylp

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jul 1, 2026

Copy link
Copy Markdown
Member

Проблема

#4205: при выводе типа переменной, собираемой конкатенацией с самой собой, тип расширялся до Строка, Число:

ПолноеИмя = Имя + Фамилия;          // Строка — верно
ПолноеИмя = ПолноеИмя + "Загадочное"; // становилось "Строка, Число"

В обратном порядке ("..." + ПолноеИмя) баг не проявлялся — что и было отмечено в issue.

Причина

При инференсе типа переменной ExpressionTypeInferencer объединяет типы по всем её присваиваниям. Для ПолноеИмя = ПолноеИмя + "..." правая часть ссылается на саму ПолноеИмя; эта рекурсивная ссылка упиралась в guard циклов (ctx.visited) и резолвилась в TypeSet.EMPTY. Ветка + в inferBinary определяет результат по левому операнду, а для пустого (неизвестного) левого операнда попадала в defaultЧисло. Это ложное Число и подмешивалось в union. При "..." + ПолноеИмя левый операнд — строковый литерал, рекурсии нет, поэтому проблемы не было.

Решение

Причина глубже, чем ветка +: self-reference терял уже известный тип из предыдущих присваиваний. Исправление — на уровне резолва самоссылки, а не подгонки ветки +:

  • inferVariable регистрирует переменную в новом InferenceContext.inProgress и по мере объединения присваиваний публикует туда растущий accumulator;
  • при повторном входе в инференс той же переменной (self-reference) возвращается накопленный к этому моменту тип вместо EMPTY — one-pass фикс-точка по присваиваниям.

Благодаря этому:

  • выражение Строка + "..." корректно выводится в Строка (а не теряет тип);
  • числовой аккумулятор Число = Число + 1 остаётся Число;
  • общая ветка + не изменена — универсальная семантика сложения не затронута.

Тесты

В BinaryOperatorInferenceTest (+ фикстура BinaryOperatorInference.bsl):

⚠️ Прогнать тесты в песочнице не удалось: сборка требует Gradle 9.6.1 (в build.gradle.kts используется multi-dollar interpolation Kotlin 2.1+), а в окружении доступен только Gradle 8.14.3; загрузка дистрибутива 9.6.1 заблокирована сетевой политикой. Проверено трассировкой; расчёт на CI.

Closes #4205

🤖 Generated with Claude Code


Generated by Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved type inference for self-referential and cyclic variable assignments, so partially inferred types no longer get dropped and results stabilize correctly across assignment chains.
    • Enhanced + operator inference in self-reference scenarios, keeping Строка and Число results consistent and preventing incorrect union growth or type widening.
  • Tests
    • Added coverage for self-referential + inference to prevent regressions.

При выводе типа переменной вида `Строка = Строка + "..."` рекурсивная
ссылка на саму переменную упиралась в guard циклов и резолвилась в пустой
набор. Ветка `+` в inferBinary трактовала пустой левый операнд как Число
(default), и это ложное Число подмешивалось в union — тип переменной
расширялся до "Строка, Число". В обратном порядке (`"..." + Строка`) левый
операнд — литерал, поэтому баг не проявлялся.

Причина глубже, чем ветка `+`: self-reference терял уже известный тип из
предыдущих присваиваний. Теперь inferVariable регистрирует переменную в
InferenceContext.inProgress и публикует растущий accumulator по мере
объединения присваиваний; при повторном входе (self-reference) возвращается
накопленный к этому моменту тип вместо EMPTY — one-pass фикс-точка.

Как следствие:
- выражение `Строка + "..."` корректно выводится в Строку (а не теряет тип);
- числовой аккумулятор `Число = Число + 1` остаётся Число;
- общая ветка `+` не изменена.

Closes #4205
@coderabbitai

coderabbitai Bot commented Jul 1, 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: f8b4c9e8-0a1c-4ac0-971b-dea7bb23f3c0

📥 Commits

Reviewing files that changed from the base of the PR and between ce69837 and f3841a1.

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

📝 Walkthrough

Walkthrough

Modifies ExpressionTypeInferencer to track partially inferred variable types via a new inProgress map, so self-referential expressions resolve to accumulated types during cycle detection. Adds regression tests covering string and numeric self-accumulator cases.

Changes

Self-reference type stabilization

Layer / File(s) Summary
InferenceContext in-progress map
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/ExpressionTypeInferencer.java
Adds inProgress to InferenceContext and imports HashMap to store partially inferred TypeSet values.
Cycle-handling and variable inference logic
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/inferencer/ExpressionTypeInferencer.java
resolveReference returns partial types on revisits; inferVariable seeds, updates, and clears inProgress while accumulating declaration and definition sources.
Regression tests for self-referential concatenation
src/test/java/com/github/_1c_syntax/bsl/languageserver/types/BinaryOperatorInferenceTest.java
Adds tests confirming self-referential string concatenation stays Строка and numeric accumulation stays Число for issue #4205.

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

Sequence Diagram(s)

sequenceDiagram
  participant inferVariable
  participant InferenceContext
  participant resolveReference

  inferVariable->>InferenceContext: check inProgress for symbol X
  InferenceContext-->>inferVariable: no entry found
  inferVariable->>InferenceContext: seed inProgress with acc
  inferVariable->>resolveReference: resolve reference to X
  resolveReference->>InferenceContext: read inProgress on cycle detection
  InferenceContext-->>resolveReference: partial TypeSet
  resolveReference-->>inferVariable: partial TypeSet
  inferVariable->>InferenceContext: update inProgress with accumulated result
  inferVariable->>InferenceContext: remove in-progress entry
Loading

Related issues: #4205

Suggested labels: bug, type-inference

Suggested reviewers: maintainers

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly states the self-referential string-type inference bug being fixed and matches the PR's main change.
Linked Issues check ✅ Passed The code and tests address #4205 by preserving accumulated types for self-references, keeping string concatenation as Строка.
Out of Scope Changes check ✅ Passed The changes stay focused on the type inference fix and its regression tests, with no unrelated edits.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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 claude/string-concat-inference-bug-yfsylp

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.

selfConcatenationExpressionIsString указывал курсор на пробел после
оператора `+` (helper прибавляет +1 к колонке), где нет ни одного
терминала — findTerminalNodeContainsPosition возвращал пусто, и тип
получался EMPTY. Ставим курсор внутрь правого операнда: findExpressionContext
поднимается до ближайшего expression-узла (всего бинарного выражения),
и тип корректно выводится в Строку.

Сам фикс инференса не менялся: selfConcatenationVariableStaysString и
numericSelfAccumulatorStaysNumber в CI прошли — падал только этот тест
из-за позиции курсора.
@sonarqubecloud

sonarqubecloud Bot commented Jul 1, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Test Results

 3 588 files  ± 0   3 588 suites  ±0   1h 45m 59s ⏱️ - 5m 22s
 3 540 tests + 3   3 522 ✅ + 3   18 💤 ±0  0 ❌ ±0 
21 240 runs  +18  21 128 ✅ +18  112 💤 ±0  0 ❌ ±0 

Results for commit f3841a1. ± Comparison against base commit 95516cf.

@nixel2007
nixel2007 merged commit a54e857 into develop Jul 2, 2026
37 checks passed
@nixel2007
nixel2007 deleted the claude/string-concat-inference-bug-yfsylp branch July 2, 2026 19: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.

[BUG] Конкатенация строки с собой расширяет выводимый тип до "Строка, Число"

2 participants