Skip to content

fix(diagnostics): не считать счетчик цикла неиспользуемым#4013

Open
johnnyshut wants to merge 2 commits into
1c-syntax:developfrom
johnnyshut:fix/issue-3912-unused-local-variable-for-counter
Open

fix(diagnostics): не считать счетчик цикла неиспользуемым#4013
johnnyshut wants to merge 2 commits into
1c-syntax:developfrom
johnnyshut:fix/issue-3912-unused-local-variable-for-counter

Conversation

@johnnyshut

@johnnyshut johnnyshut commented Jun 7, 2026

Copy link
Copy Markdown
Contributor

Описание

Исправил ложное срабатывание UnusedLocalVariable для переменной-счетчика в цикле Для.

Теперь счетчик цикла не считается неиспользуемой локальной переменной, даже если он не используется внутри тела цикла. Добавил регрессионный пример в тестовую фикстуру диагностики.

Связанные задачи

Closes #3912

Чеклист

Общие

  • Ветка PR обновлена из develop
  • Отладочные, закомментированные и прочие, не имеющие смысла участки кода удалены
  • Изменения покрыты тестами
  • Обязательные действия перед коммитом выполнены (запускал команду gradlew precommit)

Summary by CodeRabbit

  • Bug Fixes
    • Fixed incorrect reporting of loop counter variables as unused; diagnostics now exclude loop counters, reducing false positives and improving analysis accuracy.
    • No changes to public APIs or exported behaviors; this is an internal diagnostic filtering improvement.

…менных для счетчиков циклов for

Добавлена ​​функциональность в UnusedLocalVariableDiagnostic для исключения счетчиков циклов for из списка неиспользуемых. Введены методы для определения диапазонов счетчиков циклов for и проверки, является ли переменная счетчиком циклов for. Обновлены тестовые ресурсы.
@coderabbitai

coderabbitai Bot commented Jun 7, 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: fd15290c-e857-4db9-82b3-6451a18a4703

📥 Commits

Reviewing files that changed from the base of the PR and between 60ebf7e and dedbd7c.

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

📝 Walkthrough

Walkthrough

UnusedLocalVariableDiagnostic now excludes for-loop counter variables from unused-variable diagnostics by precomputing identifier Ranges for for-statement counters and skipping variables whose definition occurrence Ranges match those counters; imports and Javadoc were updated and two private helpers were added.

Changes

For-loop counter false positive fix

Layer / File(s) Summary
Imports and class Javadoc
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnostic.java
Import section updated to include tree and range utilities; class Javadoc extended to note that Для loop counters are not considered unused.
check() precompute and filter
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnostic.java
check() now computes forLoopCounterRanges once and skips variables identified as loop counters before applying the existing "no REFERENCE occurrences" diagnostic condition.
getForLoopCounterRanges helper
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnostic.java
New helper traverses forStatement nodes, extracts loop counter identifier tokens, converts them to Ranges, and returns a collected set.
isForLoopCounter helper
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnostic.java
New helper determines whether a variable is a loop counter by checking if any DEFINITION occurrence selection ranges are contained in the precomputed counter Range set.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • theshadowco
  • nixel2007

Poem

A rabbit counts each loop with care,
Hops silent past false alarms in air,
Counters now pass without a fight,
Diagnostics sleep through the night.
🐇🌿

🚥 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 accurately describes the main fix: preventing loop counters in 'Для' constructs from being flagged as unused variables.
Linked Issues check ✅ Passed The code changes successfully address issue #3912 by excluding 'Для' loop counter variables from unused variable diagnostics through AST traversal and range-based filtering.
Out of Scope Changes check ✅ Passed All changes are directly focused on fixing the UnusedLocalVariableDiagnostic to handle loop counters; no unrelated modifications are present.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

…leDiagnostic

Добавлены Javadoc комментарии к методам класса UnusedLocalVariableDiagnostic, описывающие их функциональность и параметры.
@johnnyshut johnnyshut force-pushed the fix/issue-3912-unused-local-variable-for-counter branch from 60ebf7e to dedbd7c Compare June 7, 2026 12:28
@sonarqubecloud

sonarqubecloud Bot commented Jun 7, 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

1 participant