Skip to content

fix(SymbolProvider): откатываться на буквальный поиск при невалидном regex в workspace/symbol#4063

Merged
nixel2007 merged 3 commits into
developfrom
claude/workspacesymbol-query-escaping
Jun 12, 2026
Merged

fix(SymbolProvider): откатываться на буквальный поиск при невалидном regex в workspace/symbol#4063
nixel2007 merged 3 commits into
developfrom
claude/workspacesymbol-query-escaping

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jun 12, 2026

Copy link
Copy Markdown
Member

Проблема

Строка запроса workspace/symbol напрямую компилировалась как регулярное выражение
(CaseInsensitivePattern.compile(query)). Если пользователь вводил подстроку со
спецсимволом регулярного выражения (например «Получить(» или «Метод[»), компиляция
бросала PatternSyntaxException, и провайдер возвращал пустой список. Из-за этого
обычный пользовательский ввод приводил к "ничего не найдено", хотя спецификация LSP
рекомендует трактовать query в "расслабленной" манере и доверять клиенту дофильтрацию.

Решение

Компиляция шаблона вынесена в compilePattern(...). При PatternSyntaxException
выполняется откат на буквальное сопоставление: Pattern.compile(Pattern.quote(query), CASE_INSENSITIVE | UNICODE_CASE) — те же флаги, что и у CaseInsensitivePattern.
Полноценный fuzzy-поиск намеренно не вводится. Правка строго локальна в месте
компиляции/матчинга паттерна, createWorkspaceSymbol не затронут.

Тесты

  • Обновлён getSymbolsQueryStringErrorRegex: запрос «Метод(» теперь не вызывает
    исключения, а трактуется как литерал. В фикстурах нет имён символов с литералом
    «Метод(», поэтому ожидается пустой результат — но уже без отбрасывания валидных
    совпадений. Имена методов/переменных в BSL не могут содержать спецсимволы regex,
    поэтому литеральное совпадение по реальным фикстурам пустое по объективной причине.
  • Добавлен getSymbolsQueryWithRegexSpecialCharsFallsBackToLiteralMatch (Mockito):
    символ с именем «Метод(Параметр» и невалидный запрос «Метод(». До правки тест падал
    (пустой результат из-за PatternSyntaxException), после — находит символ.

Прогон SymbolProviderTest (5 тестов) — BUILD SUCCESSFUL, все PASSED.

🤖 Generated with Claude Code

Summary by CodeRabbit

Bug Fixes

  • Symbol search now gracefully handles queries containing regex special characters. Invalid regex patterns automatically fall back to literal substring matching, preventing empty results.

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@nixel2007, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 10 minutes and 20 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 601e72eb-2267-4117-b58f-3522f236e86d

📥 Commits

Reviewing files that changed from the base of the PR and between 23241b0 and e324104.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProvider.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProviderTest.java
📝 Walkthrough

Walkthrough

The PR improves workspace symbol query handling by introducing graceful fallback from regex to literal matching. When a user query contains regex-special characters (like parentheses), the new compilePattern() helper catches compilation errors and returns a pattern that matches the literal substring instead, enabling symbol discovery instead of returning empty results.

Changes

Symbol Query Regex Fallback

Layer / File(s) Summary
Pattern compilation with fallback
src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProvider.java
New compilePattern() method compiles queries as case-insensitive Unicode-aware regex and falls back to quoted literal patterns on PatternSyntaxException. The getSymbols() method delegates regex compilation to this helper instead of inline error handling. Imports are updated.
Test coverage for regex fallback and literal matching
src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProviderTest.java
Test imports expanded to support symbol/context mocking. New mockMethodSymbol() helper creates SourceDefinedSymbol mocks with minimal state. Updated getSymbolsQueryStringErrorRegex test uses "Метод(" as the invalid pattern. New getSymbolsQueryWithRegexSpecialCharsFallsBackToLiteralMatch test verifies literal matching of symbol names containing regex-special characters.

🎯 2 (Simple) | ⏱️ ~12 minutes

🐰 A symbol sought with brackets askew,

No longer fails when patterns won't do,

We quote and we match the literal way,

Finding your methods—hip-hip-hooray! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 title accurately describes the main change: implementing a fallback to literal search when regex validation fails in workspace/symbol queries.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/workspacesymbol-query-escaping

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.

@github-actions

Copy link
Copy Markdown
Contributor

Test Results

 3 246 files  ±0   3 246 suites  ±0   1h 36m 54s ⏱️ + 2m 1s
 3 093 tests +1   3 078 ✅ +1  15 💤 ±0  0 ❌ ±0 
18 558 runs  +6  18 468 ✅ +6  90 💤 ±0  0 ❌ ±0 

Results for commit 23241b0. ± Comparison against base commit c4a8470.

@sonarqubecloud

Copy link
Copy Markdown

@nixel2007
nixel2007 enabled auto-merge June 12, 2026 14:31
nixel2007 and others added 2 commits June 12, 2026 18:51
…regex в workspace/symbol

Запрос workspace/symbol со спецсимволами регулярных выражений (например «Получить(»)
больше не приводит к PatternSyntaxException и пустой выдаче. При невалидном регулярном
выражении выполняется откат на буквальное сопоставление подстроки, как рекомендует
"расслабленная" трактовка query в спецификации LSP.

Co-Authored-By: Claude Fable 5 <[email protected]>
…al-фолбэке

Вместо ручного Pattern.compile с дублированием флагов CASE_INSENSITIVE | UNICODE_CASE.

Co-Authored-By: Claude Fable 5 <[email protected]>
@nixel2007
nixel2007 force-pushed the claude/workspacesymbol-query-escaping branch from 08a72f5 to 1df5af1 Compare June 12, 2026 16:52
После вливания containerName (#4062) createWorkspaceSymbol обращается к
symbol.getOwner().getMdObject() — мок без стаба ронял тест NPE.

Co-Authored-By: Claude Fable 5 <[email protected]>
@nixel2007
nixel2007 disabled auto-merge June 12, 2026 18:07
@nixel2007
nixel2007 merged commit bcfef0d into develop Jun 12, 2026
31 checks passed
@nixel2007
nixel2007 deleted the claude/workspacesymbol-query-escaping branch June 12, 2026 18:07
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.

1 participant