bsl-language-server icon indicating copy to clipboard operation
bsl-language-server copied to clipboard

Feauture/query nested fields by dot

Open Levon444 opened this issue 6 months ago • 1 comments

Описание

Добавил диагностику, проверяющую наличие разыменований ссылочных полей через точку.

Диагностика ругается на разыменование:

  1. В полях выборки
  2. В Секции "ГДЕ"
  3. В Соединениях
  4. В параметрах виртуальных таблиц
  5. Соответственно и в запросах для отбора параметров виртуальных таблиц
  6. В функции "ВЫРАЗИТЬ"

Реализация: Реализовал через "AbstractSDBLListenerDiagnostic", посчитал такой вариант более легковесным. В основном используется функция "enterColumn", так как в по контексту колонки через свойство "columnNames" очень удобно проверять разыменование (если количество элементов у списка более 1, то это "редфлаг" =)), исключением являются виртуальные таблицы, где даже 1 элемент в columnNames свидетельствует о наличии разыменования, в такой ситуации дополнительно контролируется заполненность свойства mdoName, также при посещении секции параметров виртуальной таблицы взводится флаг о начале обработки ВТ, дабы при посещении контекста колонки можно было легче понять где мы находимся. Для контроля функций по схожему принципу используется метод enterFunctionnCall.

Что то красивое через stream и подобное реализовать не вышло ибо не нашел этому применения. Возможно диагностика описана косноязычно, так что жду критики)

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

Основная задача: Closes #1301

Задача, описывающая схожий функционал, но более частное его проявление: Closes #2792

Чеклист

Общие

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

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

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

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

Levon444 avatar May 08 '25 06:05 Levon444

Walkthrough

В проект добавлена новая диагностика QueryNestedFieldsByDot, предназначенная для выявления разыменования ссылочных полей через точку в тексте запроса 1С. Реализованы диагностический класс, документация, локализации сообщений, тесты и тестовые данные, охватывающие различные сценарии использования точки для доступа к вложенным полям.

Changes

Файл(ы) Краткое описание изменений
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryNestedFieldsByDotDiagnostic.java Добавлен новый диагностический класс для выявления разыменования ссылочных полей через точку в запросах 1С, с обработкой различных контекстов (виртуальные таблицы, функции, колонки).
src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryNestedFieldsByDotDiagnostic_en.properties,
src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryNestedFieldsByDotDiagnostic_ru.properties
Добавлены новые файлы локализации сообщений диагностики на русском и английском языках.
docs/diagnostics/QueryNestedFieldsByDot.md,
docs/en/diagnostics/QueryNestedFieldsByDot.md
Добавлена документация по новой диагностике на русском и английском языках с примерами и описанием.
src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryNestedFieldsByDotDiagnosticTest.java,
src/test/resources/diagnostics/QueryNestedFieldsByDotDiagnostic.bsl
Добавлены тесты и тестовые данные для проверки корректности работы диагностики, включая различные случаи разыменования через точку.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant BSL_LanguageServer
    participant QueryNestedFieldsByDotDiagnostic

    User->>BSL_LanguageServer: Запуск анализа запроса 1С
    BSL_LanguageServer->>QueryNestedFieldsByDotDiagnostic: Передача AST запроса
    QueryNestedFieldsByDotDiagnostic->>QueryNestedFieldsByDotDiagnostic: Обход элементов запроса
    alt Найдено разыменование через точку
        QueryNestedFieldsByDotDiagnostic->>BSL_LanguageServer: Добавить диагностическое сообщение
    end
    BSL_LanguageServer->>User: Возврат списка диагностик

Assessment against linked issues

Objective Addressed Explanation
Диагностика разыменования ссылочных полей составного типа через точку в запросах 1С (#1301)
Диагностика обращения через точку к полям ссылочных реквизитов временной таблицы (#2792)

Poem

В запросах точка — ловушка проста,
Ссылочные поля — не тронь их, брат!
Диагностика новая строго следит,
Где разыменование — зайчик кричит!
Теперь запросы чище, быстрей и светлей,
Спасибо за код — и морковку скорей! 🥕

[!TIP]

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • [ ] 📝 Generate Docstrings

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
🪧 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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 using 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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.

coderabbitai[bot] avatar May 08 '25 06:05 coderabbitai[bot]