Skip to content

[WIP] Делегаты в native-режиме#1697

Open
dmpas wants to merge 5 commits into
EvilBeaver:developfrom
dmpas:feature/native-delegate-call-1531
Open

[WIP] Делегаты в native-режиме#1697
dmpas wants to merge 5 commits into
EvilBeaver:developfrom
dmpas:feature/native-delegate-call-1531

Conversation

@dmpas
Copy link
Copy Markdown
Collaborator

@dmpas dmpas commented Jun 2, 2026

Summary by CodeRabbit

  • Bug Fixes

    • Improved runtime validation for method and delegate calls — now explicitly detects and reports too many or too few arguments.
  • New Features

    • Added a delegate execution API that unwraps reference results and normalizes null returns.
  • Tests

    • Added cross-mode tests verifying delegate invocation and parameter-count behavior; updated a documentation conversion test expectation.

@dmpas dmpas added the native Компиляция в CLR в движке 2.0 label Jun 2, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 2, 2026

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0977a3b2-1438-4390-abbf-d3560f2e12cd

📥 Commits

Reviewing files that changed from the base of the PR and between dfb0e87 and b534a43.

📒 Files selected for processing (1)
  • tests/cross-delegate-native.os
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/cross-delegate-native.os

📝 Walkthrough

Walkthrough

Adds explicit argument-count validation in delegate invocation paths, a public Execute context method on DelegateAction, integration tests for stack/native delegate parameter handling, and a small test expectation adjustment for XML doc conversion.

Changes

Delegate Argument Validation and Execution

Layer / File(s) Summary
Argument count validation in invoke contexts
src/OneScript.Native/Runtime/CallableMethod.cs, src/ScriptEngine/Machine/MachineInstance.cs
CallableMethod.Invoke and MachineInstance.SetExecutionFrame now validate argument counts, throwing TooManyArgumentsPassed when args exceed parameters and TooFewArgumentsPassed when non-defaulted parameters lack values.
Delegate Execute context method
src/OneScript.StandardLibrary/DelegateAction.cs
A new public Execute(IBslProcess, params BslValue[]) method invokes the stored delegate, unwraps IValueReference results, and ensures a non-null BslValue return via ValueFactory.Create() when needed.
Stack and native delegate integration tests
tests/cross-delegate-stack.os, tests/cross-delegate-native.os
Two test modules register tests, dynamically create delegates, verify execution with correct parameters, and assert that too few or too many parameters throw exceptions for both #stack and #native delegates.
Test expectation update
src/Tests/DocumenterTests/XmlDocConversionTest.cs
Updated expected string in TestConversionOfTextBlock so КонецЦикла; appears with the correct line separation in the converted output.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Suggested reviewers

  • EvilBeaver

"🐰
I counted params with careful paws,
Threw errors where they give me pause.
Stack or native, tests in line,
Delegates now behave just fine.
Hop, compile, and then applause!"

🚥 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 title '[WIP] Делегаты в native-режиме' accurately describes the main change: implementing delegate support in native mode. It is concise and clearly conveys the primary objective of the changeset.
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

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.

Copy link
Copy Markdown
Contributor

@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

🧹 Nitpick comments (1)
tests/cross-delegate-stack.os (1)

1-100: 💤 Low value

Consider extracting shared test logic to reduce duplication.

This file is nearly identical to cross-delegate-native.os (only differing in the #stack directive at line 1). While test isolation may justify the duplication, consider whether the shared logic (lines 10-99) could be extracted to a common module to improve maintainability.

If the #stack directive must apply to the entire test module for correct behavior, the current duplication is acceptable.

🤖 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 `@tests/cross-delegate-stack.os` around lines 1 - 100, The test file duplicates
almost all logic from the native variant; extract the shared test functions
(ПолучитьСписокТестов, ТестДолжен_ВыполнитьДействиеОбъектаТеста,
ТестДолжен_ПроверитьКоличествоПараметров and ТестовыйДелегат) into a single
reusable module (e.g., ОбщиеТесты) that both cross-delegate-stack.os and
cross-delegate-native.os can include or call, leaving only the module-specific
directives and thin wrappers (the exported wrapper procedures like
ТестДолжен_ВыполнитьДействиеОбъектаТеста_Стэковый / _Родной and
ТестДолжен_ПроверитьКоличествоПараметров_Стэковый / _Родной) in each file; if
the `#stack` directive must apply to the whole file, keep that directive in
cross-delegate-stack.os and only move function bodies into the shared module
while retaining the wrapper exports in the original file so behavior and test
isolation remain unchanged.
🤖 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/OneScript.Native/Runtime/CallableMethod.cs`:
- Around line 46-54: The check in CallableMethod.Invoke (or wherever
CallableMethod.cs validates arguments) incorrectly throws
RuntimeException.TooFewArgumentsPassed when args.Length <
_method.GetBslParameters().Length without considering parameters that have
defaults; update the logic that compares _method.GetBslParameters() to args to
iterate the trailing/missing parameters and allow omitted ones that have
paramDef.HasDefaultValue (same approach as MachineInstance.SetExecutionFrame
uses) instead of immediately throwing, so only throw TooFewArgumentsPassed when
a missing parameter lacks HasDefaultValue.

---

Nitpick comments:
In `@tests/cross-delegate-stack.os`:
- Around line 1-100: The test file duplicates almost all logic from the native
variant; extract the shared test functions (ПолучитьСписокТестов,
ТестДолжен_ВыполнитьДействиеОбъектаТеста,
ТестДолжен_ПроверитьКоличествоПараметров and ТестовыйДелегат) into a single
reusable module (e.g., ОбщиеТесты) that both cross-delegate-stack.os and
cross-delegate-native.os can include or call, leaving only the module-specific
directives and thin wrappers (the exported wrapper procedures like
ТестДолжен_ВыполнитьДействиеОбъектаТеста_Стэковый / _Родной and
ТестДолжен_ПроверитьКоличествоПараметров_Стэковый / _Родной) in each file; if
the `#stack` directive must apply to the whole file, keep that directive in
cross-delegate-stack.os and only move function bodies into the shared module
while retaining the wrapper exports in the original file so behavior and test
isolation remain unchanged.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: b369ce19-1084-4e00-9945-fe7fb56b030f

📥 Commits

Reviewing files that changed from the base of the PR and between 01167fe and dfb0e87.

📒 Files selected for processing (6)
  • src/OneScript.Native/Runtime/CallableMethod.cs
  • src/OneScript.StandardLibrary/DelegateAction.cs
  • src/ScriptEngine/Machine/MachineInstance.cs
  • src/Tests/DocumenterTests/XmlDocConversionTest.cs
  • tests/cross-delegate-native.os
  • tests/cross-delegate-stack.os

Comment on lines +46 to +54
if (_method.GetBslParameters().Length < args.Length)
{
throw RuntimeException.TooManyArgumentsPassed();
}
if (_method.GetBslParameters().Length > args.Length)
{
// TODO: значения параметров по-умолчанию?
throw RuntimeException.TooFewArgumentsPassed();
}
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 | 🔴 Critical | ⚡ Quick win

Missing default-parameter handling causes incorrect TooFewArgumentsPassed exception.

Lines 50-53 throw TooFewArgumentsPassed() whenever args.Length < parameters.Length, but this ignores parameters with default values. A caller passing fewer arguments than the total parameter count is valid when the omitted parameters have defaults.

MachineInstance.SetExecutionFrame (lines 175-184 in the other file) correctly checks paramDef.HasDefaultValue before throwing TooFewArgumentsPassed(). This code must do the same, otherwise delegate invocations of methods with optional parameters will fail.

🔧 Proposed fix
 if (_method.GetBslParameters().Length < args.Length)
 {
     throw RuntimeException.TooManyArgumentsPassed();
 }
-if (_method.GetBslParameters().Length > args.Length)
+
+var parameters = _method.GetBslParameters();
+for (int i = args.Length; i < parameters.Length; i++)
 {
-    // TODO: значения параметров по-умолчанию?
-    throw RuntimeException.TooFewArgumentsPassed();
+    if (!parameters[i].HasDefaultValue)
+    {
+        throw RuntimeException.TooFewArgumentsPassed();
+    }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (_method.GetBslParameters().Length < args.Length)
{
throw RuntimeException.TooManyArgumentsPassed();
}
if (_method.GetBslParameters().Length > args.Length)
{
// TODO: значения параметров по-умолчанию?
throw RuntimeException.TooFewArgumentsPassed();
}
if (_method.GetBslParameters().Length < args.Length)
{
throw RuntimeException.TooManyArgumentsPassed();
}
var parameters = _method.GetBslParameters();
for (int i = args.Length; i < parameters.Length; i++)
{
if (!parameters[i].HasDefaultValue)
{
throw RuntimeException.TooFewArgumentsPassed();
}
}
🤖 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/OneScript.Native/Runtime/CallableMethod.cs` around lines 46 - 54, The
check in CallableMethod.Invoke (or wherever CallableMethod.cs validates
arguments) incorrectly throws RuntimeException.TooFewArgumentsPassed when
args.Length < _method.GetBslParameters().Length without considering parameters
that have defaults; update the logic that compares _method.GetBslParameters() to
args to iterate the trailing/missing parameters and allow omitted ones that have
paramDef.HasDefaultValue (same approach as MachineInstance.SetExecutionFrame
uses) instead of immediately throwing, so only throw TooFewArgumentsPassed when
a missing parameter lacks HasDefaultValue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

native Компиляция в CLR в движке 2.0

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant