Skip to content

fix #1675: возвращаемый тип ЗагрузитьСценарий()#1686

Merged
EvilBeaver merged 3 commits into
EvilBeaver:developfrom
Mr-Rm:v2/fix-1675
May 26, 2026
Merged

fix #1675: возвращаемый тип ЗагрузитьСценарий()#1686
EvilBeaver merged 3 commits into
EvilBeaver:developfrom
Mr-Rm:v2/fix-1675

Conversation

@Mr-Rm
Copy link
Copy Markdown
Collaborator

@Mr-Rm Mr-Rm commented May 26, 2026

  • ЗагрузитьСценарий теперь возвращает тот же тип, что и ЗагрузитьСценарийИзСтроки - который вернула AttachedScriptsFactory.Load*
  • результат исключения при ошибках компиляции вынесен в отдельную функцию, где добавляется информация о произошедшей ошибке

Summary by CodeRabbit

  • Bug Fixes

    • Standardized compilation error handling with clearer, bilingual messages and consistent exception wrapping.
  • Refactor

    • Script loading now returns a more specific script context type and consolidates external-context construction to remove duplication.
  • Tests

    • Added a test that loads a scenario into a declared local variable and verifies expected field data.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 26, 2026

📝 Walkthrough

Walkthrough

This PR standardizes compilation error handling across three script-loading methods (AttachScript, LoadScriptFromString, and LoadScript) by introducing a shared exception helper. The public LoadScript method's return type changes from IRuntimeContextInstance to UserScriptContextInstance. A new test validates that scenarios can be loaded into declared variables.

Changes

Script compilation error handling and LoadScript API change

Layer / File(s) Summary
Exception handling infrastructure
src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs
Updated using directives, adjusted a comment, and introduced a private ScriptCompilingException(Exception) helper that returns a RuntimeException built from BilingualString.Localize(...) and the caught exception message.
Loaders: context building and filtered-catch handling
src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs
Added CreateContextData(StructureImpl) to convert external contexts; AttachScript, LoadScriptFromString, and LoadScript now use filtered catches for SyntaxErrorException/CompilerException routed to ScriptCompilingException. LoadScript return type changed from IRuntimeContextInstance to UserScriptContextInstance.
Test coverage for LoadScript variable loading
tests/native-lib/test-native-use.os
Added test list entry and exported procedure ТестДолжен_ПроверитьПодключениеСценарияСОбъявленнойПеременной that loads ТестовыйСценарий.os into a declared variable and asserts Поле1 == 1.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hop through code with careful paws,
A helper stitches compile-time flaws,
LoadScript now returns a clearer name,
Contexts are built the very same,
Tests confirm the scenario's claim.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% 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.
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.
Title check ✅ Passed The pull request title directly addresses the main change: updating the return type of LoadScript() method to match LoadScriptFromString(), which is the primary focus of this changeset.

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

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

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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs (1)

76-97: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Inconsistent exception handling: first branch not wrapped.

Line 78 (externalContext == null branch) can also throw SyntaxErrorException or CompilerException but is not wrapped in the try-catch. This means compilation errors will be handled differently depending on whether externalContext is provided, which is inconsistent with AttachScript and LoadScript.

🐛 Proposed fix to wrap both branches
         var compiler = _engine.GetCompilerService();
-        if (externalContext == null)
-        {
-            return _engine.AttachedScriptsFactory.LoadFromString(compiler, code, process);
-        }
-        else
+        try
         {
-            var extData = new ExternalContextData();
-
-            foreach (var item in externalContext)
+            if (externalContext == null)
             {
-                extData.Add(item.Key.ToString()!, item.Value);
+                return _engine.AttachedScriptsFactory.LoadFromString(compiler, code, process);
             }
-
-            try
-            {
-                return _engine.AttachedScriptsFactory.LoadFromString(compiler, code, process, extData);
-            }
-            catch (Exception e) when (e is SyntaxErrorException || e is CompilerException)
+            else
             {
-                throw ScriptCompilingException(e);
+                var extData = new ExternalContextData();
+
+                foreach (var item in externalContext)
+                {
+                    extData.Add(item.Key.ToString()!, item.Value);
+                }
+
+                return _engine.AttachedScriptsFactory.LoadFromString(compiler, code, process, extData);
             }
         }
+        catch (Exception e) when (e is SyntaxErrorException || e is CompilerException)
+        {
+            throw ScriptCompilingException(e);
+        }
🤖 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.StandardLibrary/DynamicLoadingFunctions.cs` around lines 76 -
97, The null-branch return path using
_engine.AttachedScriptsFactory.LoadFromString(compiler, code, process) isn't
wrapped like the non-null branch, causing inconsistent handling of
SyntaxErrorException/CompilerException; refactor so both paths call
LoadFromString inside the same try/catch and rethrow via
ScriptCompilingException(e), e.g., prepare extData only when externalContext !=
null but invoke _engine.AttachedScriptsFactory.LoadFromString(...) inside a
single try block that catches (Exception e) when (e is SyntaxErrorException || e
is CompilerException) and throws ScriptCompilingException(e).
🤖 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.StandardLibrary/DynamicLoadingFunctions.cs`:
- Around line 181-186: The ScriptCompilingException helper currently drops the
original exception when wrapping, so update the
ScriptCompilingException(Exception e) method to call the RuntimeException
constructor overload that accepts an inner exception: build the localized
message (using BilingualString.Localize as before) and pass it as the first
argument and pass e as the second argument to RuntimeException so the original
exception/stack trace is preserved.

---

Outside diff comments:
In `@src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs`:
- Around line 76-97: The null-branch return path using
_engine.AttachedScriptsFactory.LoadFromString(compiler, code, process) isn't
wrapped like the non-null branch, causing inconsistent handling of
SyntaxErrorException/CompilerException; refactor so both paths call
LoadFromString inside the same try/catch and rethrow via
ScriptCompilingException(e), e.g., prepare extData only when externalContext !=
null but invoke _engine.AttachedScriptsFactory.LoadFromString(...) inside a
single try block that catches (Exception e) when (e is SyntaxErrorException || e
is CompilerException) and throws ScriptCompilingException(e).
🪄 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: 740ebbc4-0bd0-4806-a4bb-bec128ecee9b

📥 Commits

Reviewing files that changed from the base of the PR and between 17dae14 and 342a790.

📒 Files selected for processing (2)
  • src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs
  • tests/native-lib/test-native-use.os

Comment thread src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs
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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs (1)

178-182: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use a loader-agnostic compilation error message.

This helper is shared by AttachScript, LoadScriptFromString, and LoadScript, but the text still says "attached script". Compilation failures from ЗагрузитьСценарий* will therefore surface a misleading error.

Suggested fix
         private static RuntimeException ScriptCompilingException(Exception e)
         {
             return new RuntimeException(BilingualString.Localize(
-                "Ошибка компиляции подключаемого сценария:\n",
-                "Error compiling attached script:\n") + e.Message, e);
+                "Ошибка компиляции сценария:\n",
+                "Error compiling script:\n") + e.Message, e);
         }
🤖 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.StandardLibrary/DynamicLoadingFunctions.cs` around lines 178 -
182, The helper ScriptCompilingException currently hardcodes "attached script"
in its message which is misleading for
LoadScriptFromString/LoadScript/AttachScript consumers; change the localized
strings passed to BilingualString.Localize in ScriptCompilingException to a
loader-agnostic phrase such as "Ошибка компиляции сценария:\n" / "Error
compiling script:\n" so all callers (AttachScript, LoadScriptFromString,
LoadScript) receive a neutral error message while preserving the appended
e.Message and exception chaining.
🤖 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.

Outside diff comments:
In `@src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs`:
- Around line 178-182: The helper ScriptCompilingException currently hardcodes
"attached script" in its message which is misleading for
LoadScriptFromString/LoadScript/AttachScript consumers; change the localized
strings passed to BilingualString.Localize in ScriptCompilingException to a
loader-agnostic phrase such as "Ошибка компиляции сценария:\n" / "Error
compiling script:\n" so all callers (AttachScript, LoadScriptFromString,
LoadScript) receive a neutral error message while preserving the appended
e.Message and exception chaining.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 06b06c48-ac2a-4dd7-804b-f0bbdd2c6515

📥 Commits

Reviewing files that changed from the base of the PR and between 342a790 and 538ff04.

📒 Files selected for processing (1)
  • src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs (1)

179-183: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use a neutral compile-error prefix here.

This helper is shared by AttachScript, LoadScriptFromString, and LoadScript, but the localized text says "attached script". That makes load failures surface the wrong operation name to the user.

Proposed fix
         return new RuntimeException(BilingualString.Localize(
-                "Ошибка компиляции подключаемого сценария:\n",
-                "Error compiling attached script:\n") + e.Message, e);
+                "Ошибка компиляции сценария:\n",
+                "Error compiling script:\n") + e.Message, e);
🤖 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.StandardLibrary/DynamicLoadingFunctions.cs` around lines 179 -
183, The helper ScriptCompilingException uses a localized message that says
"attached script" which is incorrect for callers like AttachScript,
LoadScriptFromString, and LoadScript; change the localized prefix to a neutral
compile-error phrase (e.g., replace the bilingual strings "Ошибка компиляции
подключаемого сценария:\n" / "Error compiling attached script:\n" with neutral
alternatives such as "Ошибка компиляции сценария:\n" / "Error compiling
script:\n") so all callers receive a correct, operation-agnostic error message
while preserving the existing exception wrapping (return new
RuntimeException(..., e)).
🧹 Nitpick comments (1)
src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs (1)

71-73: ⚡ Quick win

Add explicit null guards for code and path.

These public script entry points still forward concrete string parameters straight into the engine. Script calls omit them as "", but direct CLR callers can still pass null, so it is better to fail fast here instead of depending on deeper validation.

Proposed fix
 public UserScriptContextInstance LoadScriptFromString(IBslProcess process,
     string code,
     StructureImpl externalContext = null)
 {
+    if (code == null)
+        throw new ArgumentNullException(nameof(code));
+
     var compiler = _engine.GetCompilerService();
     try
     {
         if (externalContext == null)
             return _engine.AttachedScriptsFactory.LoadFromString(compiler, code, process);
@@
 public UserScriptContextInstance LoadScript(IBslProcess process, string path, StructureImpl externalContext = null)
 {
+    if (path == null)
+        throw new ArgumentNullException(nameof(path));
+
     var compiler = _engine.GetCompilerService();
     try
     {
         if(externalContext == null)
             return _engine.AttachedScriptsFactory.LoadFromPath(compiler, path, process);
Based on learnings: in public script-exposed C# methods, omitted script arguments arrive as `""`, but direct calls may still pass `null`, so concrete string parameters should handle null explicitly.

Also applies to: 103-103

🤖 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.StandardLibrary/DynamicLoadingFunctions.cs` around lines 71 -
73, Add explicit null-guards for public string parameters so callers get fast,
clear failures: in LoadScriptFromString(IBslProcess process, string code,
StructureImpl externalContext = null) check if code is null and throw
ArgumentNullException(nameof(code)) before forwarding to the engine; do the same
for the analogous method that takes a path (e.g., LoadScriptFromPath(IBslProcess
process, string path, StructureImpl externalContext = null)) by checking path
for null and throwing ArgumentNullException(nameof(path)) so direct CLR callers
cannot pass null through to deeper validation.
🤖 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.

Outside diff comments:
In `@src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs`:
- Around line 179-183: The helper ScriptCompilingException uses a localized
message that says "attached script" which is incorrect for callers like
AttachScript, LoadScriptFromString, and LoadScript; change the localized prefix
to a neutral compile-error phrase (e.g., replace the bilingual strings "Ошибка
компиляции подключаемого сценария:\n" / "Error compiling attached script:\n"
with neutral alternatives such as "Ошибка компиляции сценария:\n" / "Error
compiling script:\n") so all callers receive a correct, operation-agnostic error
message while preserving the existing exception wrapping (return new
RuntimeException(..., e)).

---

Nitpick comments:
In `@src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs`:
- Around line 71-73: Add explicit null-guards for public string parameters so
callers get fast, clear failures: in LoadScriptFromString(IBslProcess process,
string code, StructureImpl externalContext = null) check if code is null and
throw ArgumentNullException(nameof(code)) before forwarding to the engine; do
the same for the analogous method that takes a path (e.g.,
LoadScriptFromPath(IBslProcess process, string path, StructureImpl
externalContext = null)) by checking path for null and throwing
ArgumentNullException(nameof(path)) so direct CLR callers cannot pass null
through to deeper validation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4c5000e6-9538-48f7-81d7-34e65ccd4abe

📥 Commits

Reviewing files that changed from the base of the PR and between 538ff04 and 9d10d7d.

📒 Files selected for processing (1)
  • src/OneScript.StandardLibrary/DynamicLoadingFunctions.cs

@Mr-Rm
Copy link
Copy Markdown
Collaborator Author

Mr-Rm commented May 26, 2026

Не исправлено:

  • ошибки System.IO.* как Внешнее исключение
  • несогласованность сигнатур
    AttachedScriptsFactory.LoadFromString(compiler, code, process, extData); и AttachedScriptsFactory.LoadFromPath(compiler, path, extData, process);

@Mr-Rm Mr-Rm changed the title [WIP] fix #1675: возвращаемый тип ЗагрузитьСценарий() fix #1675: возвращаемый тип ЗагрузитьСценарий() May 26, 2026
@EvilBeaver EvilBeaver merged commit 3c3984c into EvilBeaver:develop May 26, 2026
2 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.

2 participants