Skip to content

Conversation

@johnnyshut
Copy link
Contributor

@johnnyshut johnnyshut commented Oct 21, 2025

Описание

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

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

Closes #3496

Чеклист

Общие

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

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

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

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

Summary by CodeRabbit

  • Documentation

    • Enhanced MagicDate and MagicNumber docs with new "Exceptions" sections (cases where diagnostics do not trigger), added English/Russian variants and minor formatting fixes.
  • Bug Fixes

    • Diagnostics now correctly skip structure property assignments and structure method calls, reducing false positives.
  • Tests

    • Expanded and added tests covering structure-related scenarios, configuration edge cases, and date validation boundaries.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 21, 2025

Walkthrough

Added documentation “Exceptions” for MagicNumber and MagicDate; diagnostics updated to detect and skip structure property assignments and structure method calls; tests extended/adjusted to cover these exceptions and related edge cases.

Changes

Cohort / File(s) Summary
Docs: MagicNumber (ru/en)
docs/diagnostics/MagicNumber.md, docs/en/diagnostics/MagicNumber.md
Added "Исключения"/"Exceptions" section describing cases where the diagnostic does not trigger (structure property assignments, method calls) with BSL examples; minor code-block formatting fix.
Docs: MagicDate (ru/en)
docs/diagnostics/MagicDate.md, docs/en/diagnostics/MagicDate.md
Added "Исключения"/"Exceptions" section with subsections and examples; added a short intro line and minor formatting adjustments.
Implementation: MagicNumberDiagnostic
src/main/java/.../diagnostics/MagicNumberDiagnostic.java
Introduced detection/early-exit for structure-property assignments and structure method calls; added helpers (isStructurePropertyAssignment, isVariableOfStructureType, isVariableAssignedWithNewStructure, findAssignmentContext, isStructureMethodCall, isStructureObjectCall, isValidCallText, getRootParent), new imports and STRUCTURE_METHOD_PATTERN.
Implementation: MagicDateDiagnostic
src/main/java/.../diagnostics/MagicDateDiagnostic.java
Updated metadata (minutesToFix=5, tags BADPRACTICE/BRAINOVERLOAD); strengthened configuration validation for authorizedDates; centralized decision logic (shouldGenerateDiagnostic); added many AST/navigation and structure-detection helpers and Russian Javadoc.
Tests: MagicDateDiagnosticTest
src/test/java/.../diagnostics/MagicDateDiagnosticTest.java
Added constants, assertion helpers, and numerous tests covering configuration, return statements, structure assignments, invalid/valid dates, boundaries, metadata, and edge cases.
Tests: MagicNumberDiagnosticTest
src/test/java/.../diagnostics/MagicNumberDiagnosticTest.java
Adjusted expected diagnostic counts/ranges, added helper assertions, and added tests asserting no diagnostics for structure method calls and property assignments.

Sequence Diagram(s)

sequenceDiagram
    participant Evaluator as DiagnosticEvaluator
    participant Decision as shouldGenerateDiagnostic()
    participant StructDetect as StructureDetectionHelpers
    participant Validator as Pattern/ValueValidator
    rect rgb(240,248,255)
    Evaluator->>Decision: evaluate literal/expression node
    Decision->>StructDetect: isStructurePropertyAssignment / isStructureMethodCall?
    alt structure-related (true)
        StructDetect-->>Decision: true
        Decision-->>Evaluator: skip diagnostic (exempt)
    else not-structure (false)
        StructDetect-->>Decision: false
        Decision->>Validator: run pattern/date/number checks
        alt violation detected
            Validator-->>Decision: violation
            Decision-->>Evaluator: emit diagnostic
        else no violation
            Validator-->>Decision: no violation
            Decision-->>Evaluator: skip diagnostic
        end
    end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Review focus:
    • AST navigation helpers: navigateToParent, getRootParent, findAssignmentContext
    • Structure-detection heuristics: isVariableOfStructureType, isVariableAssignedWithNewStructure
    • Interaction points in isWrongExpression / shouldGenerateDiagnostic
    • New/adjusted tests in MagicDateDiagnosticTest and MagicNumberDiagnosticTest for correctness and coverage

Suggested reviewers

  • nixel2007
  • theshadowco

Poem

🐰 I hopped through docs and code tonight,
Found structure calls and gave them light.
False alarms now quiet, tests hum bright,
A tiny carrot fix — all tucked tight.

Pre-merge checks and finishing touches

✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main fix: resolving false positives in MagicNumber and MagicDate diagnostics when working with structures.
Linked Issues check ✅ Passed Code changes fully address issue #3496 by implementing detection for structure property assignments and method calls to suppress false positives in both MagicNumber and MagicDate diagnostics.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing false positives in structure-related contexts; documentation updates in both languages and test expansions support the primary objective without introducing unrelated functionality.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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: 1

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

201-217: Consider simplifying the null-safety checks.

The implementation correctly identifies structure property assignments by checking for acceptor.accessProperty(). However, the lValue.isEmpty() check on line 212 may be redundant since an empty lValue would result in a null acceptor, which is already handled by the Objects::nonNull filter on line 214.

Consider this minor simplification:

  private static boolean insideStructurePropertyAssignment(Optional<BSLParser.ExpressionContext> expression) {
    return expression
      .map(BSLParserRuleContext::getParent) // callParam
      .filter(context -> context.getChildCount() == 1)
      .map(BSLParserRuleContext::getParent) // callParamList
      .filter(context -> context.getChildCount() == 1)
      .map(BSLParserRuleContext::getParent) // doCall
      .map(BSLParserRuleContext::getParent) // assignment
      .filter(BSLParser.AssignmentContext.class::isInstance)
      .map(BSLParser.AssignmentContext.class::cast)
      .map(BSLParser.AssignmentContext::lValue)
-     .filter(lValue -> lValue != null && !lValue.isEmpty())
+     .filter(Objects::nonNull)
      .map(BSLParser.LValueContext::acceptor)
      .filter(Objects::nonNull)
      .map(acceptor -> acceptor.accessProperty() != null)
      .orElse(false);
  }
📜 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 bb7196c and 0643789.

📒 Files selected for processing (7)
  • docs/diagnostics/MagicDate.md (1 hunks)
  • docs/diagnostics/MagicNumber.md (2 hunks)
  • docs/en/diagnostics/MagicDate.md (1 hunks)
  • docs/en/diagnostics/MagicNumber.md (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (3 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1 hunks)
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json (2 hunks)
⏰ 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 (23, windows-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build
  • GitHub Check: Analyse
  • GitHub Check: Benchmark
🔇 Additional comments (8)
src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json (1)

924-929: LGTM! Formatting improvement.

The enum arrays have been reformatted from single-line to multi-line for better readability. No semantic changes.

Also applies to: 933-939, 943-947, 978-983

docs/diagnostics/MagicNumber.md (1)

34-56: LGTM! Clear documentation of exception cases.

The new "Exceptions" section effectively documents when the diagnostic does not trigger, with clear code examples for structure property assignments and method calls.

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

37-37: LGTM! Necessary import added.

The Objects import is used for the null-safety check in the new insideStructurePropertyAssignment method.


98-98: The implementation is incomplete and does not cover direct property assignments.

My verification confirms the original review comment's concern. The insideStructurePropertyAssignment method traverses through callParam → callParamList → doCall → assignment, which only suppresses diagnostics when the magic date is inside a method call. However, it does not handle direct property assignments like Structure.Property = '20240101'.

Evidence:

  • The implementation specifically requires doCall (method call context) in the traversal path
  • Direct property assignments lack this intermediate node structure
  • Test data file contains no test cases for direct property assignments
  • The method only detects assignments where the RHS contains a method/function invocation, not bare value assignments

This gap means direct property assignments to structure properties will still trigger the diagnostic, contrary to what the review comment verified.

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

129-160: Implementation is sound, but verify it's used correctly.

The helper methods isStructurePropertyAssignment and findAssignmentContext are well-implemented:

  • findAssignmentContext correctly traverses up the AST to find the nearest AssignmentContext
  • isStructurePropertyAssignment properly checks for structure property access via acceptor.accessProperty()

However, the usage of this method in isWrongExpression (line 121) may be incorrect. See the related comment on lines 118-123.

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

39-60: LGTM! Clear exception documentation.

The Exceptions section clearly documents the cases where the diagnostic does not trigger, with helpful code examples for both structure property assignments and method calls.

docs/diagnostics/MagicDate.md (1)

39-60: LGTM! Comprehensive exception documentation.

The Exceptions section effectively documents when the MagicDate diagnostic does not trigger, with clear Russian code examples for structure property assignments and method calls.

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

34-56: LGTM! Helpful exception documentation.

The Exceptions section clearly describes the non-trigger scenarios with appropriate code examples for both structure property assignments and method calls.

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

♻️ Duplicate comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

202-230: Code duplication: identical helpers in MagicNumberDiagnostic.

These methods are duplicated in MagicNumberDiagnostic.java (lines 137-163). See the refactoring suggestion in that file to extract shared logic to a common utility class.

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

137-163: Consider extracting shared helper methods to a common utility class.

Both isStructurePropertyAssignment and findAssignmentContext have identical implementations in MagicDateDiagnostic.java (lines 202-230). Extracting these to a shared utility class would improve maintainability and reduce duplication.

For example, create a utility class in the diagnostics package:

package com.github._1c_syntax.bsl.languageserver.diagnostics;

public final class StructureAssignmentHelper {
  
  private StructureAssignmentHelper() {
    // utility class
  }
  
  public static boolean isStructurePropertyAssignment(BSLParser.ExpressionContext expression) {
    var assignment = findAssignmentContext(expression);
    if (assignment == null) {
      return false;
    }
    
    var lValue = assignment.lValue();
    if (lValue == null || lValue.isEmpty()) {
      return false;
    }
    
    var acceptor = lValue.acceptor();
    return acceptor != null && acceptor.accessProperty() != null;
  }
  
  public static BSLParser.AssignmentContext findAssignmentContext(BSLParserRuleContext ctx) {
    var current = ctx.getParent();
    while (current != null) {
      if (current instanceof BSLParser.AssignmentContext assignmentContext) {
        return assignmentContext;
      }
      current = current.getParent();
    }
    return null;
  }
}
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

37-37: Remove unused import.

The java.util.Objects import added on line 37 is not used anywhere in the file.

Apply this diff:

-import java.util.Objects;
📜 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 0643789 and a73b562.

⛔ Files ignored due to path filters (1)
  • src/test/resources/diagnostics/MagicNumberDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (6)
  • docs/diagnostics/MagicDate.md (1 hunks)
  • docs/diagnostics/MagicNumber.md (2 hunks)
  • docs/en/diagnostics/MagicDate.md (1 hunks)
  • docs/en/diagnostics/MagicNumber.md (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (3 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • docs/en/diagnostics/MagicDate.md
  • docs/diagnostics/MagicDate.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). (12)
  • GitHub Check: Analyse
  • GitHub Check: build
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: Benchmark
🔇 Additional comments (4)
docs/diagnostics/MagicNumber.md (2)

34-56: Well-documented exceptions align with the fix.

The new "Exceptions" section clearly explains when the diagnostic does not trigger, using concrete, representative examples that match the reported issue. The examples correctly show structure property assignments and method calls as exception cases. The formatting and Russian description are clear and consistent with the documentation style.


34-56: Verify whether English documentation requires parallel updates.

The PR checklist mentions descriptions should be filled for both Russian and English versions (though English translation can be omitted). Please confirm whether a corresponding English documentation file (likely docs/diagnostics/MagicNumber.md or similar without language qualifier) needs to be updated with equivalent exception documentation.

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

34-56: LGTM! Clear documentation of exceptions.

The new Exceptions section clearly documents when the diagnostic should not trigger, with helpful examples that align with the PR objectives.

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

118-131: Logic is correct - false positive issue properly addressed.

Contrary to the previous review comment, the current implementation correctly excludes structure property assignments. The early return with false on line 123 ensures the filter rejects structure property assignments, making the Optional empty and causing isWrongExpression to return false, which prevents the diagnostic from firing.

Logic flow:

  • If isStructurePropertyAssignment → filter returns false → Optional empty → isPresent() returns false → diagnostic does NOT fire ✓

The code has been updated since the previous review and now implements the correct behavior.

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)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

37-37: Remove unused import.

The java.util.Objects import is not used anywhere in this file.

Apply this diff to remove the unused import:

-import java.util.Objects;
📜 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 a73b562 and 1dd0160.

📒 Files selected for processing (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (3 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.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: Analyse
  • GitHub Check: build
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: Benchmark
🔇 Additional comments (4)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2)

42-42: LGTM! Test expectation correctly updated.

The reduction from 18 to 17 diagnostics reflects the new suppression logic for structure property assignments.


72-72: LGTM! Test expectation correctly updated.

The reduction from 10 to 9 diagnostics confirms the suppression logic works correctly with custom configuration.

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

97-100: LGTM! Past review concern successfully addressed.

The diagnostic condition now correctly includes the insideStructurePropertyAssignment check, resolving the critical issue flagged in the previous review where this method was defined but not called.


203-226: LGTM! Logic correctly detects structure property assignments.

The method properly traverses the AST to find assignments with property accessors, successfully identifying patterns like structure.property = value. Null safety is appropriately handled at each step.

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: 2

📜 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 1dd0160 and 90ab479.

📒 Files selected for processing (4)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java (2 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-04-18T22:46:43.245Z
Learnt from: nixel2007
PR: 1c-syntax/bsl-language-server#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/AbstractVisitorDiagnostic.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: Analyse
  • GitHub Check: build
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: Analyze the repo with CodeSee
🔇 Additional comments (4)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (2)

118-131: LGTM! Logic correctly excludes structure property assignments.

The filter logic is correct: when isStructurePropertyAssignment returns true, the filter returns false, making the Optional empty, so isPresent() returns false and the diagnostic does not fire. This aligns with the PR objective to suppress false positives for structure property assignments.


143-162: No code duplication found. The method correctly uses the inherited implementation from AbstractVisitorDiagnostic.

The verification confirms that MagicNumberDiagnostic extends AbstractVisitorDiagnostic and the call to findAssignmentContext at line 150 correctly resolves to the inherited protected static method defined in the base class. There is no private duplicate implementation in MagicNumberDiagnostic, so no refactoring is needed.

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

42-60: LGTM! Test expectations updated correctly.

The diagnostic count adjustments (18→17 and 10→9) correctly reflect the new behavior where structure property assignments no longer trigger the MagicDate diagnostic.

Also applies to: 72-82

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

52-67: Code verified—shared implementation is properly reused.

The search confirms that both MagicNumberDiagnostic and MagicDateDiagnostic are calling the shared findAssignmentContext() method from AbstractVisitorDiagnostic (lines 150 and 209 respectively). No duplicate private implementations exist in the subclasses. The refactoring successfully eliminated code duplication.

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: 2

♻️ Duplicate comments (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1)

86-180: Refactor or remove redundant test methods.

These six test methods repeat the same pattern from past reviews: all call getDiagnostics() on the default fixture and verify different subsets of the same 17 diagnostics. They don't isolate specific behaviors with dedicated test inputs.

For example:

  • testValidDateFormats claims to test various date formats but doesn't create test code with different format variations
  • testReturnSimpleDate claims to verify return statement suppression but doesn't create a focused test case with only return statements
  • testStructurePropertyAssignment claims to test structure property suppression but doesn't create test code demonstrating structure property assignments

These tests don't add value beyond the main test() method. Consider:

  1. Removing these tests entirely, or
  2. Refactoring each to test focused scenarios with custom test code via getDocumentContext(testCode):
    @Test
    void testStructurePropertyAssignment() {
      var testCode = """
        Структура = Новый Структура();
        Структура.Свойство = "00020101";  // Should NOT trigger diagnostic
        Переменная = "00020101";           // SHOULD trigger diagnostic
        """;
      var diagnostics = getDiagnostics(getDocumentContext(testCode));
      assertThat(diagnostics).hasSize(1);
      assertThat(diagnostics, true).hasRange(2, ...);  // Only line 2
    }

Based on past review comments.

📜 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 90ab479 and 4a4f2e7.

📒 Files selected for processing (1)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (3 hunks)

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

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/diagnostics/MagicDateDiagnostic.java (1)

139-156: Time bounds are too permissive (can accept 24:60:60).

Use canonical ranges to avoid false positives on invalid date strings.

Apply this diff:

-    return hh <= 24 && mm <= 60 && ss <= 60;
+    return hh >= 0 && hh < 24 && mm >= 0 && mm < 60 && ss >= 0 && ss < 60;
♻️ Duplicate comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

298-307: Duplicate helper: extract or reuse base implementation.

findAssignmentContext(...) appears here and (likely) in related diagnostics. Prefer a single protected static helper in AbstractVisitorDiagnostic; remove duplicates and call the shared one.

Apply this diff (assuming base now provides it):

-  private static BSLParser.AssignmentContext findAssignmentContext(BSLParserRuleContext ctx) {
-    var current = ctx.getParent();
-    while (current != null) {
-      if (current instanceof BSLParser.AssignmentContext assignmentContext) {
-        return assignmentContext;
-      }
-      current = current.getParent();
-    }
-    return null;
-  }

If not yet extracted, move this implementation to AbstractVisitorDiagnostic and adjust usages accordingly.

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

83-89: Normalize configured authorizedDates to digits‑only and validate length.

isExcluded() strips non‑digits from candidate values; mirror that normalization here to ensure matches and reduce surprises.

Apply this diff:

-    Set<String> authD = Arrays.stream(authorizedDatesString.split(","))
-      .map(String::trim)
-      .collect(Collectors.toSet());
+    Set<String> authD = Arrays.stream(authorizedDatesString.split(","))
+      .map(String::trim)
+      .map(s -> nonNumberPattern.matcher(s).replaceAll(""))
+      .filter(s -> !s.isEmpty() && (s.length() == 8 || s.length() == 12 || s.length() == 14))
+      .collect(Collectors.toSet());

118-131: 12‑digit format gap vs defaults.

DEFAULT_AUTHORIZED_DATES contains "000101010000" (12 digits), but string validation accepts only 8/14 digits. If 12‑digit "YYYYMMDDHHMM" strings are valid inputs in this context, extend the validator accordingly.

  • Update validator to handle 12‑digit strings:
-  if (strDate.length() == 8) {
+  if (strDate.length() == 8) {
     return true;
   }
-  var hh = parseInt(strDate.substring(8, 10));
-  var mm = parseInt(strDate.substring(10, 12));
-  var ss = parseInt(strDate.substring(12, 14));
-  return hh <= 24 && mm <= 60 && ss <= 60;
+  if (strDate.length() == 12) {
+    var hh = parseInt(strDate.substring(8, 10));
+    var mm = parseInt(strDate.substring(10, 12));
+    return hh >= 0 && hh < 24 && mm >= 0 && mm < 60;
+  }
+  var hh = parseInt(strDate.substring(8, 10));
+  var mm = parseInt(strDate.substring(10, 12));
+  var ss = parseInt(strDate.substring(12, 14));
+  return hh >= 0 && hh < 24 && mm >= 0 && mm < 60 && ss >= 0 && ss < 60;
  • If 12‑digit strings are intended, also broaden paramPattern to include 12 digits:
    ""[0123]{1}\d{7}"|"[0123]{1}\d{11}"|"[0123]{1}\d{13}"

195-209: getExpression() brittleness (strict childCount==1 hops).

This can miss valid trees with extra trivia nodes. Consider a more tolerant climb (e.g., walk parents until ExpressionContext) or reuse a central AST utility.

📜 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 4a4f2e7 and 198a942.

📒 Files selected for processing (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (9 hunks)
⏰ 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). (9)
  • GitHub Check: Analyse
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (17, windows-latest)
🔇 Additional comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

107-111: Structure‑property suppression is correctly wired.

The added check prevents false positives for structure property assignments as intended. LGTM.

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: 2

♻️ Duplicate comments (3)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2)

85-167: Remove or refactor superficial test methods.

These five test methods (testValidDateFormats, testExcludedDates, testSimpleDateAssignment, testReturnSimpleDate, testAssignmentWithDateMethod) all perform identical operations—calling getDiagnostics() and asserting size/ranges—without isolating or verifying the specific private methods they claim to test. Past review feedback already identified this issue with similar tests.

Consider either removing these redundant tests or refactoring them to create focused test cases that exercise specific validation logic (e.g., dedicated fixtures for date format validation, exclusion lists, or assignment contexts).


169-198: Misleading test—correct the comment and add focused structure property assignment test cases.

The comment at lines 175-176 incorrectly identifies line 30 as a structure property assignment when it's actually an Execute() call. Past review confirmed this discrepancy. Additionally, the test doesn't demonstrate actual structure property assignment suppression (e.g., Структура.Свойство = "00020101" or Структура.Вставить("Ключ", "00020101")).

Required fixes:

  1. Remove or correct the misleading comment.
  2. Add dedicated test cases with actual structure property assignments to verify the suppression feature works as intended.
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

281-291: Consider narrowing suppression to Structure type only.

The current implementation suppresses diagnostics for all property assignments (e.g., Obj.Property = "00020101"), regardless of whether the base object is a Структура/Structure. Past review identified this over-broad suppression concern.

To align precisely with the PR objective, consider using documentContext.getSymbolTree() (available to diagnostics) to verify the base expression type is Структура/Structure before suppressing. This would prevent unintended suppression for non-Structure property assignments and ensure test coverage includes such cases.

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

149-162: Consider narrowing suppression to Structure type only.

The current implementation suppresses diagnostics for all property assignments (e.g., Obj.Property = 20), regardless of whether the base object is actually a Структура/Structure. This matches the over-broad suppression concern raised in the MagicDateDiagnostic past review.

To align with the PR objective (suppress for structure properties specifically), consider using documentContext.getSymbolTree() to verify the base expression type is Структура/Structure before suppressing. This refinement would prevent unintended suppression for non-Structure property assignments.

📜 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 198a942 and b9ac178.

⛔ Files ignored due to path filters (1)
  • src/test/resources/diagnostics/MagicNumberDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (8)
  • docs/diagnostics/MagicDate.md (1 hunks)
  • docs/diagnostics/MagicNumber.md (2 hunks)
  • docs/en/diagnostics/MagicDate.md (1 hunks)
  • docs/en/diagnostics/MagicNumber.md (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java (2 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (10 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • docs/diagnostics/MagicDate.md
  • docs/en/diagnostics/MagicDate.md
  • docs/diagnostics/MagicNumber.md
  • docs/en/diagnostics/MagicNumber.md
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-04-18T22:46:43.245Z
Learnt from: nixel2007
PR: 1c-syntax/bsl-language-server#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/AbstractVisitorDiagnostic.java
🔇 Additional comments (4)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java (1)

52-67: LGTM! Well-placed helper to eliminate duplication.

The findAssignmentContext method correctly walks up the AST to locate the nearest enclosing AssignmentContext. Extracting this logic to the base class eliminates duplication between MagicDateDiagnostic and MagicNumberDiagnostic, improving maintainability.

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

118-131: LGTM! Structure property assignment suppression logic is correct.

The early-return pattern at lines 122-124 correctly suppresses the diagnostic when isStructurePropertyAssignment returns true. The flow ensures structure property assignments (e.g., Структура.Свойство = 20) do not trigger MagicNumber diagnostics, aligning with the PR objectives.

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

108-111: LGTM! Structure property assignment check correctly integrated.

The addition of insideStructurePropertyAssignment at line 111 correctly suppresses the diagnostic for structure property assignments, resolving the critical issue from past reviews. The condition chain now properly handles all intended exclusion contexts.


77-273: LGTM! Well-documented validation and context detection methods.

The new and updated methods (configure, isValidDate, parseInt, isAccepted, isExcluded, getExpression, and various context-checking helpers) are well-structured with clear Javadoc comments. The validation logic for date formats and context detection is straightforward and appropriate for the diagnostic's purpose.

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

♻️ Duplicate comments (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1)

85-174: Remove or refactor superficial test methods that don't add meaningful coverage.

These five test methods (testValidDateFormats, testExcludedDates, testSimpleDateAssignment, testReturnSimpleDate, testAssignmentWithDateMethod) all call getDiagnostics() on the same fixture and assert subsets of the same 17 diagnostics. They claim to test specific scenarios (various date formats, excluded dates, simple assignments, return statements, Date() method usage) but don't isolate or demonstrate those behaviors—they simply repeat assertions on the same integration test output.

These tests were flagged as redundant in previous review rounds and haven't been meaningfully improved. Consider either:

  1. Removing them entirely (recommended), or
  2. Creating focused test fixtures that isolate each scenario:
    • Create separate .bsl files with specific test cases for each scenario
    • Use dedicated configuration where relevant (e.g., for excluded dates)
    • Assert the specific behavior being tested (e.g., for testExcludedDates, configure authorized dates and verify those specific dates don't generate diagnostics)
📜 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 3417507 and 2762463.

📒 Files selected for processing (1)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2 hunks)
🔇 Additional comments (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1)

42-42: Diagnostic count reduction is correct and properly implemented.

The test counts were reduced (18→17 and 10→9) due to newly added logic in MagicDateDiagnostic.insideStructurePropertyAssignment() that suppresses magic date diagnostics when they appear in structure property assignments.

Verification confirms:

  • The diagnostic implementation includes the insideStructurePropertyAssignment() method (lines 280-293) that checks if a magic date is on the right-hand side of a structure property assignment
  • The method is correctly called in visitConstValue() as part of the suppression chain
  • Fixture line 32 (ОтборЭлемента.ПравоеЗначение = Новый СтандартнаяДатаНачала(Дата('19800101000000'));) contains exactly this pattern: a structure property assignment with a magic date inside a Date() constructor
  • This is the suppressed diagnostic causing the count reduction from 18→17 (first test) and 10→9 (second test)

The change is intentional and appropriate—it reduces false positives by not flagging magic dates in structure property assignments where the property name itself provides semantic context.

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

♻️ Duplicate comments (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)

122-122: Remove redundant class name qualifier.

As noted in the past review, the explicit MagicNumberDiagnostic. qualifier is unnecessary when calling a static method from within the same class.

Apply this diff:

-        if (MagicNumberDiagnostic.isStructurePropertyAssignment(expression)) {
+        if (isStructurePropertyAssignment(expression)) {
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

421-451: Over-broad suppression remains unaddressed: matches any property assignment.

The implementation suppresses diagnostics for all property assignments (e.g., Obj.Date = "20250101"), not just Structure properties. The past review flagged this concern and suggested using documentContext.getSymbolTree() to verify the base type is actually "Структура"/"Structure", but this type validation was not implemented.

This means cases like:

ОтборЭлемента.ПравоеЗначение = "19800101"  // Not a Structure, but suppressed

will incorrectly suppress the diagnostic.

Consider either:

  1. Adding type checking via the symbol tree to verify the base object is a Structure type, or
  2. Documenting this limitation if type information is unavailable or the broader suppression is intentional
🧹 Nitpick comments (2)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2)

191-221: Clarify test expectations for return statement suppression.

The Javadoc states "Проверяет, что возврат дат из функций НЕ генерирует диагностики" (verifies that returning dates from functions does NOT generate diagnostics), but the test expects 19 diagnostics—the same count as the main test.

If return statements are being suppressed, we'd expect either:

  1. Fewer diagnostics than the baseline test, or
  2. Assertions that specifically verify return statement lines are absent from the diagnostic list

The current test doesn't demonstrate that return statement suppression is working. Consider adding explicit checks using assertNoDiagnosticOnLine for specific return statement lines to verify suppression.


259-270: Make edge case test more specific.

The test claims to verify "пустые строки, null значения, некорректные форматы" (empty strings, null values, incorrect formats) but only asserts that diagnostics are not empty, without verifying specific edge case behavior. Consider adding explicit test cases or assertions for each claimed edge case scenario.

📜 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 2762463 and 5db7b11.

⛔ Files ignored due to path filters (2)
  • src/test/resources/diagnostics/MagicDateDiagnostic.bsl is excluded by !src/test/resources/**
  • src/test/resources/diagnostics/MagicNumberDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (8)
  • docs/diagnostics/MagicDate.md (1 hunks)
  • docs/diagnostics/MagicNumber.md (2 hunks)
  • docs/en/diagnostics/MagicDate.md (1 hunks)
  • docs/en/diagnostics/MagicNumber.md (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java (2 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (7 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • docs/diagnostics/MagicDate.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • docs/en/diagnostics/MagicDate.md
  • docs/en/diagnostics/MagicNumber.md
  • docs/diagnostics/MagicNumber.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). (12)
  • GitHub Check: Analyse
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build
  • GitHub Check: Benchmark
🔇 Additional comments (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java (1)

56-68: LGTM!

The helper method is well-implemented, uses the appropriate Trees.getRootParent utility as suggested in past reviews, and is correctly scoped for reuse by diagnostic subclasses.

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

239-257: LGTM! Core feature verification is correct.

This test properly verifies the PR's main objective: suppressing MagicDate diagnostics for structure property assignments while still generating them for simple variable assignments. The use of line-specific assertions clearly demonstrates the expected behavior.

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)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

434-487: Consider adding type verification to structure property assignments.

There's an asymmetry in how structure detection works:

  • isStructureMethodCall (lines 466-487): Verifies the object is actually a Structure type via isVariableOfStructureType before suppressing
  • isStructurePropertyAssignment (lines 434-457): Only checks for accessProperty() without type verification

This means NonStructureObject.Property = "00020101" would be incorrectly suppressed even though the object isn't a Structure.

For consistency and correctness, consider extracting the base object name from the acceptor in isStructurePropertyAssignment and calling isVariableOfStructureType to verify it's actually a Structure, similar to how isStructureMethodCall handles it.

Example approach:

 private static boolean isStructurePropertyAssignment(BSLParser.ExpressionContext expr) {
   if (expr == null) {
     return false;
   }
   
   var assignment = (BSLParser.AssignmentContext) Trees.getRootParent((BSLParserRuleContext) expr, 
     BSLParser.RULE_assignment);
   if (assignment == null) {
     return false;
   }
   
   var lValue = assignment.lValue();
   if (lValue == null || lValue.isEmpty()) {
     return false;
   }
   
   var acceptor = lValue.acceptor();
   if (acceptor == null) {
     return false;
   }
   
   var accessProperty = acceptor.accessProperty();
-  return accessProperty != null;
+  if (accessProperty == null) {
+    return false;
+  }
+  
+  // Extract base object name and verify it's a Structure type
+  String objectName = extractObjectName(acceptor);
+  return objectName != null && isVariableOfStructureType(objectName);
 }

Note: You'll need to make isVariableOfStructureType non-private (protected or package-private) and implement extractObjectName to parse the object identifier from the acceptor context.

📜 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 5db7b11 and 53f5eba.

⛔ Files ignored due to path filters (1)
  • src/test/resources/diagnostics/MagicDateDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (7 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
⏰ 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: Analyse
  • GitHub Check: build
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: Benchmark
🔇 Additional comments (4)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1)

27-336: Excellent test coverage and structure!

The test file demonstrates strong engineering practices:

  • Helper methods (lines 67-96) eliminate duplication and provide clear, reusable assertions
  • Line number constants (lines 40-50) make tests maintainable and self-documenting
  • Comprehensive scenarios: covers configuration, date formats, exclusions, assignments, structure handling, edge cases, and bilingual support
  • Clear documentation: Javadoc comments explain what each test verifies

The test suite thoroughly validates the PR objectives around suppressing diagnostics for structure property assignments while ensuring normal cases still trigger.

src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (3)

47-68: Outstanding documentation!

The class-level Javadoc comprehensively documents:

  • Purpose and behavior
  • Supported date formats
  • Suppression scenarios (structure properties, method calls, returns, etc.)
  • Configuration options

This makes the diagnostic's behavior crystal clear to users and maintainers.


205-218: Well-designed centralized decision logic.

The shouldGenerateDiagnostic method consolidates all suppression checks into a single, testable decision point. This improves maintainability and makes the diagnostic's behavior easier to understand and modify.

The optimization note about minimizing AST tree traversals shows attention to performance.


515-569: Robust structure type detection with graceful fallback.

The implementation demonstrates good engineering:

  • Primary path: Uses SymbolTree for accurate type resolution (lines 528-544)
  • Fallback: Heuristic name-based detection when symbol tree unavailable (lines 554-569)
  • Bilingual support: Handles both Russian and English naming conventions

The heuristic approach is pragmatic—while not perfect, it provides reasonable coverage for common naming patterns when formal type information isn't available.

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)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

514-568: Symbol resolution with sensible heuristic fallback.

The isVariableOfStructureType method correctly prioritizes symbol tree lookup with description analysis, falling back to name-based heuristics when symbol information is unavailable. The heuristic keywords (структура, structure, стр, str, данные, data, параметры, params) are reasonable for typical 1C:Enterprise code patterns.

Note: The heuristic at lines 560-567 could have false positives (e.g., a variable named "строка" would match "стр"), but this trade-off is acceptable given the fallback nature and difficulty of perfect type inference without full semantic analysis.

📜 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 53f5eba and 8aa91eb.

📒 Files selected for processing (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (8 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java (1)
  • DiagnosticMetadata (54-197)
⏰ 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: Analyse
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
🔇 Additional comments (7)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (7)

24-25: VariableSymbol import is correctly used.

Despite a past review comment flagging this import as unused, it's actually required at line 532 where symbolTree.getVariableSymbol() returns Optional<VariableSymbol>. The import should remain.


46-67: Excellent documentation.

The comprehensive JavaDoc clearly explains the diagnostic's purpose, suppression scenarios, and supported date formats. This aligns perfectly with the PR objectives and helps future maintainers understand the intended behavior.


108-147: Robust configuration handling.

The enhanced configuration logic with null checks, empty-string filtering, and date validation (isValidDateString) prevents configuration errors and ensures only valid dates are authorized. This defensive approach improves reliability.


149-193: Excellent refactoring with centralized gating.

Both visitString and visitConstValue now route through shouldGenerateDiagnostic, eliminating code duplication and ensuring consistent suppression logic across all entry points. The flow is clear: validate → get context → gate → report.


195-217: Core fix correctly implemented.

The centralized shouldGenerateDiagnostic method properly implements the PR objective by suppressing diagnostics for structure property assignments and method calls (line 211), while preserving other suppression conditions. The boolean logic is correct: diagnostics are generated only when none of the suppression conditions are met.


225-283: Enhanced date validation is solid.

The improved validation logic correctly handles both date formats (YYYYMMDD and YYYYMMDDHHMMSS), validates component ranges, and aligns with 1C platform limits (year 1-9999). The parseInt helper safely handles leading zeros and exceptions. Note: day validation doesn't enforce month-specific limits (e.g., February 30), but this is acceptable for magic-number detection heuristics.


427-486: Structure detection logic is well-implemented.

The methods correctly identify structure property assignments and method calls:

  • isStructurePropertyAssignment uses AST traversal to detect Obj.Property = value patterns
  • isStructureMethodCall uses the bilingual STRUCTURE_METHOD_PATTERN to match both "Вставить" and "Insert" (case-insensitive)
  • Text parsing in isStructureObjectCall is reasonable given AST constraints

This addresses the PR objective and past review feedback about bilingual support.

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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2)

86-90: Fix paramPattern: excludes valid dates (years starting with 4–9).

The pattern forces the first digit to [0–3], so strings like "99991231" and "40010101" are never checked. This causes false negatives.

Apply:

-  private static final Pattern paramPattern = CaseInsensitivePattern.compile(
-    "\"[0123]{1}\\d{7}\"|\"[0123]{1}\\d{13}\""
-  );
+  private static final Pattern paramPattern = CaseInsensitivePattern.compile(
+    "\"\\d{8}\"|\"\\d{14}\""
+  );

80-82: Remove unsupported 12-digit default date from authorized list.

DEFAULT_AUTHORIZED_DATES includes "000101010000" (12 digits) while supported lengths are 8 or 14; configure() filters it out anyway, creating a misleading default.

-  private static final String DEFAULT_AUTHORIZED_DATES = "00010101,00010101000000,000101010000";
+  private static final String DEFAULT_AUTHORIZED_DATES = "00010101,00010101000000";

Also update docs mentioning supported formats.

♻️ Duplicate comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

433-456: Structure property suppression matches any property; add type check.

isStructurePropertyAssignment() returns true for all property assignments (Obj.Prop = "..."), not only Structure. This suppresses diagnostics in non-Structure contexts.

-  private static boolean isStructurePropertyAssignment(BSLParser.ExpressionContext expr) {
+  private boolean isStructurePropertyAssignment(BSLParser.ExpressionContext expr) {
     if (expr == null) {
       return false;
     }
@@
-    var accessProperty = acceptor.accessProperty();
-    return accessProperty != null;
+    var accessProperty = acceptor.accessProperty();
+    if (accessProperty == null) {
+      return false;
+    }
+    // LHS like Var.Property — verify Var is a Structure
+    String lhs = acceptor.getText();
+    int dot = lhs.indexOf('.');
+    if (dot <= 0) {
+      return false;
+    }
+    String baseName = lhs.substring(0, dot).trim();
+    return isVariableOfStructureType(baseName);
   }

Add a test ensuring non-Structure property assignments (e.g., ОтборЭлемента.ПравоеЗначение = "00020101") still produce diagnostics.

🧹 Nitpick comments (8)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (3)

95-99: Redundant inline (?i) with CaseInsensitivePattern.

CaseInsensitivePattern.compile already sets case-insensitive mode; the embedded "(?i)" is redundant.

-  private static final Pattern STRUCTURE_METHOD_PATTERN = CaseInsensitivePattern.compile(
-    "(?i)Вставить|Insert"
-  );
+  private static final Pattern STRUCTURE_METHOD_PATTERN = CaseInsensitivePattern.compile(
+    "Вставить|Insert"
+  );

313-321: Duplicate expression-mapping helpers; consider unifying.

getExpression(Optional) and getExpressionFromString(StringContext) are identical apart from parameter type.

Extract a single private method accepting BSLParserRuleContext (or a generic mapper) to reduce duplication.

Also applies to: 329-337


404-424: Fragile multi-parent walk; prefer direct AST queries.

The deep parent chain in insideAssignmentWithDateMethodForSimpleDate() is brittle. Use Trees.getRootParent(expr, RULE_assignment) and then inspect the RHS for GlobalMethodCallContext with methodPattern, or traverse with Trees.findFirst(...).

If you want, I can draft a helper that finds a GlobalMethodCallContext under an assignment’s rValue.

src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (5)

195-225: Test intent vs assertions mismatch (return/assignment cases).

Docstrings say “return does NOT generate diagnostics” and “assignment with Date() generates diagnostics,” yet assertions don’t verify absence on return lines and rely on global counts/ranges.

  • Add assertNoDiagnosticOnLine for return lines.
  • For Date() assignment, assert presence on the specific lines; for returns, assert absence.
    If line numbers aren’t constant, assert by message substring or by locating the exact Range from the fixture.

268-276: Weak “isNotEmpty” tests — refactor to focused assertions.

testEdgeCases, testEdgeCasesExtended, and testStringLiterals only check non-empty diagnostics. Replace with targeted expectations (presence/absence on specific lines or counts) or remove to reduce noise.

Also applies to: 338-350, 369-376


324-336: Latin method coverage: also assert non-Structure Insert still reports.

Great that you check DataStructure.Insert. Add a counterexample where Insert is called on a non-Structure to ensure no over-suppression.


131-150: Configuration tests: add assertions that invalid/empty/null authorizedDates don’t break filtering.

Since configure() filters invalid dates, assert that:

  • invalid dates are not included (e.g., "invalid" doesn’t prevent "00020101" from reporting),
  • null/empty reverts to defaults,
  • duplicates are handled (Set semantics).

If helpful, assert the diagnostic count difference before/after configuration.

Also applies to: 382-408, 414-424


247-261: Test coverage incomplete: non-Structure property assignments not verified.

The test method testStructurePropertyAssignment() validates Structure property suppression and simple variable reporting, but lacks explicit coverage for non-Structure object properties (e.g., ОтборЭлемента.ПравоеЗначение = "00020101"). While the current assertions indirectly cover this via SIMPLE_ASSIGNMENT_LINE, adding an explicit assertion for a non-Structure property assignment would strengthen test coverage.

Two approaches:

  1. Extend the fixture to include ОтборЭлемента.ПравоеЗначение = "00020101" and add a corresponding assertion.
  2. Create an alternate fixture using getDiagnostics(String simpleFileName) (supported by the harness).

The current test is functionally adequate but incomplete.

📜 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 8aa91eb and 2269189.

⛔ Files ignored due to path filters (1)
  • src/test/resources/diagnostics/MagicDateDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (8 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
⏰ 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
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: Analyse
🔇 Additional comments (2)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1)

39-47: No off-by-one errors found.

Line constants in the test match the actual fixture exactly (lines 73, 74, 76, 84, 85 for the respective constant values). The original review's concern about off-by-one shifts is incorrect.

Likely an incorrect or invalid review comment.

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

522-544: No changes needed; review comment is based on unavailable APIs.

The VariableSymbol API does not expose type predicates like getType(), typeOf(), or getTypeName(). The available methods are:

  • getKind() → VariableKind (scope: LOCAL, PARAMETER, DYNAMIC, etc.—not value type)
  • getDescription() → Optional (text metadata from comments, no type fields)

The current implementation at lines 522-544 already uses the only viable approach: parsing description text for structure keywords plus name-based heuristics. There are no "actual type predicates" available to replace this logic.

Likely an incorrect or invalid review comment.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2)

86-88: Critical: paramPattern excludes valid dates (years 4000–9999).

"[0123]{1}\\d{7}" and "[0123]{1}\\d{13}" wrongly reject strings starting with 4–9, so "90010101" and "99991231235959" are ignored entirely.

Apply:

-  private static final Pattern paramPattern = CaseInsensitivePattern.compile(
-    "\"[0123]{1}\\d{7}\"|\"[0123]{1}\\d{13}\""
-  );
+  private static final Pattern paramPattern = Pattern.compile(
+    "\"\\d{8}\"|\"\\d{14}\""
+  );

Optionally, drop the pre-filter and rely on isValidDate(String) for correctness.


80-85: Default config includes unsupported 12‑digit date.

DEFAULT_AUTHORIZED_DATES contains 000101010000 (12 digits), but validators accept only 8 or 14 digits. After configure(), this entry is silently discarded, creating inconsistent behavior between defaults and configured state.

Choose one:

  • Align defaults with validators (recommended):
-  private static final String DEFAULT_AUTHORIZED_DATES = "00010101,00010101000000,000101010000";
+  private static final String DEFAULT_AUTHORIZED_DATES = "00010101,00010101000000";
  • Or add 12‑digit support consistently:
    • Allow 12 in isValidDateString and isValidDate (parse HHMM without seconds).
♻️ Duplicate comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

421-444: Over-broad suppression: property assignment matches any object, not only Structure.

accessProperty() != null is true for arbitrary object properties, so diagnostics can be suppressed outside Structures (e.g., Obj.Prop = "00020101"). Re-opened; still present in current code.

Tighten by verifying the base object is a Structure (symbol/type when available; heuristic fallback). Also make the method non-static so it can use documentContext.

-  private static boolean isStructurePropertyAssignment(BSLParser.ExpressionContext expr) {
+  private boolean isStructurePropertyAssignment(BSLParser.ExpressionContext expr) {
     if (expr == null) {
       return false;
     }
@@
-    var accessProperty = acceptor.accessProperty();
-    return accessProperty != null;
+    var accessProperty = acceptor.accessProperty();
+    if (accessProperty == null) {
+      return false;
+    }
+    // Extract base object from "Base.Property[.Sub...]"
+    String acceptorText = acceptor.getText();
+    int dotIdx = acceptorText.indexOf('.');
+    if (dotIdx <= 0) {
+      return false;
+    }
+    String baseName = acceptorText.substring(0, dotIdx).trim();
+    return isVariableOfStructureType(baseName);
   }

Add a test ensuring a non‑Structure property assignment still reports MagicDate. Example (fixture snippet):

ОтборЭлемента.ПравоеЗначение = "00020101"; // should report
🧹 Nitpick comments (4)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2)

453-474: Prefer AST for receiver/method instead of parsing call text.

isStructureMethodCall/isStructureObjectCall parse callText and split on the first '.', which breaks on chains like Obj.Sub.Insert(...) and is locale/format fragile.

  • Extract the receiver from the parser nodes (e.g., member/access nodes) and resolve its type via SymbolTree.
  • Keep the bilingual method check via STRUCTURE_METHOD_PATTERN, but match against the actual method identifier node, not String text. This reduces false positives/negatives in nested expressions.

Also applies to: 483-500


203-216: Duplicate checks for simple date assignment.

insideSimpleDateAssignment(...) ends up delegating to insideAssignmentWithDateMethodForSimpleDate(...), and shouldGenerateDiagnostic(...) evaluates both, duplicating work.

  • Remove isSimpleAssignment from shouldGenerateDiagnostic and rely on isDateMethod, or inline a single helper to avoid repeated AST walks.

Also applies to: 346-359

src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2)

244-255: Add negative check: non‑Structure property assignment must still report.

Great that structure property/method cases are suppressed. Add an explicit non‑Structure property assignment in the fixture and assert that it DOES produce a diagnostic to guard against over-broad suppression.

Example to add to fixture:

ОбъектНеСтруктура.Свойство = "00020101"; // should report

Then assert presence on that line.


318-340: Consolidate superficial “isNotEmpty” tests or make them assertive.

Several tests only assert isNotEmpty(). Either merge them into one sanity test or add precise expectations (ranges/lines) to increase value.

📜 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 2269189 and e88f2f9.

⛔ Files ignored due to path filters (1)
  • src/test/resources/diagnostics/MagicDateDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (8 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java (1)
  • DiagnosticMetadata (54-197)
⏰ 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 (17, macOS-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build
  • GitHub Check: Analyse
🔇 Additional comments (2)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2)

39-47: Fix off-by-one error in SIMPLE_ASSIGNMENT_LINE constant; verify Latin constants manually.

Based on fixture inspection:

  • SIMPLE_ASSIGNMENT_LINE = 76 is off-by-one; the actual assignment ПростаяПеременная = "00040101"; is on line 77, not 76.
  • STRUCTURE_INSERT_LINE, STRUCTURE_PROPERTY_LINE, STRUCTURE2_INSERT_LINE, and STRUCTURE2_PROPERTY_LINE constants are correct.
  • Please confirm LATIN_INSERT_LINE = 93 and LATIN_INSERT_CYRILLIC_LINE = 94 against the fixture file, as the Latin section in the fixture begins after line 107.

128-147: Incorrect premise about the map mutation concern.

The review comment states that getDefaultConfiguration() "may return a shared map," but this is inaccurate. The method creates a new Map on each invocation via Collectors.toMap() in DiagnosticInfo.java line 272-274, so mutations to the local configuration variable in testConfigure() do not leak through that mechanism.

However, there is a legitimate test isolation concern: MagicDateDiagnosticTest lacks @DirtiesContext while many peer diagnostic test classes in the codebase explicitly use it (e.g., MetadataObjectNameLengthDiagnosticTest, TimeoutsInExternalResourcesDiagnosticTest). The real risk is that diagnosticInstance state mutations in testConfigure() could affect subsequent test methods if the bean is reused across the test context. The appropriate fix would be to add @DirtiesContext at the class level, consistent with other diagnostic tests, rather than wrapping the configuration map.

Likely an incorrect or invalid review comment.

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/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2)

257-440: Many test methods only assert isNotEmpty() without verifying specific behavior.

Several test methods (testEdgeCases, testEdgeCasesExtended, testStringLiterals, testVisitStringMethod, testInvalidDateFormats, testStructureMethodCallEdgeCases, testSymbolResolutionEdgeCases) only call getDiagnostics() and assert isNotEmpty(). These don't verify specific edge cases or behavior—they're essentially duplicates of the main test.

Consider either removing these or refactoring them to assert specific scenarios (e.g., specific input patterns, expected diagnostic locations, or configuration behaviors). Tests should validate distinct behavior rather than repeat generic checks.


272-396: Minor test duplication: null configuration tested twice.

Both testInvalidConfiguration (line 280) and testNullConfiguration (lines 372-381) test the null configuration scenario. Consider consolidating related configuration tests to reduce duplication.

📜 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 e88f2f9 and 78fbf77.

📒 Files selected for processing (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java (2 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (8 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
⏰ 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: Analyse
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build
🔇 Additional comments (11)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java (1)

55-64: LGTM! Helper method correctly extracts shared AST traversal logic.

The findAssignmentContext helper properly uses Trees.getRootParent to locate the assignment context, eliminating duplication between MagicDateDiagnostic and MagicNumberDiagnostic. The protected static visibility makes it accessible to diagnostic subclasses.

Based on past review comments

src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2)

49-93: LGTM! Helper methods improve test readability.

The three helper methods (hasDiagnosticOnLine, assertNoDiagnosticOnLine, assertHasDiagnosticOnLine) provide clear, reusable utilities for verifying diagnostic presence on specific lines. Good Javadoc documentation.


244-255: LGTM! Test correctly verifies structure property assignment suppression.

The test properly validates the PR's core feature: diagnostics are suppressed for structure property assignments (Структура.Вставить, Структура.СвойствоДаты) but still fire for simple variable assignments. Good use of helper methods for clear assertions.

src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (8)

46-67: LGTM! Comprehensive class documentation.

The Javadoc clearly documents when the diagnostic is suppressed (structure property assignments, structure method calls, simple date assignments, returns, authorized dates) and lists supported date formats. This helps users understand the diagnostic's behavior.


107-132: LGTM! Enhanced configuration handling with proper validation.

The configure method now includes null checks, validates date strings with isValidDateString, and filters out invalid entries. This prevents configuration errors from breaking the diagnostic.


194-216: LGTM! Centralized suppression logic.

The shouldGenerateDiagnostic method consolidates all suppression checks in one place, making the logic clear and maintainable. Properly checks for structure property assignments, structure method calls, returns, and date method assignments.


233-267: LGTM! Date validation with correct bounds.

The validation properly uses MAX_YEAR_BY_1C constant for year bounds and strict inequalities for time components (hh < 24, mm < 60, ss < 60). Handles both 8-digit (date only) and 14-digit (date+time) formats correctly.


446-474: LGTM! Bilingual structure method detection with type checking.

The method now uses STRUCTURE_METHOD_PATTERN to match both Вставить and Insert (case-insensitive), and delegates to isStructureObjectCall for proper type verification via the symbol tree. This addresses previous concerns about language limitations and over-broad suppression.

Based on past review comments


502-530: LGTM! Symbol tree-based type detection with safe fallback.

The method properly uses SymbolTree to resolve variable types and checks the description for structure indicators. Returns false if the symbol tree is unavailable or the variable isn't found, which is a safe default that avoids false suppression.


338-359: LGTM! Refactored to use AST-based detection.

The method now properly delegates to insideAssignmentWithDateMethodForSimpleDate for precise AST-based checking, eliminating the previous text-based heuristic that caused false positives. Correctly excludes structure property assignments and method calls first.

Based on past review comments


414-444: Property assignment suppression remains over-broad without type checking.

The method suppresses diagnostics for any property assignment (e.g., Obj.Property = "00020101") without verifying that Obj is actually a Structure. While isVariableOfStructureType exists (line 510) and is correctly used in isStructureObjectCall for method calls, it is not used in isStructurePropertyAssignment for property assignments.

This means property assignments to non-Structure objects—or even undefined variables like ОтборЭлемента.ПравоеЗначение on line 32—are also suppressed, creating an asymmetry with method call handling. Either add type checking to isStructurePropertyAssignment similar to isStructureObjectCall, or document why all property assignments are intentionally suppressed.

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

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/diagnostics/MagicDateDiagnostic.java (1)

80-81: Remove the unsupported 12-digit value from DEFAULT_AUTHORIZED_DATES.

The constant includes "000101010000" (12 digits), but the isValidDateString method only accepts 8 or 14 digit strings (line 141). During configuration, this 12-digit value is silently filtered out (lines 124–131), contradicting the documented supported formats. Remove the 12-digit value to eliminate the confusing inconsistency:

-  private static final String DEFAULT_AUTHORIZED_DATES = "00010101,00010101000000,000101010000";
+  private static final String DEFAULT_AUTHORIZED_DATES = "00010101,00010101000000";
♻️ Duplicate comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

417-440: Over-broad suppression: property assignment without Structure type check.

isStructurePropertyAssignment() suppresses diagnostics for any property assignment, not only Structure properties. This masks cases like Obj.Date = "20250101". Add a Structure-type check using the base identifier of the lValue, consistent with isStructureMethodCall/isVariableOfStructureType.

Apply:

   private static boolean isStructurePropertyAssignment(BSLParser.ExpressionContext expr) {
@@
-    var accessProperty = acceptor.accessProperty();
-    return accessProperty != null;
+    var accessProperty = acceptor.accessProperty();
+    if (accessProperty == null) {
+      return false;
+    }
+    // Verify base object is Structure: <Base>.<Property> = ...
+    var lValueText = lValue.getText();
+    int dot = lValueText.indexOf('.');
+    if (dot <= 0) {
+      return false;
+    }
+    var objectName = lValueText.substring(0, dot);
+    // Delegate to existing resolver
+    return new MagicDateDiagnostic().isVariableOfStructureType(objectName);
   }

Note: if calling a non-static method from static context is undesired, move isVariableOfStructureType to static or a shared util.

🧹 Nitpick comments (5)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (3)

199-212: Redundant checks: isSimpleAssignment duplicates isDateMethod.

insideSimpleDateAssignment now delegates to insideAssignmentWithDateMethodForSimpleDate; you also compute isDateMethod. Drop one to reduce AST traversals.

-    boolean isDateMethod = insideAssignmentWithDateMethodForSimpleDate(expressionContext);
-    boolean isSimpleAssignment = insideSimpleDateAssignment(expressionContext);
-    
-    return !isStructureProperty && !isReturn && !isDateMethod && !isSimpleAssignment;
+    boolean isDateMethod = insideAssignmentWithDateMethodForSimpleDate(expressionContext);
+    return !isStructureProperty && !isReturn && !isDateMethod;

Optionally remove insideSimpleDateAssignment if no longer used.


388-408: Deep parent-walk is brittle; prefer Trees.getRootParent.

insideAssignmentWithDateMethodForSimpleDate chains multiple parent hops. Use Trees.getRootParent to reach GlobalMethodCall and Assignment for clarity and resilience.

-  return expression
-      .map(BSLParserRuleContext::getParent)
-      .filter(context -> context.getChildCount() == 1)
-      .map(BSLParserRuleContext::getParent)
-      .filter(context -> context.getChildCount() == 1)
-      .map(BSLParserRuleContext::getParent)
-      .map(BSLParserRuleContext::getParent)
-      .filter(BSLParser.GlobalMethodCallContext.class::isInstance)
-      .map(BSLParser.GlobalMethodCallContext.class::cast)
-      .filter(context -> methodPattern.matcher(context.methodName().getText()).matches())
-      .map(BSLParserRuleContext::getParent)
-      .filter(context -> context.getChildCount() == 1)
-      .map(BSLParserRuleContext::getParent)
-      .filter(context -> context.getChildCount() == 1)
-      .map(BSLParserRuleContext::getParent)
-      .filter(context -> context.getChildCount() == 1)
-      .map(BSLParserRuleContext::getParent)
-      .filter(BSLParser.AssignmentContext.class::isInstance)
-      .isPresent();
+  return expression
+      .map(expr -> (BSLParser.GlobalMethodCallContext)
+          Trees.getRootParent((BSLParserRuleContext) expr, BSLParser.RULE_globalMethodCall))
+      .filter(ctx -> methodPattern.matcher(ctx.methodName().getText()).matches())
+      .map(ctx -> Trees.getRootParent(ctx, BSLParser.RULE_assignment))
+      .filter(BSLParser.AssignmentContext.class::isInstance)
+      .isPresent();

324-332: Duplicate expression-extraction helpers.

getExpressionFromString duplicates getExpression logic. Consider extracting a common helper accepting BSLParserRuleContext and reusing it.

Also applies to: 308-316

src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2)

95-122: Brittle golden-count and dense range assertions.

Hard-coding hasSize(40) and many ranges ties tests to fixture editing. Prefer focused scenario tests: assert on specific lines of interest (helpers already exist) and avoid global counts.


257-266: Superficial tests asserting only non-empty diagnostics.

Several tests only check isNotEmpty(), adding little value and increasing noise. Consolidate or rewrite to assert precise suppression/triggering for specific lines.

Also applies to: 318-327, 402-407, 414-418, 425-429, 436-440

📜 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 78fbf77 and 3f10d92.

⛔ Files ignored due to path filters (2)
  • src/test/resources/diagnostics/MagicDateDiagnostic.bsl is excluded by !src/test/resources/**
  • src/test/resources/diagnostics/MagicNumberDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (8 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionOutParameterDiagnostic.java (1)
  • DiagnosticMetadata (41-87)
⏰ 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: Analyse
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build
🔇 Additional comments (2)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2)

128-147: Configured authorizedDates include unsupported 12-digit format.

testConfigure passes "000101010000" (12 digits), which the validator now rejects. Align the test with supported formats or extend validation to include 12-digit DATETIME.


39-48: The proposed changes in the review comment are incorrect and should not be applied.

The constants STRUCTURE_INSERT_LINE, STRUCTURE_PROPERTY_LINE, STRUCTURE2_INSERT_LINE, and STRUCTURE2_PROPERTY_LINE are all correct as currently written. The fixture file confirms:

  • Line 73: Структура.Вставить()
  • Line 74: Структура.СвойствоДаты =
  • Line 84: ПеремСтрДаты.Вставить()
  • Line 85: ПеремСтрДаты.СвойствоДаты =

However, there are actual line number errors elsewhere:

  • SIMPLE_ASSIGNMENT_LINE = 76 should be 77 (fixture line 77 has the magic date assignment)
  • LATIN_INSERT_LINE = 93 should be 111 (fixture line 111 has DataStructure.Insert())
  • LATIN_INSERT_CYRILLIC_LINE = 94 should be 112 (fixture line 112 has the Cyrillic version)

Likely an incorrect or invalid review comment.

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 (2)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1)

322-327: Consider strengthening assertions in edge-case and coverage tests.

Several test methods (testEdgeCasesExtended, testStringLiterals, testInvalidDateFormats, testStructureMethodCallEdgeCases, testSymbolResolutionEdgeCases) only assert isNotEmpty() without verifying specific behavior or diagnostic locations.

While these may improve code coverage metrics, they don't validate correctness. Consider either:

  1. Adding specific assertions about which lines should/shouldn't have diagnostics
  2. Consolidating these into a single smoke test if they're just ensuring no crashes

Also applies to: 346-351, 403-420, 426-431

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

383-406: Consider adding type validation for property assignments.

The method suppresses diagnostics for any property assignment (e.g., Obj.Date = "00020101"), regardless of whether Obj is actually a Structure type. While isStructureMethodCall() validates types via isVariableOfStructureType(), property assignments lack this check.

This broader suppression may be acceptable if the semantic context of any property name is deemed sufficient, but for consistency with the PR objective ("при присваивании значений к свойствам структуры"), consider using isVariableOfStructureType() to validate the base object type.

📜 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 3f10d92 and 9aee875.

⛔ Files ignored due to path filters (1)
  • src/test/resources/diagnostics/MagicDateDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (8 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
⏰ 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
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: Analyse
🔇 Additional comments (8)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1)

64-93: LGTM: Well-structured test helpers.

The helper methods provide clear, focused assertions for checking diagnostics on specific lines. The use of descriptive error messages improves test failure diagnostics.

src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (7)

46-67: Excellent documentation.

The Javadoc clearly describes the diagnostic's purpose, suppression contexts, and supported date formats. This will help users understand when false positives are expected vs. real issues.


86-97: LGTM: Patterns correctly support validation and bilingual detection.

The paramPattern now accepts any 8- or 14-digit date (delegating validation to isValidDate()), and STRUCTURE_METHOD_PATTERN properly handles both Russian and English method names case-insensitively.


107-132: LGTM: Robust configuration handling.

The method properly handles null configuration, validates date strings, and filters invalid entries. The defensive programming approach prevents configuration errors from causing runtime issues.


180-193: LGTM: Centralized suppression logic improves maintainability.

The shouldGenerateDiagnostic() method consolidates all suppression conditions in one place, making the logic transparent and reducing the risk of inconsistent checks across different code paths.


216-244: LGTM: Date validation is now correct.

The validation properly uses MAX_YEAR_BY_1C constant, enforces strict time component bounds (< 24/60/60), and handles both 8- and 14-digit date formats correctly.


300-321: LGTM: Precise AST-based detection.

The method correctly delegates to insideAssignmentWithDateMethodForSimpleDate() for accurate detection, and explicitly excludes structure-related contexts to avoid false suppressions.


415-494: LGTM: Robust structure method validation with type checking.

The implementation properly:

  • Detects structure method calls bilingually via pattern matching
  • Extracts the base object identifier
  • Uses SymbolTree to resolve and validate the variable is actually a Structure type
  • Handles null cases defensively throughout

This precise type checking reduces false positives effectively.

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 (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

458-487: Consider adding type verification for consistency with method call checking.

The method isStructurePropertyAssignment() suppresses diagnostics for ANY property assignment (e.g., Object.Property = value) without verifying the object is actually a Structure type. In contrast, isStructureMethodCall() (lines 500-597) uses isVariableOfStructureType() to verify the object type via symbol tree before suppressing.

This inconsistency could lead to over-broad suppression. For example, ОтборЭлемента.ПравоеЗначение = "00020101" would be suppressed even if ОтборЭлемента is not a Structure.

Suggestion: Add type verification similar to isStructureMethodCall():

 private static boolean isStructurePropertyAssignment(BSLParser.ExpressionContext expr) {
   if (expr == null) {
     return false;
   }
   
   var assignment = getRootParent(expr, BSLParser.RULE_assignment);
   if (!(assignment instanceof BSLParser.AssignmentContext)) {
     return false;
   }
   
   var assignmentContext = (BSLParser.AssignmentContext) assignment;
   var lValue = assignmentContext.lValue();
   if (lValue == null || lValue.isEmpty()) {
     return false;
   }
   
   var acceptor = lValue.acceptor();
   if (acceptor == null) {
     return false;
   }
   
   var accessProperty = acceptor.accessProperty();
-  return accessProperty != null;
+  if (accessProperty == null) {
+    return false;
+  }
+  
+  // Extract object name and verify it's a Structure type
+  String objectName = acceptor.getText();
+  if (objectName != null) {
+    int dotIndex = objectName.indexOf('.');
+    if (dotIndex > 0) {
+      objectName = objectName.substring(0, dotIndex);
+      return isVariableOfStructureType(objectName);
+    }
+  }
+  return false;
 }

Note: This would require making isVariableOfStructureType() accessible (currently it requires documentContext, so the method signature would need adjustment).

Alternatively, if the intent is to suppress diagnostics for ALL property assignments (not just structures), consider renaming the method to isAnyPropertyAssignment() to reflect its actual behavior.

📜 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 9aee875 and 7c807eb.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (6 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-04-18T22:46:43.245Z
Learnt from: nixel2007
PR: 1c-syntax/bsl-language-server#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/MagicDateDiagnostic.java
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java (1)
  • DiagnosticMetadata (54-197)
⏰ 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
  • GitHub Check: Analyse
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
🔇 Additional comments (10)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (3)

27-93: LGTM! Well-structured test infrastructure.

The helper methods and constants significantly improve test readability and maintainability. The Collections import is correctly used at line 274.


95-255: Excellent test coverage for core functionality.

The tests properly verify:

  • Structure property assignments are suppressed (lines 248-252)
  • Structure method calls (Insert/Вставить) are suppressed (lines 248, 251)
  • Simple variable assignments still generate diagnostics (line 254)

This aligns perfectly with the PR objectives.


257-431: Comprehensive edge case coverage.

The tests effectively cover:

  • Bilingual method support (Вставить/Insert)
  • Invalid/null/empty configurations
  • Different structure variable names
  • Symbol resolution scenarios
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (7)

24-31: LGTM! All imports are properly used.

The imports for SymbolTree, VariableSymbol, and Trees are correctly utilized in the type resolution logic.


45-108: Excellent documentation and bilingual pattern support.

The Javadoc clearly documents suppression contexts, and the updated paramPattern correctly allows all valid 1C years (1-9999). The bilingual STRUCTURE_METHOD_PATTERN properly supports both Russian and English code.


116-151: Robust configuration validation.

The null guards and isValidDateString() filtering ensure the diagnostic handles invalid configurations gracefully.


154-220: Well-architected central diagnostic logic.

The shouldGenerateDiagnostic() method effectively centralizes suppression logic, making the code more maintainable and reducing duplication between visitConstValue() and visitString().


243-286: Date validation logic is correct.

The time bounds correctly allow 0-23 hours, 0-59 minutes, and 0-59 seconds. The parseInt() method safely handles leading zeros and invalid inputs.


362-455: AST navigation logic is well-implemented.

The refactored insideSimpleDateAssignment() correctly delegates to AST-based checking, avoiding the text-based false positives mentioned in past reviews. The navigateToParent() helper provides safe traversal with proper null checks.


500-597: Excellent implementation with proper type verification.

The structure method call detection correctly:

  • Uses symbol tree resolution to verify object types
  • Supports bilingual method names (Вставить/Insert)
  • Handles edge cases with comprehensive null checks
  • Gracefully degrades when symbol information is unavailable

This implementation properly addresses past review feedback about over-broad suppression.

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 (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1)

257-266: Consider adding specific assertions to edge case tests.

Several test methods (testEdgeCases, testEdgeCasesExtended, testStringLiterals, testStructureMethodCallEdgeCases, testSymbolResolutionEdgeCases) only assert that diagnostics are not empty without verifying specific behavior.

Consider enhancing these tests with targeted assertions that verify the actual edge cases they claim to test (e.g., specific line numbers, expected diagnostic messages, or absence of diagnostics in certain scenarios).

Also applies to: 318-327, 342-351, 410-420, 422-431

📜 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 7c807eb and 8a7f27c.

⛔ Files ignored due to path filters (2)
  • src/test/resources/diagnostics/MagicDateDiagnostic.bsl is excluded by !src/test/resources/**
  • src/test/resources/diagnostics/MagicNumberDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (8)
  • docs/diagnostics/MagicDate.md (1 hunks)
  • docs/diagnostics/MagicNumber.md (2 hunks)
  • docs/en/diagnostics/MagicDate.md (1 hunks)
  • docs/en/diagnostics/MagicNumber.md (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java (2 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (6 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java
  • docs/diagnostics/MagicDate.md
  • docs/diagnostics/MagicNumber.md
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-04-18T22:46:43.245Z
Learnt from: nixel2007
PR: 1c-syntax/bsl-language-server#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/MagicDateDiagnostic.java
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java (1)
  • DiagnosticMetadata (54-197)
⏰ 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: Analyse
  • GitHub Check: build
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, macOS-latest)
🔇 Additional comments (6)
docs/en/diagnostics/MagicNumber.md (1)

33-56: LGTM! Clear documentation of exception cases.

The new "Exceptions" section effectively documents when the diagnostic is suppressed for structure property assignments and method calls. The examples are clear and align with the PR objectives.

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

38-60: LGTM! Consistent documentation with clear examples.

The "Exceptions" section mirrors the MagicNumber documentation structure and provides clear examples specific to date literals. Well done.

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

55-64: LGTM! Good refactoring to eliminate duplication.

Extracting the findAssignmentContext helper to the base class is the right approach. The method is correctly implemented using Trees.getRootParent and will be shared by both MagicNumber and MagicDate diagnostics.

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

45-66: Excellent refactoring with centralized suppression logic.

The comprehensive Javadoc (lines 45-66) clearly documents the diagnostic's purpose and exception cases. The shouldGenerateDiagnostic method (lines 200-220) nicely centralizes all suppression checks in one place, making the logic easy to understand and maintain. The implementation successfully addresses the PR objectives of suppressing false positives for structure property assignments.

Also applies to: 200-220


567-597: No issues found with the double .getDescription() call—it's correct API usage.

The chain is intentional: VariableSymbol.getDescription() returns Optional<VariableDescription>, and the inner .map(description -> description.getDescription()) calls the SourceDefinedSymbolDescription.getDescription() method (which returns String) on each VariableDescription object. This is proper Optional chaining.

The type-checking logic via SymbolTree is sound and properly prevents false positives.

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

240-255: LGTM! Well-structured test for the core feature.

The testStructurePropertyAssignment method effectively verifies the PR's main objective: suppressing diagnostics for structure property assignments while still triggering for simple variable assignments. The helper methods provide clear, descriptive assertions.

@nixel2007
Copy link
Member

@johnnyshut можешь над кавереджом в magic date поработать? Такое чувство, что visit String больше не вызывается, все обрабатывается на уровне visitConstValue с ранним возвратом.

@johnnyshut
Copy link
Contributor Author

@johnnyshut можешь над кавереджом в magic date поработать? Такое чувство, что visit String больше не вызывается, все обрабатывается на уровне visitConstValue с ранним возвратом.

Да, Ты прав, хочу убрать лишнее и тесты плохо сделал

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

♻️ Duplicate comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

25-25: Remove unused VariableSymbol import.

The VariableSymbol import is not referenced anywhere in the file. Despite being marked as addressed in previous reviews, it remains unused—getVariableSymbol() at line 478 returns Optional<VariableSymbol> but the type is never explicitly referenced in this file.

Apply this diff:

-import com.github._1c_syntax.bsl.languageserver.context.symbol.VariableSymbol;
🧹 Nitpick comments (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1)

276-280: Consider strengthening testStructureWithMetadata.

The test currently only asserts diagnostics is not null, which is a minimal check that doesn't verify any specific behavior related to structure metadata. Consider either:

  1. Adding assertions that verify diagnostic behavior when structures lack metadata (e.g., whether diagnostics are generated or suppressed), or
  2. Removing the test if it's a placeholder

Example enhancement:

 @Test
 void testStructureWithMetadata() {
   List<Diagnostic> diagnostics = getDiagnostics();
-  assertThat(diagnostics).isNotNull();
+  // When structure metadata is missing, diagnostics should still be generated for non-structure contexts
+  assertThat(diagnostics).hasSize(49);
+  // Or verify specific line behavior:
+  // assertHasDiagnosticOnLine(diagnostics, <line_with_undefined_structure>, "Undefined structure variable");
 }
📜 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 7f751b5 and fa015ef.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (5 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 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/MagicDateDiagnostic.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/MagicDateDiagnostic.java
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java (1)
  • DiagnosticMetadata (54-197)
⏰ 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, macOS-latest)
  • GitHub Check: build (25, windows-latest)
  • GitHub Check: build (25, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (25, ubuntu-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build
  • GitHub Check: Analyse
🔇 Additional comments (11)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (5)

116-140: LGTM! Robust configuration handling.

The null checks and validation via isValidDateString ensure the diagnostic handles edge cases gracefully. The fallback to DEFAULT_AUTHORIZED_DATES when the config is empty or null is correct.


191-202: LGTM! Clear decision logic.

The method correctly consolidates all suppression checks and returns true (generate diagnostic) only when none of the exception contexts apply. The null check provides a safe default.


363-375: LGTM! Defensive AST navigation.

The null checks and child-count validation ensure safe traversal through the parse tree. This prevents NPE and enforces the expected single-child path constraint.


160-183: LGTM! Clean separation of validation and decision logic.

The refactored visitConstValue clearly separates format validation from the diagnostic decision, delegating to shouldGenerateDiagnostic. This improves maintainability and testability.


475-490: Verify variable resolution scope and document intent.

The scope limitation is confirmed: isVariableOfStructureType receives only the variable name string and must use module-level scope via symbolTree.getModule() (line 478). This means structure variables declared within local procedures or functions cannot be resolved, relying instead on the fallback heuristic check for "структура" or "structure" in the variable's description.

The ExpressionContext is available at the entry point (isStructureMethodCall line 422) but is converted to text and lost by the time scope resolution occurs. If intentional, add a comment explaining that only module-level structure assignments are suppressed. If not intentional, thread the ExpressionContext through the call chain and use SymbolTree.getMethodSymbol() or equivalent to resolve the proper scope.

src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (6)

27-27: LGTM! Collections import is correctly used.

The import is utilized in testConfigurationEdgeCases at line 219 for creating an empty configuration map.


71-100: LGTM! Well-designed test helpers.

The helper methods hasDiagnosticOnLine, assertNoDiagnosticOnLine, and assertHasDiagnosticOnLine provide clear, reusable utilities for line-specific diagnostic assertions with descriptive error messages. This improves test maintainability.


106-129: LGTM! Comprehensive baseline test.

The test establishes a baseline of 49 diagnostics and verifies specific ranges. This ensures the diagnostic behavior is stable across changes.


135-154: LGTM! Tests configuration with edge cases.

The test verifies that authorized dates correctly suppress diagnostics (49 → 26) and that the configuration parser handles whitespace and empty strings robustly.


171-182: LGTM! Comprehensive structure suppression test.

The test verifies the PR's core feature—suppressing diagnostics for structure property assignments and method calls—including bilingual support (Insert vs Вставить). The assertions clearly demonstrate the expected suppression behavior.


217-243: LGTM! Thorough edge case coverage.

The test validates configuration handling for empty maps, null configuration, empty/null authorizedDates string, and mixed valid/invalid dates. The assertions confirm the diagnostic maintains stable behavior (49 diagnostics) and correctly applies valid dates from mixed input.

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 (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

210-230: Consider adding explicit lower bound checks for time components.

While parseInt returns 0 on error (preventing negative values), adding explicit >= 0 checks for hh, mm, and ss would make the validation more defensive and self-documenting:

-    return hh <= MAX_HOUR && mm <= MAX_MINUTE && ss <= MAX_SECOND;
+    return (hh >= 0 && hh <= MAX_HOUR) && (mm >= 0 && mm <= MAX_MINUTE) && (ss >= 0 && ss <= MAX_SECOND);
📜 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 b27887f and c3f388d.

📒 Files selected for processing (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (5 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 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/MagicDateDiagnostic.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/MagicDateDiagnostic.java
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java (1)
  • DiagnosticMetadata (54-197)
⏰ 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
  • GitHub Check: Analyse
  • GitHub Check: build (25, ubuntu-latest)
  • GitHub Check: build (25, macOS-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (25, windows-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
🔇 Additional comments (6)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (6)

45-66: LGTM! Excellent documentation.

The comprehensive Javadoc clearly explains the diagnostic purpose, supported formats, and suppression contexts. This aligns perfectly with the PR objective to document when diagnostics should not fire for structure-related operations.


94-108: LGTM! Well-structured constants.

The bilingual structure method pattern and date validation constants improve code maintainability and address the bilingual support requirement from past reviews.


122-140: LGTM! Robust configuration handling.

The null checks and validation filtering ensure that only valid date strings are accepted during configuration, preventing runtime issues from malformed config.


160-202: LGTM! Clean validation and decision logic.

The visitor correctly validates string dates and delegates the suppression decision to shouldGenerateDiagnostic, which properly implements the PR's objective to skip diagnostics for structure property assignments and method calls.


292-367: LGTM! Well-structured context detection.

The context checking methods correctly identify structure-related contexts and exclude them from diagnostics. The navigateToParent helper provides defensive AST traversal by validating single-child nodes at each level, ensuring we're in the expected syntactic context.


376-478: LGTM! Comprehensive structure detection.

The structure detection logic correctly:

  • Identifies structure property assignments via AST analysis
  • Validates structure method calls using bilingual pattern matching
  • Resolves variable types via SymbolTree with heuristic description checking

The implementation properly addresses the PR objective to suppress false positives for structure-related operations.

…nostic

- Добавлен метод для поиска контекста назначения в AbstractVisitorDiagnostic.
- Улучшен MagicDateDiagnostic для лучшей обработки проверки даты и контекста.
- Введены новые служебные методы для проверки назначения свойств структуры и вызова методов.
- Улучшена обработка конфигурации для авторизованных дат и добавлена ​​проверка строк даты.
- Обновлена ​​логика диагностики для предотвращения ложных срабатываний в определенных контекстах.
- Добавлены новые тесты для проверки различных сценариев обнаружения магических дат и их подавления.
- Реализованы проверки для невалидных форматов дат и граничных значений.
- Улучшена конфигурация диагностики с учетом пустых и некорректных значений.
- Включены тесты для проверки работы с авторизованными датами и структурными присваиваниями.
…umber

- Включены новые разделы "Исключения" в документацию для диагностики магических дат и чисел.
- Описаны случаи, когда диагностика не срабатывает, включая присваивание к свойствам структур и вызовы методов.
- Обновлены примеры кода для лучшего понимания исключений.
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 (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1)

277-280: Strengthen test to verify the claimed behavior.

The Javadoc states this test verifies that variables without structure metadata generate diagnostics, but the implementation only asserts the diagnostics collection is not null (which is always true). This doesn't validate the specific scenario.

Consider adding assertions that verify:

  • Specific lines with non-structure variables DO generate diagnostics
  • Lines with properly-typed structure variables do NOT generate diagnostics
📜 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 c3f388d and 848d374.

⛔ Files ignored due to path filters (2)
  • src/test/resources/diagnostics/MagicDateDiagnostic.bsl is excluded by !src/test/resources/**
  • src/test/resources/diagnostics/MagicNumberDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (8)
  • docs/diagnostics/MagicDate.md (3 hunks)
  • docs/diagnostics/MagicNumber.md (2 hunks)
  • docs/en/diagnostics/MagicDate.md (2 hunks)
  • docs/en/diagnostics/MagicNumber.md (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java (2 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (4 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • docs/en/diagnostics/MagicDate.md
  • docs/en/diagnostics/MagicNumber.md
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java
  • docs/diagnostics/MagicDate.md
  • docs/diagnostics/MagicNumber.md
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-10-27T08:05:10.072Z
Learnt from: theshadowco
Repo: 1c-syntax/bsl-language-server PR: 3555
File: src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java:163-166
Timestamp: 2025-10-27T08:05:10.072Z
Learning: В проекте bsl-language-server используется собственная версия ANTLR4, в которой интерфейс TerminalNode переопределяет метод getParent() с возвращаемым типом RuleNode вместо ParseTree (как в стандартной версии ANTLR4).

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.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/AbstractVisitorDiagnostic.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.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/MagicDateDiagnostic.java
🧬 Code graph analysis (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)
  • DiagnosticMetadata (40-164)
⏰ 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: Analyse
  • GitHub Check: build
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (25, ubuntu-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (25, macOS-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (25, windows-latest)
  • GitHub Check: build (17, macOS-latest)
🔇 Additional comments (8)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java (1)

55-64: LGTM! Clean extraction of shared helper.

The findAssignmentContext helper is properly extracted to the base class, eliminating duplication previously present in MagicDateDiagnostic and MagicNumberDiagnostic. The implementation correctly uses Trees.getRootParent as suggested in past review discussions.

src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2)

71-100: LGTM! Well-structured test helpers.

The three helper methods (hasDiagnosticOnLine, assertNoDiagnosticOnLine, assertHasDiagnosticOnLine) effectively reduce duplication across test methods and provide clear, descriptive error messages. The 0-based line number convention is properly documented.


218-243: LGTM! Comprehensive configuration edge case testing.

The test properly validates handling of null, empty, and invalid configurations, ensuring the diagnostic gracefully falls back to defaults and filters invalid date strings from the authorized list.

src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (5)

120-144: LGTM! Robust configuration handling.

The configure method now properly guards against null and empty configurations with appropriate fallbacks. The addition of isValidDateString filtering ensures only valid date formats enter the authorized list.


195-206: LGTM! Central suppression logic correctly implements PR objectives.

The shouldGenerateDiagnostic method properly coordinates all four suppression contexts:

  1. Structure property assignments
  2. Structure method calls (Вставить/Insert)
  3. Return statements
  4. Date method assignments

The logic correctly generates diagnostics UNLESS the expression falls into one of these exception cases, directly addressing the false-positive issues described in issue #3496.


467-482: LGTM! Proper structure type validation via symbol resolution.

The isVariableOfStructureType method correctly addresses the past review concern about over-broad suppression by:

  • Using SymbolTree to resolve variable types
  • Checking for "структура"/"structure" in the variable description (bilingual support)
  • Using Locale.ROOT for safe case-insensitive comparison
  • Returning false conservatively when symbol or description is absent

This ensures only actual Structure-typed variables suppress diagnostics, preventing false negatives.


359-371: LGTM! Safe AST navigation helper.

The navigateToParent method provides careful upward traversal with proper null guards and single-child path validation. The getChildCount() != 1 check ensures the navigation stays on the expected path through the AST, preventing incorrect matches.


45-66: Excellent documentation of diagnostic behavior.

The enhanced class Javadoc clearly describes:

  • The diagnostic's purpose
  • Supported date formats (YYYYMMDD, YYYYMMDDHHMMSS)
  • All suppression contexts (structure properties, structure methods, returns, date assignments, authorized dates)

This comprehensive documentation helps users understand exactly when the diagnostic will and won't fire, which is critical for a diagnostic targeting false positives.

@johnnyshut
Copy link
Contributor Author

@nixel2007 готово, посмотри, пожалуйста

…stic

- Удален неиспользуемый оператор импорта для SymbolTree в MagicDateDiagnostic.java для очистки кода и улучшения читаемости.
…icDateDiagnostic и MagicNumberDiagnostic

- Перемещен метод findAssignmentContext из AbstractVisitorDiagnostic в MagicDateDiagnostic и MagicNumberDiagnostic для улучшения инкапсуляции и упрощения кода.
- Удалены неиспользуемые импорты и комментарии в AbstractVisitorDiagnostic для повышения читаемости.
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

♻️ Duplicate comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (1)

374-405: Restrict property suppression to Structures only.

isStructurePropertyAssignment currently returns true for any property assignment just because an accessProperty node exists. As a result, statements like ОтборЭлемента.ПравоеЗначение = "20250101" (receiver is not a Structure) now bypass the diagnostic entirely. Please reuse the symbol-tree based type check you already implemented for structure method calls (or share it) so that we suppress diagnostics only when the receiver is proven to be a Structure; otherwise keep reporting the literal.

📜 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 01f32c2 and d80a10b.

📒 Files selected for processing (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (4 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (2 hunks)
🧰 Additional context used
🧠 Learnings (5)
📚 Learning: 2025-10-27T08:05:10.072Z
Learnt from: theshadowco
Repo: 1c-syntax/bsl-language-server PR: 3555
File: src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java:163-166
Timestamp: 2025-10-27T08:05:10.072Z
Learning: В проекте bsl-language-server используется собственная версия ANTLR4, в которой интерфейс TerminalNode переопределяет метод getParent() с возвращаемым типом RuleNode вместо ParseTree (как в стандартной версии ANTLR4).

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.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:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.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/MagicNumberDiagnostic.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java
📚 Learning: 2025-02-10T17:12:56.150Z
Learnt from: nixel2007
Repo: 1c-syntax/bsl-language-server PR: 3408
File: src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic.java:63-66
Timestamp: 2025-02-10T17:12:56.150Z
Learning: In BSL Language Server, `documentContext.getServerContext().getConfiguration()` is guaranteed to return a non-null value, making null checks unnecessary.

Applied to files:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.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/MagicDateDiagnostic.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: Analyse
  • GitHub Check: build
  • GitHub Check: Benchmark
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (25, windows-latest)
  • GitHub Check: build (25, macOS-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (25, ubuntu-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (17, windows-latest)

… и MagicNumberDiagnostic

- Переписаны методы isStructurePropertyAssignment и isVariableOfStructureType для улучшения читаемости и производительности.
- Добавлены новые проверки на наличие присваивания переменной через "Новый Структура".
- Удалены статические модификаторы из методов, чтобы улучшить инкапсуляцию.
- Обновлены тесты для MagicDateDiagnostic, чтобы отразить изменения в логике диагностики.
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: 3

🧹 Nitpick comments (2)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1)

277-280: Consider enhancing or removing placeholder test.

This test only verifies that getDiagnostics() returns a non-null result, which is trivially true. Given that structure metadata handling is already thoroughly covered by testStructureAssignments(), consider either removing this test or expanding it to verify a specific scenario (e.g., structure variables without symbol tree metadata fall back to AST detection).

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

184-266: Type detection has limited scope.

The current heuristics for detecting structure types have the following limitations:

  1. String matching in descriptions (lines 195-197): Searching for "структура"/"structure" may have false positives (description mentions structures in another context) or false negatives (no description, or uses different terminology).

  2. Only direct assignments (line 231): The code only detects Var = New Structure but misses:

    • Var = SomeFunction() where the function returns a structure
    • Structures passed as parameters
    • Structures from external modules/libraries

While a perfect type system is complex, you might reduce false negatives by also checking:

  • Symbol type information from getSymbolTree() if available
  • Constructor signatures and return types

Based on learnings

📜 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 d80a10b and 25c48d4.

📒 Files selected for processing (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (4 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (2 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📚 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:

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.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/MagicNumberDiagnostic.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.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/MagicDateDiagnostic.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: Analyse
  • GitHub Check: build
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (25, ubuntu-latest)
  • GitHub Check: build (25, windows-latest)
  • GitHub Check: build (25, macOS-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: Benchmark
🔇 Additional comments (6)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (2)

196-207: Excellent centralized decision logic.

The shouldGenerateDiagnostic method cleanly implements the PR objective by suppressing diagnostics in all the appropriate contexts (structure properties/methods, returns, date methods, simple assignments). The logic is clear and maintainable.


487-569: Robust structure type detection with proper fallback.

The implementation correctly uses the symbol tree as the primary source (lines 492-505), then falls back to AST scanning for Новый Структура assignments (lines 516-569). This two-tier approach handles both cases where metadata is available and where it isn't, making the diagnostic resilient to different code patterns.

src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java (2)

172-182: Excellent structure suppression coverage with bilingual support.

The test comprehensively validates that diagnostics are correctly suppressed for:

  • Structure property assignments (lines 175-178)
  • Various structure variable names (lines 179-180)
  • English method names (line 181: DataParams.Insert)

This directly verifies the PR's core objective and ensures bilingual codebases are handled correctly.


218-243: Thorough edge case testing for configuration.

The test validates all critical edge cases:

  • Empty configuration
  • Null configuration
  • Empty string values
  • Invalid date formats in configuration

This defensive testing ensures the diagnostic handles malformed inputs gracefully.

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

137-277: Well-documented new methods.

The added Javadoc comments clearly explain the purpose, parameters, and return values of each new private method. The documentation style is consistent with the project.


192-193: The review comment is incorrect.

Lines 192-193 do not call getDescription() twice on the same object. The chain involves two distinct methods on different types:

  • variableSymbol.get().getDescription() calls VariableSymbol#getDescription() returning Optional<VariableDescription>
  • .map(description -> description.getDescription()) calls VariableDescription#getDescription() (from SourceDefinedSymbolDescription interface) returning String

This is correct API usage and the same pattern is consistently applied across MagicDateDiagnostic and other diagnostics in the codebase.

Likely an incorrect or invalid review comment.

…method calls

- Introduced new methods to check for structure method calls and validate call text.
- Updated logic to prevent false positives for method calls on structure objects.
- Adjusted tests to reflect changes in diagnostics, ensuring correct behavior for structure method calls and assignments.
- Removed outdated test cases that no longer apply to the updated logic.
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

♻️ Duplicate comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (1)

217-270: Performance concern persists: repeated full AST scans.

This method calls Trees.findAllRuleNodes(documentContext.getAst(), BSLParser.RULE_assignment) which traverses the entire AST. Since this is invoked for each magic number in the file, it creates O(n × m) behavior where n is the number of magic numbers and m is the number of assignments.

The previous review suggested implementing document-level caching of structure variable names to avoid repeated scans. Consider this optimization:

private Set<String> cachedStructureVariables = null;

private Set<String> getStructureVariables() {
  if (cachedStructureVariables == null) {
    cachedStructureVariables = new HashSet<>();
    var assignments = Trees.findAllRuleNodes(documentContext.getAst(), BSLParser.RULE_assignment);
    // ... existing logic to populate the set
  }
  return cachedStructureVariables;
}

@Override
public ParseTree visitFile(BSLParser.FileContext ctx) {
  cachedStructureVariables = null; // Reset cache for new file
  return super.visitFile(ctx);
}
🧹 Nitpick comments (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnosticTest.java (1)

128-143: Consider expanding test coverage for edge cases and negative scenarios.

The new tests effectively verify that structure operations don't trigger diagnostics. However, consider adding tests for:

  1. Non-structure objects: Verify that similar syntax with non-structure objects still triggers diagnostics (e.g., SomeObject.Property = 42 where SomeObject is not a Structure).
  2. Edge cases: Test chained property access (Obj1.Obj2.Insert(...)), method call chains (GetStructure().Insert(...)), and other complex expressions.
  3. Boundary validation: Ensure the diagnostic still fires for arithmetic expressions, parameters, and other contexts that should remain flagged.

These additional tests would help prevent regressions and verify the suppression logic doesn't inadvertently become too broad.

Would you like me to generate example test cases for these scenarios?

📜 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 25c48d4 and e263ec5.

⛔ Files ignored due to path filters (1)
  • src/test/resources/diagnostics/MagicNumberDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (3 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnosticTest.java (4 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
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.
📚 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/MagicNumberDiagnostic.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 (21, macOS-latest)
  • GitHub Check: build (25, macOS-latest)
  • GitHub Check: build (25, windows-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (25, ubuntu-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build
  • GitHub Check: Analyse
  • GitHub Check: Benchmark
🔇 Additional comments (3)
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (2)

128-139: Logic correctly suppresses diagnostics for structure operations.

The implementation properly checks for structure property assignments and method calls before applying the standard "wrong expression" checks. When either isStructurePropertyAssignment or isStructureMethodCall returns true, the method returns false (indicating the expression is NOT wrong), which prevents the diagnostic from firing. This aligns with the PR objectives.


196-201: No issue found with the nested getDescription() call.

The code is correct and idiomatic. variableSymbol.get().getDescription() returns Optional<Description>, and the first .map() invokes getDescription() on the Description object (extracting its wrapped String value), producing Optional<String>. The second .map() then processes that String with an explicit (String description) parameter. This pattern is intentional and used consistently throughout the codebase (e.g., MagicDateDiagnostic.java:496).

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

111-126: Helper methods improve test readability.

The hasDiagnosticOnLine and assertNoDiagnosticOnLine helper methods provide a clear, reusable way to verify that specific lines do not trigger diagnostics. The implementation is straightforward and the error messages are descriptive.

…factor structure assignment logic in MagicNumberDiagnostic

- Updated null check in MagicDateDiagnostic to return early if the current node is null.
- Refactored structure assignment logic in MagicNumberDiagnostic for clarity and reusability.
- Introduced a new method to encapsulate structure assignment checks, enhancing code readability and maintainability.
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: 2

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

519-572: Consider caching structure variable names for better performance.

The method scans all assignments in the AST for every magic date check, leading to O(n²) behavior in files with many magic dates and assignments. While correctness is preserved, consider caching the set of structure variable names at the document level (e.g., computed once in visitFile or lazily initialized) to avoid repeated traversals.

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

157-350: Significant code duplication with MagicDateDiagnostic.

The following methods are nearly identical between MagicNumberDiagnostic and MagicDateDiagnostic:

  • isStructurePropertyAssignment
  • findAssignmentContext
  • isVariableOfStructureType
  • isVariableAssignedWithNewStructure
  • isStructureMethodCall
  • isStructureObjectCall
  • isValidCallText
  • getRootParent

Consider extracting these shared structure-detection utilities to AbstractVisitorDiagnostic or a dedicated helper class to improve maintainability and reduce duplication.

📜 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 e263ec5 and b89cf67.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java (4 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java (3 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 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/MagicNumberDiagnostic.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.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/MagicDateDiagnostic.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: Analyse
  • GitHub Check: build
  • GitHub Check: build (25, windows-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (25, ubuntu-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (25, macOS-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: Benchmark

Comment on lines +461 to +471
private boolean isStructureObjectCall(String callText) {
var dotIndex = callText.indexOf('.');
var methodPart = callText.substring(dotIndex + 1);

if (!STRUCTURE_METHOD_PATTERN.matcher(methodPart).find()) {
return false;
}

var objectName = callText.substring(0, dotIndex).trim();
return isVariableOfStructureType(objectName);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Text-based call parsing may miss chained structure calls.

The method extracts objectName using substring(0, dotIndex), which captures only the first identifier before the first dot. This means:

  • Obj1.Obj2.Insert(...) checks if Obj1 is a structure, not Obj2
  • GetStructure().Insert(...) would check if "GetStructure()" is a variable name (likely fails)

While these are edge cases, they could result in false positives where the diagnostic fires for legitimate structure operations. Consider enhancing the detection to use AST traversal for more accurate receiver identification if these patterns are encountered in practice.

🤖 Prompt for AI Agents
In
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java
around lines 461 to 471, the current substring-based extraction of objectName
using the first dot misidentifies receivers for chained member or call
expressions; replace the fragile text parsing with AST-based receiver
resolution: obtain the AST node for the method call, traverse its receiver chain
to find the actual receiver identifier (walk MemberAccess/QualifiedName nodes to
the rightmost qualifier and unwrap CallExpression callee/primary expressions as
needed), then pass that resolved identifier into isVariableOfStructureType.
Ensure null-safety when receiver is complex (function call, parenthesized
expression) and fall back to returning false if no simple identifier can be
resolved.

Comment on lines +318 to +328
private boolean isStructureObjectCall(String callText) {
var dotIndex = callText.indexOf('.');
var methodPart = callText.substring(dotIndex + 1);

if (!STRUCTURE_METHOD_PATTERN.matcher(methodPart).find()) {
return false;
}

var objectName = callText.substring(0, dotIndex).trim();
return isVariableOfStructureType(objectName);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Text-based call parsing may miss chained structure calls.

The method extracts objectName using substring(0, dotIndex), which captures only the first identifier before the first dot. This means:

  • Obj1.Obj2.Insert(...) checks if Obj1 is a structure, not Obj2
  • GetStructure().Insert(...) would check if "GetStructure()" is a variable name (likely fails)

While these are edge cases, they could result in false positives where the diagnostic fires for legitimate structure operations. Consider enhancing the detection to use AST traversal for more accurate receiver identification if these patterns are encountered in practice.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Nov 4, 2025

Quality Gate Failed Quality Gate failed

Failed conditions
77.2% Coverage on New Code (required ≥ 80%)
14.8% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FP] Требует переменные для чисел, при вставке нового ключа в структуру.

2 participants