Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Реализация #3271: Диагностика двойных отрицаний #3308

Merged
merged 11 commits into from
Aug 20, 2024

Conversation

EvilBeaver
Copy link
Collaborator

Описание

  • Добавлен новый вид абстрактной диагностики - диагностика по дереву выражений (вместо AST)
  • Существующая диагностика IdenticalSubexpressions переделана на этот механизм
  • Новая диагностика DoubleNegatives так же использует этот механизм
  • Диагностика DoubleNegatives проверяет двойные отрицания вида
    • Не А = БулевЛитерал
    • Не А <> ЛюбоеВыражение

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

Closes #3271

#3271

Чеклист

Общие

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

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

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

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

Copy link

coderabbitai bot commented Jun 6, 2024

Walkthrough

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

Changes

Файл Описание изменений
docs/diagnostics/DoubleNegatives.md Добавлен новый файл, описывающий диагностику двойных отрицаний
src/.../diagnostics/AbstractExpressionTreeDiagnostic.java Добавлены новые классы и методы для анализа выражений и построения дерева выражений
src/.../diagnostics/DoubleNegativesDiagnostic.java Новый класс для обнаружения двойных отрицаний в коде BSL
src/.../diagnostics/IdenticalExpressionsDiagnostic.java Возвращение к AbstractExpressionTreeDiagnostic, обновление методов для работы с бинарными операциями
src/.../expressiontree/BinaryOperationNode.java Обновление аннотаций и полей для BinaryOperationNode
src/.../expressiontree/BslExpression.java Добавлены новые аннотации и поле parent в BslExpression
src/.../expressiontree/BslOperationNode.java Изменение конструктора BslOperationNode
src/.../expressiontree/ExpressionTreeBuildingVisitor.java Открытие класса как публичного финального, новые методы для построения деревьев выражений
src/.../expressiontree/ExpressionTreeVisitor.java Добавлены методы для посещения различных типов узлов
src/.../expressiontree/TerminalSymbolNode.java Обновление конструктора TerminalSymbolNode
src/.../diagnostics/DoubleNegativesDiagnostic_en.properties Сообщения на английском языке для диагностики двойных отрицаний
src/.../diagnostics/DoubleNegativesDiagnostic_ru.properties Сообщения на русском языке для диагностики двойных отрицаний
src/.../diagnostics/DoubleNegativesDiagnosticTest.java Новый тестовый класс для проверки работы DoubleNegativesDiagnostic
src/.../ExpressionParseTreeRewriterTest.java Переименование в ExpressionTreeBuildingVisitor и изменение соответствующих методов
src/.../ExpressionTreeComparersTest.java Переход на использование ExpressionTreeBuildingVisitor для построения деревьев выражений
src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl Новый файл с логикой проверки двойных отрицаний в BSL

Assessment against linked issues

Объектив Addressed Объяснение
[3271] Диагностика избыточных отрицаний

🐰 В коде был закон,
Двойные отрицания – дурной тон.
Теперь для ясности и красоты,
Диагностика борется с этой темнотой.
📝 Testы завершены, код пишется чисто,
Работаем дальше, ведь путь наш искристый.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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

Outside diff range and nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java (1)

42-42: Комментарий к классу ExpressionTreeBuildingVisitor должен быть переведен на английский язык, чтобы соответствовать общим стандартам документации проекта.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between dd5b714 and 7ad9766.

Files ignored due to path filters (2)
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json is excluded by !**/*.json
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json is excluded by !**/*.json
Files selected for processing (17)
  • docs/diagnostics/DoubleNegatives.md (1 hunks)
  • docs/en/diagnostics/DoubleNegatives.md (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExpressionTreeDiagnostic.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnostic.java (4 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BinaryOperationNode.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslExpression.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslOperationNode.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java (6 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeVisitor.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TerminalSymbolNode.java (1 hunks)
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic_en.properties (1 hunks)
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic_ru.properties (1 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnosticTest.java (1 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionParseTreeRewriterTest.java (3 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionTreeComparersTest.java (2 hunks)
  • src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl (1 hunks)
Files skipped from review due to trivial changes (5)
  • docs/diagnostics/DoubleNegatives.md
  • docs/en/diagnostics/DoubleNegatives.md
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic_en.properties
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic_ru.properties
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnosticTest.java
Additional comments not posted (27)
src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslOperationNode.java (1)

39-39: Изменение конструктора BslOperationNode соответствует новой структуре суперкласса. Убедитесь, что все экземпляры этого класса и его подклассов корректно обновлены для передачи нового параметра.

Verification successful

Изменение конструктора BslOperationNode было корректно применено в подклассах UnaryOperationNode и BinaryOperationNode. Все вызовы конструктора используют новую сигнатуру.

  • UnaryOperationNode.java: super(ExpressionNodeType.UNARY_OP, operator, operationContext);
  • BinaryOperationNode.java: super(ExpressionNodeType.BINARY_OP, operator, actualSourceCode);
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Описание: Проверка использования конструктора `BslOperationNode` во всем проекте.

# Тест: Поиск использования конструктора. Ожидаем: только вызовы с новой сигнатурой.
rg --type java $'new BslOperationNode'

Length of output: 39



Script:

#!/bin/bash
# Описание: Проверка использования класса `BslOperationNode` во всем проекте.

# Тест: Поиск использования класса. Ожидаем: найти все упоминания класса.
rg --type java 'BslOperationNode'

Length of output: 1107



Script:

#!/bin/bash
# Описание: Проверка использования конструктора `BslOperationNode` в подклассах.

# Тест: Поиск использования конструктора в подклассах. Ожидаем: найти вызовы конструктора с новой сигнатурой.
rg --type java 'super(' src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BinaryOperationNode.java src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/UnaryOperationNode.java

Length of output: 289



Script:

#!/bin/bash
# Описание: Проверка использования конструктора `BslOperationNode` в подклассах.

# Тест: Поиск использования конструктора в подклассах. Ожидаем: найти вызовы конструктора с новой сигнатурой.
rg --type java 'super\(' src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BinaryOperationNode.java src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/UnaryOperationNode.java

Length of output: 565

src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl (1)

1-41: Тестовые случаи в файле DoubleNegativesDiagnostic.bsl кажутся всесторонними и предназначены для активации диагностики в различных условиях. Убедитесь, что они соответствуют предполагаемому поведению диагностики.

src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslExpression.java (1)

28-42: Добавление поля parent и аннотаций @Setter и @ToString в класс BslExpression соответствует улучшению структуры дерева выражений. Убедитесь, что изменения не влияют на другие части системы неожиданным образом.

Verification successful

Использование поля parent в классе BslExpression в файле DoubleNegativesDiagnostic.java корректно и соответствует его назначению. Изменения не вызывают побочных эффектов.

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Описание: Проверка влияния изменений в `BslExpression` на другие части системы.

# Тест: Поиск использования поля `parent`. Ожидаем: корректное использование без побочных эффектов.
rg --type java $'parent'

Length of output: 20245



Script:

#!/bin/bash
# Extract and review the relevant code snippets where `parent` is used in `DoubleNegativesDiagnostic.java`.

# Search for the usage of `parent` in `DoubleNegativesDiagnostic.java`.
rg --type java --context 5 'parent' src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java

Length of output: 1149

src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TerminalSymbolNode.java (1)

33-33: Изменение конструктора TerminalSymbolNode соответствует новой структуре. Убедитесь, что все экземпляры этого класса корректно обновлены.

Verification successful

Конструктор TerminalSymbolNode используется с новой сигнатурой во всех найденных случаях.

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TerminalSymbolNode.java: три вызова конструктора с двумя параметрами.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Описание: Проверка использования конструктора `TerminalSymbolNode` во всем проекте.

# Тест: Поиск использования конструктора. Ожидаем: только вызовы с новой сигнатурой.
rg --type java $'new TerminalSymbolNode'

Length of output: 565

src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BinaryOperationNode.java (2)

29-29: Добавлены аннотации Lombok для автоматической генерации методов. Это улучшает читаемость и поддерживаемость кода.


33-34: Поля left и right теперь объявлены как private final, что улучшает инкапсуляцию и обеспечивает неизменяемость, повышая надежность кода.

src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeVisitor.java (5)

50-52: Метод visitTopLevelExpression корректно делегирует вызов методу visit, что является хорошей практикой проектирования.


54-57: Метод visitAbstractCall корректно реализует паттерн посетитель, обходя все аргументы вызова.


60-62: Метод visitUnaryOperation правильно реализует паттерн посетитель для унарных операций.


64-67: Метод visitBinaryOperation эффективно использует паттерн посетитель, обрабатывая обе стороны бинарной операции.


69-73: Метод visitTernaryOperator тщательно реализует паттерн посетитель, обходя все компоненты тернарной операции.

src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionTreeComparersTest.java (1)

75-75: Метод getExpressionTree теперь использует ExpressionTreeBuildingVisitor, что соответствует общей стратегии рефакторинга и улучшает согласованность.

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

46-54: Метод getDiagnostics эффективно инкапсулирует логику диагностики, устанавливая контекст документа, очищая предыдущие диагностики, строя дерево выражений и возвращая диагностики.


67-69: Метод onExpressionEnter позволяет оптимизировать производительность, предоставляя раннее принятие решений о необходимости построения дерева выражений.


74-90: Перечисление ExpressionVisitorDecision четко определяет решения, которые можно принимать при входе в выражение, управляя потоком управления в процессе диагностики.

src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java (4)

36-43: Проверьте, что все теги диагностики соответствуют вашим требованиям. В частности, DiagnosticTag.BADPRACTICE может быть не совсем точным для данной диагностики, если она нацелена на улучшение читаемости, а не на указание на плохие практики кодирования.


52-73: Логика в методе visitBinaryOperation кажется корректной, но стоит убедиться, что все случаи двойного отрицания корректно обрабатываются. В частности, проверьте, что логика в строках 67-71 адекватно обрабатывает все возможные сценарии, связанные с бинарными операциями и литералами.


91-97: Метод isBooleanLiteral корректно определяет, является ли узел булевым литералом. Однако, убедитесь, что контекст ConstValueContext всегда будет содержать только булевы литералы, и нет случаев, когда это предположение нарушается.


103-108: Метод addDiagnostic использует Trees.getTokens, который может быть неэффективен, если вызывается часто. Рассмотрите возможность кэширования результатов или оптимизации вызовов, чтобы уменьшить потенциальное влияние на производительность.
[PERFORMANCE]

src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnostic.java (4)

37-37: Проверьте, что тип диагностики (DiagnosticType.ERROR) корректно отражает натуру проблем, которые выявляет данная диагностика. Если диагностика не связана с ошибками выполнения, возможно, стоит использовать другой тип, например, DiagnosticType.CODE_SMELL.


101-104: Метод onExpressionEnter использует кастомную логику для определения, следует ли пропускать обработку выражения. Убедитесь, что метод sufficientSize корректно реализован и не приводит к пропуску важных выражений.


106-118: Метод visitTopLevelExpression использует TransitiveOperationsIgnoringComparer для сравнения операций. Убедитесь, что логика сравнения корректно обрабатывает все случаи и не приводит к ложным срабатываниям или пропускам.


120-135: В методе visitBinaryOperation используется фильтрация операций по типу. Убедитесь, что все исключаемые операции (DEREFERENCE, INDEX_ACCESS) действительно не должны обрабатываться в рамках данной диагностики.

src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java (2)

65-69: Метод buildExpressionTree предоставляет публичный статический интерфейс для построения деревьев выражений. Убедитесь, что этот метод используется во всех местах, где требуется построение деревьев выражений, чтобы избежать дублирования логики.


195-208: Метод processOperation использует приоритет операций для построения дерева. Убедитесь, что логика сравнения приоритетов корректна и не приводит к ошибкам в структуре дерева.

src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionParseTreeRewriterTest.java (2)

149-162: Тест booleanNotPriority проверяет приоритет оператора NOT. Убедитесь, что тест покрывает все возможные случаи использования этого оператора, включая вложенные и сложные выражения.


335-352: Тест notOperatorPriority проверяет корректность приоритета оператора NOT в сложных выражениях. Убедитесь, что тест адекватно отражает все потенциальные случаи использования и не пропускает краевые случаи.

Comment on lines 47 to 50
@Override
protected ExpressionVisitorDecision onExpressionEnter(BSLParser.ExpressionContext ctx) {
return super.onExpressionEnter(ctx);
}
Copy link

Choose a reason for hiding this comment

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

Метод onExpressionEnter переопределяется только для вызова родительской реализации. Если дополнительная логика обработки выражений не требуется, можно рассмотреть возможность удаления этого переопределения для упрощения кода.

Copy link

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7ad9766 and 656b264.

Files selected for processing (4)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExpressionTreeDiagnostic.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnostic.java (5 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java (6 hunks)
Files skipped from review as they are similar to previous changes (4)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExpressionTreeDiagnostic.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnostic.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java

@nixel2007
Copy link
Member

/rebase

Copy link

@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: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 656b264 and 7e2945b.

Files selected for processing (1)
  • src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl (1 hunks)
Additional comments not posted (6)
src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl (6)

33-34: Отрицание с неравенством нелитералу.

Строки 33 и 34 демонстрируют случаи с отрицанием и неравенством нелитералу, которые должны срабатывать. Это важные тесты для проверки способности диагностики распознавать менее очевидные случаи двойных отрицаний.


40-42: Прямое двойное отрицание.

Строки 40-42 содержат примеры прямого двойного отрицания. Необходимо убедиться, что диагностика корректно идентифицирует и обрабатывает такие случаи, особенно в контексте сложных логических выражений.


23-25: Сложные условия с двойными отрицаниями.

Строки 23-25 содержат сложные условные выражения с использованием двойных отрицаний. Эти случаи особенно важны для проверки, так как они влияют на точность и эффективность диагностики. Убедитесь, что диагностика адекватно обрабатывает такие случаи.


8-18: Различные случаи использования двойных отрицаний.

Примеры от 8 по 18 строки демонстрируют различные сценарии использования двойных отрицаний. Важно убедиться, что диагностика корректно срабатывает в каждом случае. Особое внимание следует уделить строкам, где указано "не срабатывает", чтобы подтвердить, что это ожидаемое поведение.

Verification successful

Подтвердите корректность работы диагностики для двойных отрицаний

Имплементация класса DoubleNegativesDiagnostic показывает, что диагностика срабатывает для случаев, когда оператором является NOT_EQUAL или один из операндов является булевым литералом. Код также проверяет наличие родительского узла с оператором отрицания. Это подтверждает, что диагностика должна корректно срабатывать для указанных случаев.

  • Файл: src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java
  • Методы: visitBinaryOperation, visitUnaryOperation, isBooleanLiteral, isNegationOperator, addDiagnostic
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that diagnostic triggers correctly for the lines where it is supposed to trigger and does not trigger where indicated.
# Test: Manually review the output of the diagnostic for each case.
rg --type bsl $'DoubleNegativesDiagnostic'

Length of output: 69



Script:

#!/bin/bash
# Locate files in the diagnostics directory to identify the correct file type or extension.
fd . src/test/resources/diagnostics

Length of output: 13095



Script:

#!/bin/bash
# Search for the DoubleNegativesDiagnostic within .bsl files.
rg 'DoubleNegativesDiagnostic' --glob '*.bsl'

Length of output: 45



Script:

#!/bin/bash
# Search for the implementation of the DoubleNegativesDiagnostic function in the codebase.
ast-grep --lang bsl --pattern 'function DoubleNegativesDiagnostic($$) { $$ }'

Length of output: 186



Script:

#!/bin/bash
# Search for the implementation of the DoubleNegativesDiagnostic function in .bsl files.
rg 'function DoubleNegativesDiagnostic' --glob '*.bsl'

Length of output: 56



Script:

#!/bin/bash
# Search for any references to DoubleNegativesDiagnostic in the codebase.
rg 'DoubleNegativesDiagnostic'

Length of output: 692



Script:

#!/bin/bash
# Extract the implementation of DoubleNegativesDiagnostic from the identified file.
sed -n '/public class DoubleNegativesDiagnostic extends AbstractExpressionTreeDiagnostic/,/}/p' src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java

Length of output: 515



Script:

#!/bin/bash
# Extract the complete implementation of DoubleNegativesDiagnostic from the identified file.
sed -n '/public class DoubleNegativesDiagnostic extends AbstractExpressionTreeDiagnostic/,/^}/p' src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java

Length of output: 2631


44-45: Проверка записи без использования двойных отрицаний.

Строки 44 и 45 кажутся не связанными с темой двойных отрицаний, но важно проверить, не влияют ли изменения диагностики на другие части кода, особенно при работе с объектами и методами.

Verification successful

Изменения диагностики не влияют на обработку объектов и вызовы методов.

Методы visitBinaryOperation и visitUnaryOperation в классе DoubleNegativesDiagnostic касаются только логики диагностики двойных отрицаний и не вмешиваются в обработку объектов или вызовы методов в других частях кода.

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the changes in diagnostic do not affect unrelated parts of the code, particularly object handling and method calls.
# Test: Review the behavior of these lines after diagnostic changes.
rg --type bsl $'DoubleNegativesDiagnostic'

Length of output: 69



Script:

#!/bin/bash
# Description: Verify that the changes in diagnostic do not affect unrelated parts of the code, particularly object handling and method calls.
# Test: Review the behavior of these lines after diagnostic changes.
rg 'DoubleNegativesDiagnostic'

Length of output: 692



Script:

#!/bin/bash
# Description: Retrieve the implementation of DoubleNegativesDiagnostic.
ast-grep --lang java --pattern $'class DoubleNegativesDiagnostic extends $_ {
  $$$
}' src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java

Length of output: 185



Script:

#!/bin/bash
# Description: Retrieve the implementation of DoubleNegativesDiagnostic.
rg 'class DoubleNegativesDiagnostic' src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java

Length of output: 218



Script:

#!/bin/bash
# Description: Retrieve the full implementation of DoubleNegativesDiagnostic.
rg -A 50 'public class DoubleNegativesDiagnostic extends AbstractExpressionTreeDiagnostic' src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java

Length of output: 1818


27-29: Популярные кодовые конструкции с отрицаниями.

В строках 27-29 используется популярная конструкция с отрицанием, которая, как указано, не должна срабатывать. Это важно для предотвращения ложных срабатываний на широко используемые и принятые практики.

Verification successful

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

  • src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the diagnostic does not trigger on popular code constructs as intended.
# Test: Check for false positives in commonly used constructs.
rg --type bsl $'DoubleNegativesDiagnostic'

Length of output: 69



Script:

#!/bin/bash
# Locate all files and search for the DoubleNegativesDiagnostic pattern
fd -e bsl | xargs rg 'DoubleNegativesDiagnostic'

Length of output: 48



Script:

#!/bin/bash
# Search for the term DoubleNegativesDiagnostic in all files to locate its definition or usage.
rg 'DoubleNegativesDiagnostic'

Length of output: 692



Script:

#!/bin/bash
# Extract the implementation of DoubleNegativesDiagnostic from the source file.
ast-grep --lang java --pattern $'class DoubleNegativesDiagnostic extends AbstractExpressionTreeDiagnostic {
  $$$
}' src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java

Length of output: 215



Script:

#!/bin/bash
# Search for the implementation of DoubleNegativesDiagnostic in the source file.
rg 'class DoubleNegativesDiagnostic' src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java -A 50

Length of output: 1770



Script:

#!/bin/bash
# Search for test cases in DoubleNegativesDiagnosticTest.
rg 'DoubleNegativesDiagnostic' src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnosticTest.java -A 50

Length of output: 872



Script:

#!/bin/bash
# Search for test resources related to DoubleNegativesDiagnostic in the src/test/resources directory.
fd -e bsl --search-path src/test/resources

Length of output: 19029



Script:

#!/bin/bash
# View the contents of DoubleNegativesDiagnostic.bsl.
cat src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl

Length of output: 1568

Copy link

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7e2945b and 2dff72e.

Files selected for processing (5)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExpressionTreeDiagnostic.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java (7 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnosticTest.java (1 hunks)
  • src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl (1 hunks)
Additional context used
Learnings (3)
src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl (2)
Learnt from: nixel2007
PR: 1c-syntax/bsl-language-server#3308
File: src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl:20-21
Timestamp: 2024-07-04T19:35:26.747Z
Learning: The file `DoubleNegativesDiagnostic.bsl` is a test resource intended to demonstrate the functionality of the DoubleNegatives diagnostic.
Learnt from: nixel2007
PR: 1c-syntax/bsl-language-server#3308
File: src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl:2-4
Timestamp: 2024-07-04T19:35:42.937Z
Learning: Test resources in the repository may contain code that intentionally triggers diagnostics to demonstrate their functionality.
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnosticTest.java (2)
Learnt from: nixel2007
PR: 1c-syntax/bsl-language-server#3308
File: src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl:2-4
Timestamp: 2024-07-04T19:35:42.937Z
Learning: Test resources in the repository may contain code that intentionally triggers diagnostics to demonstrate their functionality.
Learnt from: nixel2007
PR: 1c-syntax/bsl-language-server#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.
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java (2)
Learnt from: nixel2007
PR: 1c-syntax/bsl-language-server#3308
File: src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl:20-21
Timestamp: 2024-07-04T19:35:26.747Z
Learning: The file `DoubleNegativesDiagnostic.bsl` is a test resource intended to demonstrate the functionality of the DoubleNegatives diagnostic.
Learnt from: nixel2007
PR: 1c-syntax/bsl-language-server#3308
File: src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl:2-4
Timestamp: 2024-07-04T19:35:42.937Z
Learning: Test resources in the repository may contain code that intentionally triggers diagnostics to demonstrate their functionality.
Additional comments not posted (19)
src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl (2)

2-4: Ресурс для тестов: Условие с двойным отрицанием.

Этот код предназначен для проверки диагностики двойных отрицаний.


16-17: Ресурс для тестов: Условие в цикле с двойным отрицанием.

Этот код предназначен для проверки диагностики двойных отрицаний.

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

31-34: Класс тестирования DoubleNegativesDiagnostic.

Класс правильно наследует AbstractDiagnosticTest и инициализирует тесты для DoubleNegativesDiagnostic.


36-56: Метод тестирования диагностики.

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

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

1-43: Класс DoubleNegativesDiagnostic.

Класс правильно наследует AbstractExpressionTreeDiagnostic и определяет метаданные диагностики.


46-66: Метод visitBinaryOperation.

Метод корректно обрабатывает бинарные операции и проверяет наличие двойных отрицаний.


68-81: Метод visitUnaryOperation.

Метод корректно обрабатывает унарные операции и проверяет наличие двойных отрицаний.


83-86: Метод isNegationOperator.

Метод правильно определяет, является ли родительский узел оператором отрицания.


88-114: Методы addDiagnostic.

Методы корректно добавляют диагностику для бинарных и унарных операций.

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

1-43: Класс AbstractExpressionTreeDiagnostic.

Класс предоставляет основные методы и функциональность для диагностики на основе деревьев выражений.


47-56: Метод getDiagnostics.

Метод корректно инициализирует контекст документа и строит дерево выражений.


58-71: Метод onExpressionEnter.

Метод предоставляет стратегию для входа в выражение и определения необходимости построения дерева выражений.


73-92: Перечисление ExpressionVisitorDecision.

Перечисление определяет возможные действия при входе в выражение.


94-121: Класс ExpressionTreeBuilder.

Класс корректно строит дерево выражений и вызывает методы для обработки верхнеуровневых выражений.

src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java (5)

65-69: Хорошо!

Метод buildExpressionTree правильно реализует фабричный метод для создания и инициации построения дерева выражений.


195-195: Хорошо!

Метод visitOperation корректно обрабатывает операции, обеспечивая правильный приоритет операторов.


202-209: Хорошо!

Метод hasHigherPriorityOperatorsInFly корректно сравнивает приоритет текущего оператора с операторами в стеке.


380-380: Хорошо!

Метод makeSubexpression корректно делегирует построение подвыражения методу buildExpressionTree.


405-414: Хорошо!

Метод buildOperation корректно обрабатывает построение операций и устанавливает родительские узлы.

Copy link

sonarcloud bot commented Jul 9, 2024

Comment on lines +70 to +72
if (node.getOperator() == BslOperator.NOT &&
node.getParent() != null &&
node.getParent().getNodeType() == ExpressionNodeType.UNARY_OP) {
Copy link
Member

Choose a reason for hiding this comment

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

&& стоит слева поставить при переносе

@nixel2007 nixel2007 merged commit 7a7ce89 into 1c-syntax:develop Aug 20, 2024
18 of 19 checks passed
@nixel2007
Copy link
Member

Спасибо!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[NEW] Диагностика избыточных отрицаний
3 participants