Skip to content

fix #1663: клонирование значений многомерного массива +тест#1664

Open
Mr-Rm wants to merge 4 commits intoEvilBeaver:developfrom
Mr-Rm:v2/fix-1663
Open

fix #1663: клонирование значений многомерного массива +тест#1664
Mr-Rm wants to merge 4 commits intoEvilBeaver:developfrom
Mr-Rm:v2/fix-1663

Conversation

@Mr-Rm
Copy link
Copy Markdown
Collaborator

@Mr-Rm Mr-Rm commented Apr 4, 2026

Исправлено клонирование вложенных массивов при создании массива размерности > 2.
Значения во внешнем массиве не перекрываются при присваивании.
Ошибочные значения размерностей проверяются начиная с первой, а не с последней.

Summary by CodeRabbit

  • Bug Fixes
    • Improved array behavior: faster preallocated arrays, simpler search semantics, more reliable deep-copying of nested arrays, and stricter validation/error handling for array dimensions.
  • Tests
    • Added tests covering array search, multi-dimensional array creation, nested writes/reads, and dimension-related error handling.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 4, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7a4d25a5-4bfe-48ed-b0f5-e0d22f7cc2df

📥 Commits

Reviewing files that changed from the base of the PR and between 24a9f27 and dedad20.

📒 Files selected for processing (5)
  • src/OneScript.StandardLibrary/Collections/ArrayImpl.cs
  • src/OneScript.StandardLibrary/Collections/ValueTable/ValueTable.cs
  • src/OneScript.StandardLibrary/Collections/ValueTree/ValueTreeRowCollection.cs
  • src/OneScript.StandardLibrary/SystemEnvironmentContext.cs
  • src/OneScript.StandardLibrary/Tasks/BackgroundTasksManager.cs
✅ Files skipped from review due to trivial changes (3)
  • src/OneScript.StandardLibrary/Collections/ValueTable/ValueTable.cs
  • src/OneScript.StandardLibrary/SystemEnvironmentContext.cs
  • src/OneScript.StandardLibrary/Collections/ValueTree/ValueTreeRowCollection.cs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/OneScript.StandardLibrary/Collections/ArrayImpl.cs

📝 Walkthrough

Walkthrough

Refactors ArrayImpl: adds a public presized constructor, simplifies null handling in Add/Insert/Find, replaces FillArray with CreateArray, changes CloneArray to pre-size and deep-clone nested arrays, rewrites multi-dimensional Constructor validation and build logic, and adds unit tests for array behaviors.

Changes

Cohort / File(s) Summary
Array implementation
src/OneScript.StandardLibrary/Collections/ArrayImpl.cs
Added public ArrayImpl(int capacity); simplified Add/Insert/Find null/default handling; replaced FillArray with CreateArray(int bound); CloneArray now pre-sizes and deep-clones nested ArrayImpl elements; reworked multi-dimensional Constructor(IValue[] dimensions) with forward validation and single base-array creation plus reverse wrapping.
Value collections – preallocation tweaks
src/OneScript.StandardLibrary/Collections/ValueTable/ValueTable.cs, src/OneScript.StandardLibrary/Collections/ValueTree/ValueTreeRowCollection.cs
UnloadColumn methods now preallocate returned ArrayImpl with _rows.Count capacity instead of empty construction.
System environment
src/OneScript.StandardLibrary/SystemEnvironmentContext.cs
GetLogicalDrives now preallocates the temporary ArrayImpl with known data.Length capacity.
Background tasks
src/OneScript.StandardLibrary/Tasks/BackgroundTasksManager.cs
GetBackgroundJobs now constructs ArrayImpl from _tasks enumerable directly instead of using _tasks.ToArray() snapshot (changes snapshot vs live enumeration semantics).
Tests
tests/array.os
Added test module exporting ПолучитьСписокТестов and four exported tests: search in array, 4‑dimensional array creation and sizes, 3‑D array writes/reads (including undefined cells), and error handling for invalid dimensions.

Sequence Diagram(s)

(omitted)

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested reviewers

  • EvilBeaver

Poem

🐇 I sized the nests and lined each row,

I cloned the tunnels where the cold winds blow,
I hopped through dims both shallow and deep,
I left some spots undefined to keep,
🥕 Tests now hum — I twitch, then go to sleep.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly addresses the main issue: it references the fixed issue number (#1663) and clearly describes the primary change—deep cloning of multi-dimensional array values and adding tests.

✏️ 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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/OneScript.StandardLibrary/Collections/ArrayImpl.cs`:
- Around line 204-223: Add a guard at the start of Constructor(IValue[]
dimensions) to handle null or empty input: check if dimensions is null or
dimensions.Length == 0 and throw an appropriate RuntimeException (e.g., a
missing/invalid argument count error) before any access to dimensions[0] or
dimensions[^1]; ensure this check comes before the existing special-case for
FixedArrayImpl and before the for-loop so subsequent uses (the null/type checks,
the AsNumber() calls, computing bound, and calling new ArrayImpl(...) /
FillArray(...)) cannot throw NullReferenceException or IndexOutOfRangeException.
🪄 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: 94e5e234-0f1d-40bb-acf7-7b726525542f

📥 Commits

Reviewing files that changed from the base of the PR and between 6858bd0 and 9da9308.

📒 Files selected for processing (2)
  • src/OneScript.StandardLibrary/Collections/ArrayImpl.cs
  • tests/array.os

Comment on lines +204 to +223
public static ArrayImpl Constructor(IValue[] dimensions)
{
if (dimensions.Length == 1 && dimensions[0] is FixedArrayImpl fa)
{
return Constructor(fa);
{
return Constructor(fa);
}
ArrayImpl cloneable = null;
for (int dim = dimensions.Length - 1; dim >= 0; dim--)

// fail fast
for (int dim = 0; dim < dimensions.Length; dim++)
{
if (dimensions[dim] == null)
throw RuntimeException.InvalidNthArgumentType(dim + 1);

int bound = (int)dimensions[dim].AsNumber();
if (bound <= 0)
throw RuntimeException.InvalidNthArgumentType(dim + 1);

if ((int)dimensions[dim].AsNumber() <= 0)
throw RuntimeException.InvalidNthArgumentValue(dim + 1);

var newInst = new ArrayImpl();
FillArray(newInst, bound);
if(cloneable != null)
{
for (int i = 0; i < bound; i++)
{
newInst._values[i] = CloneArray(cloneable);
}
}
cloneable = newInst;

}

int bound = (int)dimensions[^1].AsNumber();
var newInst = new ArrayImpl(bound);
FillArray(newInst, bound);
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 | 🟡 Minor

Guard Constructor(IValue[] dimensions) against null/empty input.

Line 206 and Line 221 assume dimensions is non-null and non-empty. A direct call with null or Array.Empty<IValue>() currently leaks NullReferenceException / IndexOutOfRangeException from a public entry point instead of handling the case intentionally.

🛡️ Proposed fix
 [ScriptConstructor(Name = "По количеству элементов")]
 public static ArrayImpl Constructor(IValue[] dimensions)
 {
+    if (dimensions == null)
+        throw new ArgumentNullException(nameof(dimensions));
+    if (dimensions.Length == 0)
+        return Constructor();
+
     if (dimensions.Length == 1 && dimensions[0] is FixedArrayImpl fa)
     { 
             return Constructor(fa);
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/OneScript.StandardLibrary/Collections/ArrayImpl.cs` around lines 204 -
223, Add a guard at the start of Constructor(IValue[] dimensions) to handle null
or empty input: check if dimensions is null or dimensions.Length == 0 and throw
an appropriate RuntimeException (e.g., a missing/invalid argument count error)
before any access to dimensions[0] or dimensions[^1]; ensure this check comes
before the existing special-case for FixedArrayImpl and before the for-loop so
subsequent uses (the null/type checks, the AsNumber() calls, computing bound,
and calling new ArrayImpl(...) / FillArray(...)) cannot throw
NullReferenceException or IndexOutOfRangeException.

@dmpas dmpas self-requested a review April 5, 2026 08:15
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.

♻️ Duplicate comments (1)
src/OneScript.StandardLibrary/Collections/ArrayImpl.cs (1)

192-194: ⚠️ Potential issue | 🟡 Minor

Guard Constructor(IValue[] dimensions) against null.

The empty-array case is fine now, but direct C# calls with null still blow up on Line 194 via dimensions.Length. Add an explicit check so this public entry point fails intentionally instead of leaking NullReferenceException.

🛡️ Proposed fix
 [ScriptConstructor(Name = "По количеству элементов")]
 public static ArrayImpl Constructor(IValue[] dimensions)
 {
+    if (dimensions == null)
+        throw new System.ArgumentNullException(nameof(dimensions));
+
     if (dimensions.Length == 1 && dimensions[0] is FixedArrayImpl fa)
     { 
             return Constructor(fa);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/OneScript.StandardLibrary/Collections/ArrayImpl.cs` around lines 192 -
194, The public static ArrayImpl Constructor(IValue[] dimensions) currently
dereferences dimensions without guarding for null; add an explicit null check at
the start of the Constructor method (the ArrayImpl.Constructor(IValue[]
dimensions) entry point) and throw a clear exception (e.g.,
ArgumentNullException for "dimensions") so callers receive an intentional,
descriptive failure instead of a NullReferenceException.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/OneScript.StandardLibrary/Collections/ArrayImpl.cs`:
- Around line 192-194: The public static ArrayImpl Constructor(IValue[]
dimensions) currently dereferences dimensions without guarding for null; add an
explicit null check at the start of the Constructor method (the
ArrayImpl.Constructor(IValue[] dimensions) entry point) and throw a clear
exception (e.g., ArgumentNullException for "dimensions") so callers receive an
intentional, descriptive failure instead of a NullReferenceException.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 592b1f66-8c3f-4e72-a73f-b8b20ade69d7

📥 Commits

Reviewing files that changed from the base of the PR and between 9da9308 and f426410.

📒 Files selected for processing (2)
  • src/OneScript.StandardLibrary/Collections/ArrayImpl.cs
  • tests/array.os
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/array.os

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.

♻️ Duplicate comments (1)
src/OneScript.StandardLibrary/Collections/ArrayImpl.cs (1)

244-248: ⚠️ Potential issue | 🟡 Minor

Guard Constructor(IValue[] dimensions) against null.

Line 246 still dereferences dimensions before any guard, so a direct C# call with null leaks NullReferenceException from a public entry point.

🛡️ Suggested change
         public static ArrayImpl Constructor(IValue[] dimensions)
         {
+            if (dimensions == null)
+                throw new System.ArgumentNullException(nameof(dimensions));
+            if (dimensions.Length == 0)
+                return Constructor();
+
             if (dimensions.Length == 1 && dimensions[0] is FixedArrayImpl fa)
             { 
                     return Constructor(fa);
             }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/OneScript.StandardLibrary/Collections/ArrayImpl.cs` around lines 244 -
248, The public static method Constructor(IValue[] dimensions) currently
dereferences dimensions before validating it; add a null guard at the very start
of Constructor(IValue[] dimensions) (before checking dimensions.Length or
pattern-matching to FixedArrayImpl) and throw an
ArgumentNullException(nameof(dimensions)) (or otherwise handle null consistently
with the library's API) so callers passing null get a clear, intentional
exception instead of a leaked NullReferenceException; ensure the FixedArrayImpl
pattern match (fa) remains after the guard.
🧹 Nitpick comments (1)
src/OneScript.StandardLibrary/Collections/ArrayImpl.cs (1)

33-36: Keep the capacity-only constructor non-public.

new ArrayImpl(3) reads like a sized-array constructor to C# callers, but it only reserves capacity and leaves Count() at 0. If this overload exists only for CreateArray and CloneArray, make it private or internal.

♻️ Suggested change
-        public ArrayImpl(int size)
+        private ArrayImpl(int size)
         {
             _values = new List<IValue>(size);
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/OneScript.StandardLibrary/Collections/ArrayImpl.cs` around lines 33 - 36,
The public ArrayImpl(int size) constructor exposes a capacity-only ctor that
leaves Count() at 0; change its accessibility to non-public (make the
ArrayImpl(int size) constructor private or internal) so C# callers can't mistake
it for a sized-array constructor, and update or confirm callers (e.g.,
CreateArray and CloneArray) still compile and reference this non-public ctor;
keep the signature and behavior unchanged except for the accessibility modifier.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/OneScript.StandardLibrary/Collections/ArrayImpl.cs`:
- Around line 244-248: The public static method Constructor(IValue[] dimensions)
currently dereferences dimensions before validating it; add a null guard at the
very start of Constructor(IValue[] dimensions) (before checking
dimensions.Length or pattern-matching to FixedArrayImpl) and throw an
ArgumentNullException(nameof(dimensions)) (or otherwise handle null consistently
with the library's API) so callers passing null get a clear, intentional
exception instead of a leaked NullReferenceException; ensure the FixedArrayImpl
pattern match (fa) remains after the guard.

---

Nitpick comments:
In `@src/OneScript.StandardLibrary/Collections/ArrayImpl.cs`:
- Around line 33-36: The public ArrayImpl(int size) constructor exposes a
capacity-only ctor that leaves Count() at 0; change its accessibility to
non-public (make the ArrayImpl(int size) constructor private or internal) so C#
callers can't mistake it for a sized-array constructor, and update or confirm
callers (e.g., CreateArray and CloneArray) still compile and reference this
non-public ctor; keep the signature and behavior unchanged except for the
accessibility modifier.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9dd8c8ae-71d4-4052-98ae-4a4bbfe1faee

📥 Commits

Reviewing files that changed from the base of the PR and between f426410 and 24a9f27.

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

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