Skip to content

Conversation

@theshadowco
Copy link
Member

@theshadowco theshadowco commented Dec 1, 2025

Описание

  1. Реализация диагностики бассмысленного тернарного оператора
  2. Добавлена возможность сохранить с диагностикой некоторые данные (сейчас строка), которые позже можно использовать, напримр в квикфиксе

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

Closes #203

Чеклист

Общие

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

Для диагностик

  • Описание диагностики заполнено для обоих языков (присутствуют файлы для обоих языков, для русского заполнено все подробно, перевод на английский можно опустить)

Дополнительно

Это переработка заброшенного реквеста #1820

Summary by CodeRabbit

  • New Features

    • Detects and reports useless ternary operators and offers automatic quick fixes.
  • Configuration

    • Added a diagnostic parameter to enable/disable the new check.
  • Documentation

    • New diagnostic page with description and BSL examples (RU/EN).
  • Localization

    • English and Russian strings for diagnostic and quick-fix messages.
  • Tests

    • Unit tests covering detection and quick-fix behavior.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 1, 2025

Walkthrough

Adds a new UselessTernaryOperator diagnostic with quick-fix support, extends DiagnosticStorage to carry supplemental diagnostic data, updates configuration/schema and localization, adds documentation and unit tests.

Changes

Cohort / File(s) Summary
Documentation
docs/diagnostics/UselessTernaryOperator.md, docs/en/diagnostics/UselessTernaryOperator.md
New docs describing the "UselessTernaryOperator" diagnostic with description and examples (useless vs suspicious ternary patterns in BSL).
Diagnostic Implementation
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic.java
New diagnostic class that inspects ternary operators, emits diagnostics for redundant boolean patterns, attaches additional data for some findings, and implements quick-fix generation.
Diagnostic Storage
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
Added DiagnosticAdditionalData record and createAdditionalData factory; new addDiagnostic overloads that accept additional data; createDiagnostic updated to accept and set additional data on produced Diagnostic.
Configuration / Schema
src/main/resources/.../configuration/parameters-schema.json, src/main/resources/.../configuration/schema.json
Added UselessTernaryOperator definition and property to diagnostic parameters; reformatted several enum arrays to multi-line arrays.
Localization
src/main/resources/.../diagnostics/UselessTernaryOperatorDiagnostic_en.properties, ..._ru.properties
New English and Russian localization entries for diagnostic message, name, quick-fix message and adapted quick-fix text.
Tests
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnosticTest.java
New unit tests verifying diagnostics count, ranges, and quick-fix generation/application for sample cases.

Sequence Diagram(s)

sequenceDiagram
    participant Parser as BSL Parser
    participant Diagnoser as UselessTernaryOperatorDiagnostic
    participant Storage as DiagnosticStorage
    participant Client as LSP Client
    participant DocCtx as DocumentContext

    Parser->>Diagnoser: visitTernaryOperator(node)
    Diagnoser->>Diagnoser: analyze condition and branches
    alt pattern detected with quick-fix data
        Diagnoser->>Storage: addDiagnostic(range, DiagnosticAdditionalData, message)
    else simple diagnostic
        Diagnoser->>Storage: addDiagnostic(range, message)
    end
    Storage->>Client: publishDiagnostic(Diagnostic)
    Client->>Diagnoser: request quick fixes (CodeActionParams)
    Diagnoser->>DocCtx: compute TextEdits using DiagnosticAdditionalData
    Diagnoser->>Client: return CodeAction(s) with edits
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Review focus:
    • Propagation and nullability of DiagnosticAdditionalData through DiagnosticStorage and createDiagnostic.
    • Token extraction and pattern-detection logic in UselessTernaryOperatorDiagnostic.visitTernaryOperator.
    • Quick-fix TextEdit ranges and localized replacement text.
    • Unit test coverage and alignment of expected ranges/text with parser behavior.

Possibly related PRs

Suggested labels

hacktoberfest-accepted

Suggested reviewers

  • nixel2007

Poem

🐰 I found a ternary, tangled and terse,
One branch was certain, the other's reverse.
I nibbled the noise, left truth in the nest,
Hop—now the code breathes easy and rests.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Title directly describes the main change: implementation of a useless ternary operator diagnostic for BSL, matching the core functionality across all modified files.
Linked Issues check ✅ Passed The PR successfully implements the objective from issue #203: detecting useless/suspicious ternary operators with pattern recognition, documentation in both languages, quick fixes with additional diagnostic data, and comprehensive test coverage.
Out of Scope Changes check ✅ Passed All changes are within scope: new diagnostic implementation, supporting infrastructure (DiagnosticAdditionalData), configuration schemas, localization files, documentation, and tests directly support issue #203 requirements.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/feat203

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd18c58 and 46783cd.

📒 Files selected for processing (1)
  • docs/diagnostics/UselessTernaryOperator.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • docs/diagnostics/UselessTernaryOperator.md
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: build
  • GitHub Check: build (25, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (25, ubuntu-latest)

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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (8)
docs/diagnostics/UselessTernaryOperator.md (1)

4-26: Добавить примеры исправленного кода / упоминание квикфикса

Описание и примеры «плохого» кода читаются нормально, но сейчас нет ни одного явного примера исправления. По гайдам для docs/*/diagnostics/**/*.md лучше добавить хотя бы короткий блок с «Исправлениями» (например, замена ?(Б = 1, Истина, Ложь) на просто Б = 1 и ?(Б = 0, Ложь, Истина) на НЕ (Б = 0)), и/или явно упомянуть, что часть случаев может быть автоматически исправлена квикфиксом.

docs/en/diagnostics/UselessTernaryOperator.md (1)

4-27: Slight wording polish and add fix examples

Two minor suggestions:

  • The sentence “indicates poor code thoughtfulness” is a bit awkward; something like “indicates poor code design or readability” would read more naturally.
  • As in the Russian doc, it would be useful to add a short “Fixes” section showing the equivalent simplified code (e.g. A = B = 1; and A = NOT (B = 0);) to match the guideline of providing both problematic and fixed examples.
- The placement of Boolean constants "True" or "False" in the ternary operator indicates poor code thoughtfulness.
+ The placement of Boolean constants "True" or "False" in the ternary operator usually indicates poor code design or readability.
src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json (1)

2111-2120: Schema definition is fine; just confirm default behavior

Новая definitions.UselessTernaryOperator полностью повторяет шаблон соседних диагностик (описание, type: ["boolean","object"], $id, title). Единственный момент на проверку — default: true: если политика проекта для новых диагностик не всегда подразумевает включение “по умолчанию”, стоит явно подтвердить, что это ожидаемое поведение.

src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic_en.properties (1)

1-4: English messages OK; optional wording tweak

Строки полностью согласованы с реализацией. Если хочется чуть проще и точнее по смыслу, можно сделать quick-fix сообщение в единственном числе, т.к. обычно пользователь применяет его к одному тернарнику:

-quickFixMessage=Fix some useless ternary operators
+quickFixMessage=Fix useless ternary operator

Но это скорее вкусовщина, текущий вариант тоже приемлем.

src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnosticTest.java (1)

39-84: Tests cover the important paths; only minor robustness/naming nits

Тесты хорошо фиксируют поведение: количество диагностик, их диапазоны и точный текст квикфиксов для обоих случаев (прямая и инвертированная форма).

Пара необязательных улучшений на будущее:

  • Сейчас testQuickFix полагается на порядок срабатывания диагностик (diagnostics.get(0/1)). Если когда‑нибудь изменится обход дерева/порядок добавления, тест начнёт падать, хотя поведение останется корректным. Можно было бы искать нужные диагностики по Range или тексту/данным.
  • Имена reversDiagnostic/reversQuickFix лучше поправить на reverse... для читаемости.

Оба пункта не блокирующие.

src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic.java (1)

42-128: Diagnostic/quick‑fix logic is solid; consider making getBooleanToken more grammar‑robust

В целом реализация выглядит аккуратно и хорошо согласована с документацией/тестами:

  • В visitTernaryOperator корректно обрабатываются все интересующие случаи:
    • константа в условии → “бесполезный” тернарник без автокоррекции;
    • ветки Истина/True + Ложь/False и наоборот → диагностика + допданные для квикфикса;
    • любые другие комбинации с булевыми константами в ветках → “подозрительный” оператор без квикфикса.
  • Использование DiagnosticStorage.DiagnosticAdditionalData и локализованного шаблона quickFixAdaptedText делает квикфикс чистым и расширяемым.
  • Sentinel SKIPPED_RULE_INDEX = 0 безопасен, т.к. токены ANTLR начинаются с 1.

Единственное место, где есть потенциальная хрупкость на будущее — getBooleanToken:

var tmpCtx = Optional.of(expCtx)
  .filter(ctx -> ctx.children.size() == 1)
  .map(ctx -> ctx.member(0))
  .map(ctx -> ctx.getChild(0))
  .filter(BSLParser.ConstValueContext.class::isInstance)
  .map(BSLParser.ConstValueContext.class::cast);

Этот код опирается на текущую структуру грамматики (expression с ровно одним потомком‑member и тем фактом, что первый child — ConstValueContext). Если грамматика expression когда‑нибудь поменяется (например, появится другой wrapper‑контекст), тут можно словить NPE/IOOB либо перестать распознавать булевы константы.

Не критично на сейчас, но как небольшой буст к надёжности можно было бы:

  • либо использовать специализированный подтип контекста (если в грамматике есть отдельная альтернатива для константных выражений),
  • либо добавить дополнительные проверки (ctx.member().size() == 1, instanceof для ctx.member(0).getChild(0) и т.п.).

В остальном реализация выглядит корректной и достаточно простой для сопровождения.

src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java (2)

247-265: Consider reducing duplication by delegating from the existing overload.

The method at lines 228-245 could delegate to this one with null for data, reducing code duplication.

  public void addDiagnostic(
    Range range,
    String diagnosticMessage,
    @Nullable List<DiagnosticRelatedInformation> relatedInformation
  ) {
-
-    if (Ranges.isEmpty(range)) {
-      return;
-    }
-
-    diagnosticList.add(createDiagnostic(
-      diagnostic,
+    addDiagnostic(
      range,
       null,
       diagnosticMessage,
       relatedInformation
-    ));
+    );
  }

286-294: Consider adding null-safety for the input string.

The factory method doesn't validate the input. If null is passed, DiagnosticAdditionalData will hold a null value, which may cause issues when the data is consumed by quickfixes.

  public static DiagnosticAdditionalData createAdditionalData(String string) {
+    if (string == null) {
+      throw new IllegalArgumentException("Additional data string must not be null");
+    }
    return new DiagnosticAdditionalData(string);
  }

Alternatively, annotate the parameter with @NonNull or add a @Nullable annotation to the record field if null is intentionally allowed.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f74aa30 and bc42f49.

⛔ Files ignored due to path filters (1)
  • src/test/resources/diagnostics/UselessTernaryOperatorDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (9)
  • docs/diagnostics/UselessTernaryOperator.md (1 hunks)
  • docs/en/diagnostics/UselessTernaryOperator.md (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java (7 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic.java (1 hunks)
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json (1 hunks)
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json (3 hunks)
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic_en.properties (1 hunks)
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic_ru.properties (1 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnosticTest.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.md

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Keep documentation up to date with code changes

Files:

  • docs/diagnostics/UselessTernaryOperator.md
  • docs/en/diagnostics/UselessTernaryOperator.md
**/diagnostics/*.properties

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Resource bundles for diagnostics should have both Russian and English versions

Files:

  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic_en.properties
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic_ru.properties
**/*.java

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.java: Follow the Style Guide provided in docs/en/contributing/StyleGuide.md
Use Lombok annotations to reduce boilerplate code and enable annotation processing in your IDE
Optimize imports before committing but do NOT optimize imports across the entire project unless specifically working on that task
Follow Java naming conventions with meaningful, descriptive names; keep class and method names concise but clear
Write JavaDoc for public APIs and include comments for complex logic
Use Target Java 17 as the language version

Files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnosticTest.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
**/diagnostics/*.java

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Each diagnostic should have a Java implementation class, resource bundle for localized messages, unit tests, and documentation

Files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnosticTest.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
**/diagnostics/*Test.java

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write comprehensive unit tests for each diagnostic including test cases for edge cases, following existing test patterns

Files:

  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnosticTest.java
**/test/java/**/*.java

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use appropriate test frameworks (JUnit, AssertJ, Mockito) for testing

Files:

  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnosticTest.java
docs/*/diagnostics/**/*.md

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Update diagnostic documentation in both Russian and English with examples of problematic code and fixes

Files:

  • docs/en/diagnostics/UselessTernaryOperator.md
🧠 Learnings (9)
📓 Common learnings
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to docs/*/diagnostics/**/*.md : Update diagnostic documentation in both Russian and English with examples of problematic code and fixes
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to **/diagnostics/*Test.java : Write comprehensive unit tests for each diagnostic including test cases for edge cases, following existing test patterns
Learnt from: nixel2007
Repo: 1c-syntax/bsl-language-server PR: 3308
File: src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl:20-21
Timestamp: 2024-07-04T19:35:26.747Z
Learning: The file `DoubleNegativesDiagnostic.bsl` is a test resource intended to demonstrate the functionality of the DoubleNegatives diagnostic.
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to **/diagnostics/*.java : Each diagnostic should have a Java implementation class, resource bundle for localized messages, unit tests, and documentation
📚 Learning: 2025-11-27T07:17:33.726Z
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to docs/*/diagnostics/**/*.md : Update diagnostic documentation in both Russian and English with examples of problematic code and fixes

Applied to files:

  • docs/diagnostics/UselessTernaryOperator.md
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic_en.properties
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic_ru.properties
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnosticTest.java
  • docs/en/diagnostics/UselessTernaryOperator.md
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
📚 Learning: 2024-07-04T19:35:26.747Z
Learnt from: nixel2007
Repo: 1c-syntax/bsl-language-server PR: 3308
File: src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl:20-21
Timestamp: 2024-07-04T19:35:26.747Z
Learning: The file `DoubleNegativesDiagnostic.bsl` is a test resource intended to demonstrate the functionality of the DoubleNegatives diagnostic.

Applied to files:

  • docs/diagnostics/UselessTernaryOperator.md
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnosticTest.java
📚 Learning: 2025-11-27T07:17:33.726Z
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to **/diagnostics/*.java : Each diagnostic should have a Java implementation class, resource bundle for localized messages, unit tests, and documentation

Applied to files:

  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic_en.properties
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnosticTest.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
📚 Learning: 2025-11-27T07:17:33.726Z
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to **/diagnostics/*.properties : Resource bundles for diagnostics should have both Russian and English versions

Applied to files:

  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic_en.properties
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic_ru.properties
📚 Learning: 2025-11-27T07:17:33.726Z
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to **/diagnostics/*Test.java : Write comprehensive unit tests for each diagnostic including test cases for edge cases, following existing test patterns

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnosticTest.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
📚 Learning: 2025-02-10T17:13:41.452Z
Learnt from: theshadowco
Repo: 1c-syntax/bsl-language-server PR: 3408
File: src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic.java:54-58
Timestamp: 2025-02-10T17:13:41.452Z
Learning: In ProtectedModuleDiagnostic.java, the usage of `Range` field as a diagnostic target is accepted as is, despite being marked as a temporary solution in the comments.

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
📚 Learning: 2025-11-19T09:02:03.154Z
Learnt from: theshadowco
Repo: 1c-syntax/bsl-language-server PR: 3610
File: src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryPackageFoldingRangeSupplier.java:26-26
Timestamp: 2025-11-19T09:02:03.154Z
Learning: В проекте bsl-language-server используется кастомная версия ANTLR4 от 1c-syntax (io.github.1c-syntax:antlr4), которая включает базовый класс org.antlr.v4.runtime.Tokenizer с методами getAst() и getTokens(). SDBLTokenizer и BSLTokenizer наследуются от этого базового класса.

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
📚 Learning: 2025-04-18T22:46:43.245Z
Learnt from: nixel2007
Repo: 1c-syntax/bsl-language-server PR: 3449
File: src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java:192-203
Timestamp: 2025-04-18T22:46:43.245Z
Learning: В проекте bsl-language-server класс BSLParser.ExpressionContext наследуется от BSLParserRuleContext, а не напрямую от ParserRuleContext. При работе с ним нужно учитывать специфичные методы BSLParserRuleContext.

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic.java (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java (1)
  • DiagnosticStorage (50-338)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (25, windows-latest)
  • GitHub Check: build (25, macOS-latest)
  • GitHub Check: build (25, ubuntu-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: Analyse
  • GitHub Check: build
🔇 Additional comments (8)
src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UselessTernaryOperatorDiagnostic_ru.properties (1)

1-4: RU diagnostic strings look consistent

Все ключи и формулировки согласованы между собой и с документацией/квикфиксом (НЕ (%s)), замечаний нет.

src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json (1)

494-496: Diagnostic parameter wiring and enum formatting look correct

Свойство UselessTernaryOperator корректно ссылается на parameters-schema.json#/definitions/UselessTernaryOperator по тому же шаблону, что и остальные диагностики, а изменения enum — чисто форматирование без смены значений. Тут всё в порядке.

Also applies to: 930-989

src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java (6)

77-86: LGTM!

The new overload follows the established pattern correctly, including the node.exception null-check before proceeding.


112-118: LGTM!

Consistent with the existing delegation pattern.


128-135: LGTM!

Delegation chain is consistent with existing overloads.


228-245: LGTM!

Backward compatibility maintained by passing null for the new data parameter.


296-326: LGTM!

The data parameter is properly integrated with a null-check before setting.


327-337: LGTM!

The record is appropriately minimal for the current use case, and the JavaDoc clearly documents that this is an intentionally simple implementation.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
docs/diagnostics/UselessTernaryOperator.md (1)

8-23: Clarify the distinction between "Useless" and "Suspicious" operators with explanatory text.

The two example groups lack explanation of their differences. Line 5 briefly states the purpose but doesn't clarify:

  • What makes a ternary operator "useless" (e.g., equivalent to the condition itself)
  • What makes one "suspicious" (e.g., mixing types or asymmetric logic)
  • What the corrected patterns should be

Additionally, examples mix Russian and English keywords inconsistently, which reduces clarity in Russian documentation.

  Бессмысленные операторы
+ 
+ Когда тернарный оператор возвращает булевы константы, его можно упростить до самого условия:
  
  ```Bsl
  А = ?(Б = 1, Истина, Ложь);
+ // Правильно: А = Б = 1;
  • Подозрительные операторы

  • Когда значения в ветвях имеют несовместимые типы или странную логику:

-А = ?(Б = 1, True, Истина);

  • А = ?(Б = 1, Истина, 0);
    ```Bsl
    
  • А = ?(Б = 0, 0, False);
  • А = ?(Б = 0, Истина, Истина);

This improves clarity by:
- Explaining the underlying issue for each category
- Adding corrected examples to show the intended fix
- Maintaining consistent Russian throughout
- Aligning with learnings on comprehensive diagnostic documentation

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used**: Path: .coderabbit.yaml

**Review profile**: CHILL

**Plan**: Pro

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between bc42f49fa4400b50c6a616135d95716bcc8c4989 and 8a3d6def858ad7f303cc709241d1040c1ed65825.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `docs/diagnostics/UselessTernaryOperator.md` (1 hunks)
* `docs/en/diagnostics/UselessTernaryOperator.md` (1 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary>

* docs/en/diagnostics/UselessTernaryOperator.md

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>📓 Path-based instructions (1)</summary>

<details>
<summary>**/*.md</summary>


**📄 CodeRabbit inference engine (.github/copilot-instructions.md)**

> Keep documentation up to date with code changes

Files:
- `docs/diagnostics/UselessTernaryOperator.md`

</details>

</details><details>
<summary>🧠 Learnings (3)</summary>

<details>
<summary>📓 Common learnings</summary>

Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to docs//diagnostics/**/.md : Update diagnostic documentation in both Russian and English with examples of problematic code and fixes


Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to **/diagnostics/*.java : Each diagnostic should have a Java implementation class, resource bundle for localized messages, unit tests, and documentation


Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to **/diagnostics/*Test.java : Write comprehensive unit tests for each diagnostic including test cases for edge cases, following existing test patterns


</details>
<details>
<summary>📚 Learning: 2025-11-27T07:17:33.726Z</summary>

Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to docs//diagnostics/**/.md : Update diagnostic documentation in both Russian and English with examples of problematic code and fixes


**Applied to files:**
- `docs/diagnostics/UselessTernaryOperator.md`

</details>
<details>
<summary>📚 Learning: 2024-07-04T19:35:26.747Z</summary>

Learnt from: nixel2007
Repo: 1c-syntax/bsl-language-server PR: 3308
File: src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl:20-21
Timestamp: 2024-07-04T19:35:26.747Z
Learning: The file DoubleNegativesDiagnostic.bsl is a test resource intended to demonstrate the functionality of the DoubleNegatives diagnostic.


**Applied to files:**
- `docs/diagnostics/UselessTernaryOperator.md`

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (13)</summary>

* GitHub Check: build (25, ubuntu-latest)
* GitHub Check: build (21, windows-latest)
* GitHub Check: build (25, windows-latest)
* GitHub Check: build (21, macOS-latest)
* GitHub Check: build (25, macOS-latest)
* GitHub Check: build (17, ubuntu-latest)
* GitHub Check: build (21, ubuntu-latest)
* GitHub Check: build (17, windows-latest)
* GitHub Check: build (17, macOS-latest)
* GitHub Check: build
* GitHub Check: Benchmark
* GitHub Check: Analyse
* GitHub Check: Sentry

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java (2)

286-288: Consider validating the string parameter.

The factory method accepts a String parameter but doesn't validate it. Should null strings be rejected, or should the parameter be marked @Nullable to clarify that null is acceptable?

If null strings should be rejected, apply this diff:

 public static DiagnosticAdditionalData createAdditionalData(String string) {
+  if (string == null) {
+    throw new IllegalArgumentException("Additional data string cannot be null");
+  }
   return new DiagnosticAdditionalData(string);
 }

Alternatively, if null is acceptable, mark the parameter as @Nullable:

-public static DiagnosticAdditionalData createAdditionalData(String string) {
+public static DiagnosticAdditionalData createAdditionalData(@Nullable String string) {
   return new DiagnosticAdditionalData(string);
 }

329-331: Consider a more descriptive parameter name.

The record parameter is named string, which is quite generic. Consider renaming it to something more descriptive like value, content, or supplementalInfo to better convey its purpose.

For example:

-public record DiagnosticAdditionalData(String string) {
+public record DiagnosticAdditionalData(String value) {

Note: The JavaDoc correctly acknowledges this is a primitive implementation for the current task. This simple design is appropriate for the initial use case described in the PR objectives (storing supplemental data for quick fixes).

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a3d6de and dd18c58.

📒 Files selected for processing (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java (8 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.java

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.java: Follow the Style Guide provided in docs/en/contributing/StyleGuide.md
Use Lombok annotations to reduce boilerplate code and enable annotation processing in your IDE
Optimize imports before committing but do NOT optimize imports across the entire project unless specifically working on that task
Follow Java naming conventions with meaningful, descriptive names; keep class and method names concise but clear
Write JavaDoc for public APIs and include comments for complex logic
Use Target Java 17 as the language version

Files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
**/diagnostics/*.java

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Each diagnostic should have a Java implementation class, resource bundle for localized messages, unit tests, and documentation

Files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
🧠 Learnings (6)
📓 Common learnings
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to docs/*/diagnostics/**/*.md : Update diagnostic documentation in both Russian and English with examples of problematic code and fixes
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to **/diagnostics/*.java : Each diagnostic should have a Java implementation class, resource bundle for localized messages, unit tests, and documentation
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to **/diagnostics/*Test.java : Write comprehensive unit tests for each diagnostic including test cases for edge cases, following existing test patterns
📚 Learning: 2025-11-27T07:17:33.726Z
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to **/diagnostics/*.java : Each diagnostic should have a Java implementation class, resource bundle for localized messages, unit tests, and documentation

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
📚 Learning: 2025-02-10T17:13:41.452Z
Learnt from: theshadowco
Repo: 1c-syntax/bsl-language-server PR: 3408
File: src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic.java:54-58
Timestamp: 2025-02-10T17:13:41.452Z
Learning: In ProtectedModuleDiagnostic.java, the usage of `Range` field as a diagnostic target is accepted as is, despite being marked as a temporary solution in the comments.

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
📚 Learning: 2025-11-27T07:17:33.726Z
Learnt from: CR
Repo: 1c-syntax/bsl-language-server PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T07:17:33.726Z
Learning: Applies to docs/*/diagnostics/**/*.md : Update diagnostic documentation in both Russian and English with examples of problematic code and fixes

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
📚 Learning: 2025-11-19T09:02:03.154Z
Learnt from: theshadowco
Repo: 1c-syntax/bsl-language-server PR: 3610
File: src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryPackageFoldingRangeSupplier.java:26-26
Timestamp: 2025-11-19T09:02:03.154Z
Learning: В проекте bsl-language-server используется кастомная версия ANTLR4 от 1c-syntax (io.github.1c-syntax:antlr4), которая включает базовый класс org.antlr.v4.runtime.Tokenizer с методами getAst() и getTokens(). SDBLTokenizer и BSLTokenizer наследуются от этого базового класса.

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
📚 Learning: 2025-04-18T22:46:43.245Z
Learnt from: nixel2007
Repo: 1c-syntax/bsl-language-server PR: 3449
File: src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java:192-203
Timestamp: 2025-04-18T22:46:43.245Z
Learning: В проекте bsl-language-server класс BSLParser.ExpressionContext наследуется от BSLParserRuleContext, а не напрямую от ParserRuleContext. При работе с ним нужно учитывать специфичные методы BSLParserRuleContext.

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (12)
  • GitHub Check: build (25, macOS-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (25, windows-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (25, ubuntu-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: Analyse
  • GitHub Check: build
  • GitHub Check: Analyze the repo with CodeSee
🔇 Additional comments (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java (2)

77-86: LGTM! Well-integrated overloads for diagnostic data.

The new addDiagnostic overloads properly follow existing patterns, maintain exception/empty-range checks, delegate correctly through the method chain, and preserve thread safety and backward compatibility.

Also applies to: 112-118, 128-135, 241-259


290-320: LGTM! Proper null-safe handling of additional data.

The method correctly accepts @Nullable DiagnosticAdditionalData, only calls setData when the data is not null, and integrates well with the LSP4j Diagnostic API for use in code action requests.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Dec 1, 2025

@nixel2007 nixel2007 merged commit 7da36e3 into develop Dec 2, 2025
38 checks passed
@nixel2007 nixel2007 deleted the feature/feat203 branch December 2, 2025 13:56
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.

Бесполезный тернарник / Странный тернарник

3 participants