Skip to content

feat(types/oscript): ConstructorSymbol — отдельный тип для конструктора OScript-класса#3945

Merged
nixel2007 merged 1 commit into
developfrom
feature/oscript-constructor-symbol
May 26, 2026
Merged

feat(types/oscript): ConstructorSymbol — отдельный тип для конструктора OScript-класса#3945
nixel2007 merged 1 commit into
developfrom
feature/oscript-constructor-symbol

Conversation

@nixel2007

@nixel2007 nixel2007 commented May 26, 2026

Copy link
Copy Markdown
Member

Summary

Новый <ИмяКласса>() теперь резолвится единообразно для manifest- и implicit-классов OneScript-библиотек:

  • класс с явным ПриСозданииОбъекта/OnObjectCreate → ссылка на конструктор-метод, go-to-def ведёт в тело конструктора, hover показывает constructor-стилевой блок с сигнатурой;
  • класс без явного конструктора → ссылка на ModuleSymbol .os-файла, hover всё равно constructor-стиля (Новый ИмяКласса());
  • конструктор стал отдельным ConstructorSymbol с собственным SymbolKind.Constructor, отдельным hover-builder'ом и иконкой в DocumentSymbol/WorkspaceSymbol.

Что внутри

Symbol tree

  • MethodSymbol → интерфейс. Конкретный класс переименован в RegularMethodSymbol. Общая структура вынесена в AbstractMethodSymbol (@SuperBuilder). Новый ConstructorSymbol.
  • SymbolTreeVisitor: visitMethodvisitRegularMethod + добавлен visitConstructor. AbstractSymbolTreeDiagnostic делегирует оба override'а в общий visitMethod(MethodSymbol) — существующие 6 диагностик не переписываются.
  • SymbolTree.getConstructor(): Optional<ConstructorSymbol> — типизированный аксессор.
  • MethodSymbolComputer строит ConstructorSymbol для процедуры с именем конструктора в ModuleType.OScriptClass. Имена в Methods.isOscriptClassConstructorName.

Резолв ссылок

  • ReferenceIndexFiller.tryRegisterLibraryClassReference: при наличии конструктора регистрирует addMethodCall, иначе — addModuleReference.
  • ReferenceIndex.isReferenceAccessible: ConstructorSymbol всегда accessible (по convention объявляется без Экспорт, но фактически доступен извне через Новый).
  • AnnotationReferenceFinder использует symbolTree.getConstructor(). Для фикстуры references/annotations/ добавлен lib.config, чтобы файлы регистрировались как OScriptClass.

Hover

  • OScriptClassConstructorRenderer — общий рендер constructor-стиля.
  • ConstructorSymbolMarkupContentBuilder — hover для ConstructorSymbol.
  • ModuleSymbolMarkupContentBuilder для ModuleType.OScriptClass делегирует в renderer.

Outline / workspace symbols

  • SymbolProvider.isSupported принимает SymbolKind.Constructor.
  • DocumentSymbolProvider отдаёт SymbolKind.Constructor через symbol.getSymbolKind().

Test plan

  • ./gradlew compileJava compileTestJava — ОК
  • ./gradlew javadoc — ОК (новые файлы без warnings)
  • Ключевые тесты прогнаны (MethodsTest, MethodSymbolComputerConstructorTest, MethodSymbolComputerTest, ImplicitLibraryClassNewExpressionReferenceTest, HoverProviderOScriptLibraryTest, DocumentSymbolProviderTest, SymbolProviderOScriptConstructorTest, AnnotationReferenceFinderTest, SymbolProviderTest) — зелёные
  • Полный ./gradlew test (известны спорадические сбои 3 semantictokens-тестов по исчерпанию inotify-лимита — инфраструктурное)
  • Ручная проверка на реальном winow workspace: hover Новый Поделка() и Новый ФабрикаЖелудей() — оба подробные, go-to-def ведёт на ПриСозданииОбъекта; иконка конструктора в outline

Summary by CodeRabbit

  • New Features
    • Added support for OneScript class constructors as distinct callable symbols in the language server.
    • Constructors now appear in symbol searches and document outlines with proper classification.
    • Hover information displays constructor-style signatures (e.g., Новый ClassName(...)).
    • Go-to-definition and reference resolution now correctly handle constructor references.

Review Change Stack

…ра OScript-класса

`Новый <ИмяКласса>()` теперь резолвится единообразно: для класса с явным
`ПриСозданииОбъекта`/`OnObjectCreate` go-to-def ведёт в тело конструктора, а
hover показывает constructor-стилевой блок с сигнатурой; для класса без
конструктора — ссылка в `ModuleSymbol` .os-файла, hover тот же constructor-стиля.

Symbol tree:
- `MethodSymbol` стал интерфейсом, `RegularMethodSymbol` — обычные методы/функции,
  `ConstructorSymbol` — `ПриСозданииОбъекта`/`OnObjectCreate` в OScript-классе.
- Общая структура полей вынесена в `AbstractMethodSymbol` (`@SuperBuilder`).
- `SymbolTreeVisitor`: `visitMethod` → `visitRegularMethod`, добавлен
  `visitConstructor`. В `AbstractSymbolTreeDiagnostic` оба override'а делегируют
  в общий `visitMethod(MethodSymbol)`-helper — существующие диагностики не
  переписываются.
- `SymbolTree.getConstructor(): Optional<ConstructorSymbol>` —
  типизированный аксессор.
- `MethodSymbolComputer` строит `ConstructorSymbol` для имени-конструктора в
  файле с `ModuleType.OScriptClass`; имена вынесены в
  `Methods.isOscriptClassConstructorName`.

Резолв ссылок:
- `ReferenceIndexFiller.tryRegisterLibraryClassReference`: при наличии
  `ConstructorSymbol` регистрируется `addMethodCall` на конструктор, иначе —
  старая `addModuleReference`.
- `ReferenceIndex.isReferenceAccessible`: конструктор OScript-класса всегда
  accessible (по convention объявляется без `Экспорт`, но фактически
  доступен извне через `Новый`).
- `AnnotationReferenceFinder` использует `symbolTree.getConstructor()`; для
  фикстуры `references/annotations/` добавлен `lib.config`, чтобы аннотации
  регистрировались как `OScriptClass`.

Hover:
- `OScriptClassConstructorRenderer` — общий рендер constructor-стиля
  (`Новый ИмяКласса(...)` + location + сигнатура/описание).
- `ConstructorSymbolMarkupContentBuilder` — hover для `ConstructorSymbol`.
- `ModuleSymbolMarkupContentBuilder` для `ModuleType.OScriptClass` делегирует
  в renderer (богатый hover для класса без явного конструктора).

Outline / workspace symbols:
- `SymbolProvider.isSupported` принимает `SymbolKind.Constructor`.
- `DocumentSymbolProvider` отдаёт `SymbolKind.Constructor` через
  `symbol.getSymbolKind()`.

Тесты:
- `MethodsTest`, `MethodSymbolComputerConstructorTest`,
  `ImplicitLibraryClassNewExpressionReferenceTest` (фикстура
  `oscript-libraries/internal-classes-test/`, autumn-mock),
  `HoverProviderOScriptLibraryTest` (+2 кейса с защитой от регресса
  hover-дубликата), `SymbolProviderOScriptConstructorTest`.
@nixel2007
nixel2007 requested review from Copilot and sfaqer May 26, 2026 10:01

Copilot AI 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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@coderabbitai

coderabbitai Bot commented May 26, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR refactors method symbol handling to distinguish OneScript class constructors from regular methods through a new type hierarchy. MethodSymbol becomes an interface, with abstract AbstractMethodSymbol providing shared implementation and concrete ConstructorSymbol and RegularMethodSymbol subclasses enabling LSP symbol kind differentiation. Updates span symbol generation, reference resolution, hover rendering, and LSP providers with full test coverage.

Changes

OneScript Constructor Symbol Refactoring

Layer / File(s) Summary
Symbol Type Hierarchy
src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java, AbstractMethodSymbol.java, ConstructorSymbol.java, RegularMethodSymbol.java
MethodSymbol refactored from concrete class to interface. New abstract AbstractMethodSymbol centralizes range/region computations and builder logic. Concrete ConstructorSymbol and RegularMethodSymbol extend it and override getSymbolKind() and accept(SymbolTreeVisitor) for LSP differentiation.
Constructor Detection and Symbol Creation
src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Methods.java, context/computer/MethodSymbolComputer.java
Methods.isOscriptClassConstructorName() utility validates OneScript constructor method names case-insensitively. MethodSymbolComputer.createMethodSymbol() branches on constructor detection: returns ConstructorSymbol for OneScript class constructors (via isOscriptClassConstructor helper requiring ModuleType.OScriptClass), otherwise RegularMethodSymbol. Removed Methods.getOscriptClassConstructor(SymbolTree) in favor of direct SymbolTree.getConstructor() access.
Symbol Tree and Visitor Pattern
src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java, SymbolTreeVisitor.java, diagnostics/AbstractSymbolTreeDiagnostic.java
SymbolTree adds lazy constructor field populated by first ConstructorSymbol in flattened tree. SymbolTreeVisitor replaces single visitMethod(MethodSymbol) with separate visitRegularMethod(RegularMethodSymbol) and visitConstructor(ConstructorSymbol) callbacks. AbstractSymbolTreeDiagnostic adds overriding stubs for both new visitor methods, both delegating to shared visitMethod child-traversal logic.
Reference Resolution and Index Updates
src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java, references/AnnotationReferenceFinder.java, ReferenceIndex.java, ReferenceIndexFiller.java, types/oscript/OScriptModuleMembersProvider.java, providers/SymbolProvider.java
VariableSymbolComputer accepts List<? extends MethodSymbol>. AnnotationReferenceFinder and ReferenceIndexFiller resolve constructors via symbolTree.getConstructor() instead of deprecated Methods helper. ReferenceIndex.isReferenceAccessible() treats ConstructorSymbol references as always accessible (bypassing export checks). OScriptModuleMembersProvider uses getConstructor() to skip/include constructors in member/constructor collection. SymbolProvider.isSupported() accepts both Method and Constructor symbol kinds.
LSP Hover and Display Support
src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/ModuleSymbolMarkupContentBuilder.java, ConstructorSymbolMarkupContentBuilder.java, OScriptClassConstructorRenderer.java
ModuleSymbolMarkupContentBuilder branches on ModuleType.OScriptClass to render constructor-style hover via OScriptClassConstructorRenderer.renderWithoutConstructor(). New ConstructorSymbolMarkupContentBuilder implements MarkupContentBuilder<ConstructorSymbol> and delegates to OScriptClassConstructorRenderer.render(). OScriptClassConstructorRenderer generates Markdown hover with Новый ClassName(params) signature, module/class description, and optional constructor purpose/parameters sections, resolving class name via OScriptLibraryIndex with .os-filename fallback.
Test Coverage
src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerConstructorTest.java, providers/HoverProviderOScriptLibraryTest.java, SymbolProviderOScriptConstructorTest.java, references/ImplicitLibraryClassNewExpressionReferenceTest.java, utils/MethodsTest.java
Four MethodSymbolComputerConstructorTest scenarios: .os exported/implicit classes create ConstructorSymbol, classes without constructor produce none, .bsl modules with same name produce RegularMethodSymbol. HoverProviderOScriptLibraryTest adds two tests for Новый expression hover with/without constructor. SymbolProviderOScriptConstructorTest validates workspace/document symbol filtering includes SymbolKind.Constructor. ImplicitLibraryClassNewExpressionReferenceTest covers index registration and reference resolution for Новый MyClass(...) with constructor-vs-module symbol targeting. MethodsTest validates case-insensitive constructor name matching.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • 1c-syntax/bsl-language-server#3710: Refactors ReferenceIndex.isReferenceAccessible() using new Reference.from() accessor; this PR adds constructor-specific early-return logic to the same method.
  • 1c-syntax/bsl-language-server#3364: Introduces AnnotationReferenceFinder and annotation symbol plumbing; this PR updates it to resolve constructors via the new SymbolTree.getConstructor() API.

Poem

🐰 Hop along, dear methods bold!
Once one class, now roles unfold—
Constructors bright in SymbolKind,
Regular friends left behind,
Visitors dance their type-dispatch,
References catch, hovers match!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.68% 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 and specifically describes the main change: introducing a ConstructorSymbol as a separate type for OneScript class constructors.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/oscript-constructor-symbol

Warning

Review ran into problems

🔥 Problems

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


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.

@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.

🧹 Nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java (1)

39-55: ⚡ Quick win

Add JavaDoc to the newly exposed interface methods.

Several public API methods are declared without JavaDoc, which makes the new interface contract harder to consume and maintain.

As per coding guidelines: "Write JavaDoc for public APIs, include comments for complex logic, and keep documentation up to date with code changes".

🤖 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/context/symbol/MethodSymbol.java`
around lines 39 - 55, The MethodSymbol interface exposes several public methods
without JavaDoc; add concise JavaDoc comments for each public API method in
MethodSymbol (getName, isFunction, isExport, isDeprecated, getParameters,
getDescription, getCompilerDirectiveKind, getAnnotations) describing purpose,
return values and any nullable/optional semantics; ensure `@return` tags for each
method, mention when Optional is empty, and note any side-effects or contract
expectations (e.g., immutability of returned lists) to satisfy project Javadoc
guidelines.
🤖 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.

Nitpick comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java`:
- Around line 39-55: The MethodSymbol interface exposes several public methods
without JavaDoc; add concise JavaDoc comments for each public API method in
MethodSymbol (getName, isFunction, isExport, isDeprecated, getParameters,
getDescription, getCompilerDirectiveKind, getAnnotations) describing purpose,
return values and any nullable/optional semantics; ensure `@return` tags for each
method, mention when Optional is empty, and note any side-effects or contract
expectations (e.g., immutability of returned lists) to satisfy project Javadoc
guidelines.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 47ea5885-7856-4d57-a3c2-3e3a0af3a857

📥 Commits

Reviewing files that changed from the base of the PR and between 3e052e3 and 7c18929.

⛔ Files ignored due to path filters (7)
  • src/test/resources/oscript-libraries/internal-classes-test/oscript_modules/internal-classes-lib/lib.config is excluded by !src/test/resources/**
  • src/test/resources/oscript-libraries/internal-classes-test/oscript_modules/internal-classes-lib/src/internal/Классы/InternalEntity.os is excluded by !src/test/resources/**
  • src/test/resources/oscript-libraries/internal-classes-test/oscript_modules/internal-classes-lib/src/internal/Классы/ВнутренняяСущность.os is excluded by !src/test/resources/**
  • src/test/resources/oscript-libraries/internal-classes-test/oscript_modules/internal-classes-lib/src/Классы/ClassWithoutCtor.os is excluded by !src/test/resources/**
  • src/test/resources/oscript-libraries/internal-classes-test/oscript_modules/internal-classes-lib/src/Классы/PublicEntity.os is excluded by !src/test/resources/**
  • src/test/resources/oscript-libraries/internal-classes-test/src/Классы/Caller.os is excluded by !src/test/resources/**
  • src/test/resources/references/annotations/lib.config is excluded by !src/test/resources/**
📒 Files selected for processing (23)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/AbstractMethodSymbol.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ConstructorSymbol.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegularMethodSymbol.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTreeVisitor.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSymbolTreeDiagnostic.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/ConstructorSymbolMarkupContentBuilder.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/ModuleSymbolMarkupContentBuilder.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/OScriptClassConstructorRenderer.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProvider.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/references/AnnotationReferenceFinder.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndex.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFiller.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/OScriptModuleMembersProvider.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Methods.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerConstructorTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/HoverProviderOScriptLibraryTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProviderOScriptConstructorTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ImplicitLibraryClassNewExpressionReferenceTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/MethodsTest.java

@sonarqubecloud

Copy link
Copy Markdown

@github-actions

github-actions Bot commented May 26, 2026

Copy link
Copy Markdown
Contributor

Test Results

 2 868 files  + 24   2 868 suites  +24   1h 16m 27s ⏱️ + 9m 12s
 2 491 tests + 28   2 491 ✅ + 28  0 💤 ±0  0 ❌ ±0 
14 946 runs  +168  14 946 ✅ +168  0 💤 ±0  0 ❌ ±0 

Results for commit 7c18929. ± Comparison against base commit 3e052e3.

♻️ This comment has been updated with latest results.

@nixel2007
nixel2007 merged commit bb74850 into develop May 26, 2026
47 of 48 checks passed
@nixel2007
nixel2007 deleted the feature/oscript-constructor-symbol branch May 26, 2026 11:00
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.

2 participants