Skip to content

fix: переход диагностики BadExceptionCategory на TypeService.resolve (#1935)#4128

Merged
nixel2007 merged 2 commits into
1c-syntax:developfrom
erprivalov:feature/Issue-1935-update
Jun 17, 2026
Merged

fix: переход диагностики BadExceptionCategory на TypeService.resolve (#1935)#4128
nixel2007 merged 2 commits into
1c-syntax:developfrom
erprivalov:feature/Issue-1935-update

Conversation

@erprivalov

@erprivalov erprivalov commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Описание

В рамках решения задачи #1935 алгоритм диагностики BadExceptionCategoryDiagnostic переведен на использование семантического анализа через TypeService.resolve(). Новый подход через resolve игнорирует форматирование, исправляя отсутствие срабатывания теста в случаях когда элементы AST-дерева дополнительно разделены пробелами.

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

Closes #1935

Чеклист

Общие

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

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

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

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

Summary by CodeRabbit

  • Documentation

    • Updated diagnostics documentation for event handler validation rules.
  • New Features

    • Added two new configurable diagnostic parameters for event handlers: signature mismatch detection and region boundary checking (both enabled by default).
  • Improvements

    • Enhanced exception category classification accuracy for more reliable diagnostics.
  • Tests

    • Updated diagnostic expectations to reflect the refined behavior.

@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Refactors BadExceptionCategoryDiagnostic to use a single TypeService-based predicate for forbidden category detection, removing the old syntax-based approach and unused Position import. Adds EventHandlerInvalidSignature and EventHandlerOutsideEventRegion to JSON configuration schemas and updates their English doc metadata comments.

Changes

BadExceptionCategoryDiagnostic Refactor

Layer / File(s) Summary
checkForbiddenCategory logic and cleanup
src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadExceptionCategoryDiagnostic.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadExceptionCategoryDiagnosticTest.java
Removes the unused Position import, adjusts @DiagnosticMetadata tag formatting, refactors FORBIDDEN_CATEGORIES from a static lowercase Set to a case-insensitive TreeSet populated by initForbiddenCategories(), and replaces the prior multi-method forbidden-category chain with a single isForbiddenCategoryParam predicate that validates call parameter text, resolves the member type via TypeService, and matches against КатегорияОшибки/ErrorCategory case-insensitively. Test expected count increases from 6 to 7 with a new hasRange assertion for line 32.

EventHandler Diagnostics Schema and Docs Registration

Layer / File(s) Summary
Schema definitions and doc comments
src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json, src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json, docs/en/diagnostics/EventHandlerInvalidSignature.md, docs/en/diagnostics/EventHandlerOutsideEventRegion.md
Inserts EventHandlerInvalidSignature and EventHandlerOutsideEventRegion definitions (default true, boolean | object) into parameters-schema.json and wires both keys into schema.json's diagnosticParameters. Updates the metadata guard comment in each corresponding English diagnostic markdown file.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • 1c-syntax/bsl-language-server#4101: Introduces the BadExceptionCategory diagnostic that this PR directly builds on by refactoring its forbidden-category detection logic.

Suggested labels

hacktoberfest-accepted

Suggested reviewers

  • sfaqer
  • nixel2007

Poem

🐇 Hop hop, the category check is lean,
TypeService resolves what the old code had seen.
EventHandler schemas now properly wired,
No more Position lookups when they're not required.
With seven assertions where six used to be,
The rabbit approves this refactoring spree! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly identifies the main change: migrating BadExceptionCategoryDiagnostic to use TypeService.resolve() to fix issue #1935, which is the core objective.
Linked Issues check ✅ Passed The PR implements the BadExceptionCategoryDiagnostic to detect forbidden exception categories (ВсеОшибки, ПрочаяОшибка, etc.) in functional form RaiseException calls using semantic analysis via TypeService, fulfilling issue #1935 requirements. Configuration schema entries and documentation have been added.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing BadExceptionCategoryDiagnostic and supporting infrastructure (schemas, documentation, tests). Documentation updates for EventHandlerInvalidSignature and EventHandlerOutsideEventRegion are configuration-level additions to support new diagnostics.

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

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

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@erprivalov
erprivalov force-pushed the feature/Issue-1935-update branch from 2d8e868 to 00ac51d Compare June 16, 2026 13:43

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadExceptionCategoryDiagnostic.java`:
- Around line 61-67: The English alias for the raised-from-script exception
category in the errors.addAll() method call in BadExceptionCategoryDiagnostic is
incorrect. Replace "ScriptRaisedException" with "ExceptionRaisedFromScript" to
match the documented 1C forbidden category name. This will ensure that
ErrorCategory.ExceptionRaisedFromScript is properly recognized and not missed by
the token matching logic at line 90.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a45cf8e7-cafe-4b36-8108-4708f51b0b14

📥 Commits

Reviewing files that changed from the base of the PR and between 2d8e868 and 00ac51d.

⛔ Files ignored due to path filters (1)
  • src/test/resources/diagnostics/BadExceptionCategoryDiagnostic.bsl is excluded by !src/test/resources/**
📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadExceptionCategoryDiagnostic.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadExceptionCategoryDiagnosticTest.java

Comment on lines +61 to +67
errors.addAll(List.of(
"ВсеОшибки", "AllErrors",
"ПрочаяОшибка", "OtherError",
"ОшибкаКомпиляцииВстроенногоЯзыка", "ScriptCompileError",
"ОшибкаВоВремяВыполненияВстроенногоЯзыка", "ScriptRuntimeError",
"ИсключениеВызванноеИзВстроенногоЯзыка", "ScriptRaisedException"
));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use the documented English alias for the raised-from-script category.

ScriptRaisedException does not match the 1C documentation’s forbidden English category name, ExceptionRaisedFromScript; because Line 90 rejects unknown token text before memberAt(), ErrorCategory.ExceptionRaisedFromScript is currently missed. The referenced 1C developer guide lists the forbidden categories as AllErrors, OtherError, ScriptCompileError, ScriptRuntimeError, and ExceptionRaisedFromScript. (kb.1ci.com)

🐛 Proposed fix
     errors.addAll(List.of(
       "ВсеОшибки", "AllErrors",
       "ПрочаяОшибка", "OtherError",
       "ОшибкаКомпиляцииВстроенногоЯзыка", "ScriptCompileError",
       "ОшибкаВоВремяВыполненияВстроенногоЯзыка", "ScriptRuntimeError",
-      "ИсключениеВызванноеИзВстроенногоЯзыка", "ScriptRaisedException"
+      "ИсключениеВызванноеИзВстроенногоЯзыка", "ExceptionRaisedFromScript"
     ));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadExceptionCategoryDiagnostic.java`
around lines 61 - 67, The English alias for the raised-from-script exception
category in the errors.addAll() method call in BadExceptionCategoryDiagnostic is
incorrect. Replace "ScriptRaisedException" with "ExceptionRaisedFromScript" to
match the documented 1C forbidden category name. This will ensure that
ErrorCategory.ExceptionRaisedFromScript is properly recognized and not missed by
the token matching logic at line 90.

@sonarqubecloud

Copy link
Copy Markdown

}
private boolean isForbiddenCategoryParam(CallParamContext param) {
String lastTokenText = param.getStop().getText();
if (!FORBIDDEN_CATEGORIES.contains(lastTokenText)) {

Copy link
Copy Markdown
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 b146a92 into 1c-syntax:develop Jun 17, 2026
29 checks passed
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] BadExceptionCategory

2 participants