Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ backlog in [GitHub issues](https://github.com/Ambiguous-Interactive/NovaSharp/is

## Now

1. Fix uninitialized locals reading generic-loop iterator state across Lua 5.1–5.5
in [#164](https://github.com/Ambiguous-Interactive/NovaSharp/issues/164).
1. Advance Phase A5 call paths in
[#108](https://github.com/Ambiguous-Interactive/NovaSharp/issues/108):
- Migrate each remaining legacy CoreLib registration in its own scoped change:
Expand Down Expand Up @@ -77,7 +79,7 @@ backlog in [GitHub issues](https://github.com/Ambiguous-Interactive/NovaSharp/is
[optional-argument validation](https://github.com/Ambiguous-Interactive/NovaSharp/issues/125),
[residual number/string parity nits](https://github.com/Ambiguous-Interactive/NovaSharp/issues/138),
[table library exports](https://github.com/Ambiguous-Interactive/NovaSharp/issues/159),
[table.insert arity and results](https://github.com/Ambiguous-Interactive/NovaSharp/issues/160),
[table insert metamethod behavior](https://github.com/Ambiguous-Interactive/NovaSharp/issues/162),
other error formats, [Lua 5.5 const loop-variable enforcement](https://github.com/Ambiguous-Interactive/NovaSharp/issues/130),
`__gc`, Lua 5.4 garbage collector options, version-migration docs, and explicit
compatibility-version matrix coverage; retain the
Expand Down
3 changes: 3 additions & 0 deletions docs/lua51-stdlib-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -869,6 +869,9 @@ Inserts element `value` at position `pos` in `table`, shifting up other elements

Default for `pos` is `#table + 1`, so `table.insert(t, x)` inserts at the end.

Both forms return zero values. In `table.insert(t, pos, nil)`, the third
argument is the value to insert and the second argument is the position.

**Examples:**

```lua
Expand Down
67 changes: 67 additions & 0 deletions progress/session-192-table-insert-arity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Session 192 — Lua table insertion arity

The session advanced [#160](https://github.com/Ambiguous-Interactive/NovaSharp/issues/160).
Both forms of Lua `table.insert` return zero values. The normalized argument
count selects append or positional insertion, so explicit nil and final
expressions yielding zero or multiple values retain their Lua semantics.
Wrong arity fails before the insertion. Lua 5.1 uses the raw length and allows
positions outside the sequence. Later profiles validate the position after
evaluating length. A sparse shift visits live entries when the span of shifted keys exceeds the
table's entry count.

The initial main revision was `1b5212dd`. Tests, CSharpier, Benchmarks, and the
Pages deployment were green. The table change used main at `b63cded4`, after
the green PyYAML, ReportGenerator, and markdown-it-py pull requests
[#152](https://github.com/Ambiguous-Interactive/NovaSharp/pull/152),
[#149](https://github.com/Ambiguous-Interactive/NovaSharp/pull/149), and
[#147](https://github.com/Ambiguous-Interactive/NovaSharp/pull/147) merged.

## Evidence

- `./scripts/test/quick.sh InsertUsesArgumentCountAndReturnsNoValues` failed
all five profile cases on the baseline at the append result-count assertion.
The same assertion passed on PUC Lua 5.1.5, 5.2.4, 5.3.6, 5.4.4, and 5.5.0.
- The [Lua 5.1 implementation](https://www.lua.org/source/5.1/ltablib.c.html)
and [Lua 5.2 implementation](https://www.lua.org/source/5.2/ltablib.c.html)
established where bounds enforcement starts. The independent comparison
identified Lua 5.1 truncation toward zero for negative fractions and the
profile difference in string-to-position conversion at embedded NUL.
- The paired regression covers argument expansion, explicit nil, wrong arity
without mutation, length evaluation order, numeric string coercion,
positional bounds, and overlapping sparse Lua 5.1 shifts. Regenerating the
corpus adds three comparable snippets to every profile and expands the existing
length fixture to all five profiles.
- Hosted review reproduced a valid append at key -1 when `__len` returns -2.
The new regression failed in Lua 5.2–5.5 on the initial PR revision. It checks
both length operands, numeric conversion errors, and index wrapping at the
Lua 5.2 and Lua 5.3+ integer widths. The review fix was tested with .NET SDK
10.0.404 on main `e2d2c73`.
- A second hosted review found that positional insertion still narrowed the
length to 32 bits. The new positional fixture failed in four profiles on
that revision. It verifies shared length conversion, exact wide keys, shifts
across sparse intervals, and the unsigned Lua 5.4 and 5.5 position bounds.
The final candidate used main `0c0ed10` with all dependency changes.
- The quick build, 231 focused TableModule tests, 15,744 full quick tests,
CSharpier, pre-commit, and enforced full corpus comparisons with PUC Lua 5.1
through 5.5 passed. The pre-commit Docker-only devcontainer check and Unity
player execution were unavailable. The existing callback registration and
preservation attribute cover the implementation entry point.

## Issue triage

The initial paginated inventory contained 31 open issues. The gameplay and Lua
caller order was 160, 130, 125, 159, 138, 124, and 122. The runtime order was
108, 95, 93, 92, 118, 105, 87, 88, 104, and 103. The tooling and maintenance
order was 113, 114, 135, 119, 94, 154, 98, 99, 106, 84, 102, 85, 121, and 157.

A matched-reference probe also reproduced uninitialized generic-loop locals
reading iterator state on the base. It is now first in the execution queue
[#164](https://github.com/Ambiguous-Interactive/NovaSharp/issues/164).
Table insertion's indexed access and proxy differences are tracked in
[#162](https://github.com/Ambiguous-Interactive/NovaSharp/issues/162).
The remaining local session 189 guidance is tracked in
[#163](https://github.com/Ambiguous-Interactive/NovaSharp/issues/163).
The Lua error ratchet depends on the checkout directory for two file-loading
fixtures. The comparison succeeded when launched from the primary checkout.
The normalization fix is tracked in
[#165](https://github.com/Ambiguous-Interactive/NovaSharp/issues/165).
224 changes: 198 additions & 26 deletions src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/TableModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -296,55 +296,227 @@ CallbackArgumentsView args
nameof(executionContext)
);

LuaValue vlist = args.AsType(0, "table.insert", DataType.Table, false);
LuaValue vpos = args[1];
LuaValue vvalue = args[2];

if (args.Count > 3)
LuaValue tableValue = args.AsType(0, "table.insert", DataType.Table);
Table list = tableValue.Table;
LuaCompatibilityVersion version = LuaVersionDefaults.Resolve(
executionContext.Script.CompatibilityVersion
);
long end = GetInsertEnd(executionContext, tableValue, version);
if (args.Count == 2)
{
throw new ScriptRuntimeException("wrong number of arguments to 'insert'");
SetInsertValue(list, end, args[1]);
return LuaValue.Void;
}

int len = GetTableLength(executionContext, vlist);
Table list = vlist.Table;
LuaCompatibilityVersion version = executionContext.Script.CompatibilityVersion;

if (vvalue.IsNil)
if (args.Count != 3)
{
vvalue = vpos;
vpos = LuaValue.FromNumber(len + 1);
throw new ScriptRuntimeException("wrong number of arguments to 'insert'");
}

if (vpos.Type != DataType.Number)
LuaValue positionArgument = args[1];
LuaNumber? number = GetInsertNumber(positionArgument, version);
if (!number.HasValue)
{
throw ScriptRuntimeException.BadArgument(
1,
"table.insert",
DataType.Number,
vpos.Type,
positionArgument.Type,
false
);
}

// Lua 5.3+: require integer representation; Lua 5.1/5.2: silently truncate
int pos = (int)
Utilities.LuaNumberHelpers.ToLongWithValidation(version, vpos, "insert", 2);

if (pos > len + 1 || pos < 1)
LuaNumber numericPosition = number.Value;
long position;
if (version <= LuaCompatibilityVersion.Lua52)
{
throw new ScriptRuntimeException(
"bad argument #2 to 'insert' (position out of bounds)"
position = NarrowInsertNumber(numericPosition);
}
else
{
position = Utilities.LuaNumberHelpers.ToLongWithValidation(
version,
LuaValue.NewNumber(numericPosition),
"insert",
2
);
}

for (int i = len; i >= pos; i--)
// Lua 5.4 and 5.5 compare pos - 1 and end as unsigned Lua integers.
bool outOfBounds =
version >= LuaCompatibilityVersion.Lua54
? unchecked((ulong)position - 1) >= unchecked((ulong)end)
: position < 1 || position > end;
if (version != LuaCompatibilityVersion.Lua51 && outOfBounds)
{
list.Set(i + 1, list.Get(i));
throw ScriptRuntimeException.BadArgument(1, "insert", "position out of bounds");
}

list.Set(pos, vvalue);
if (end > position)
{
// Sparse ranges can span billions of absent keys. Visit occupied entries instead.
if (unchecked((ulong)(end - position)) > (ulong)list.Count)
{
ShiftSparseInsertRange(list, position, end);
}
else if (end <= int.MaxValue && position >= int.MinValue)
{
for (int i = (int)end; i > (int)position; i--)
{
list.Set(i, list.Get(i - 1));
}
}
else
{
for (long i = end; i > position; i--)
{
SetInsertValue(list, i, list.GetValue(LuaValue.NewInteger(i - 1)));
}
}
}

SetInsertValue(list, position, args[2]);
return LuaValue.Void;
}

return vlist;
private static void SetInsertValue(Table list, long index, LuaValue value)
{
if (index >= int.MinValue && index <= int.MaxValue)
{
list.Set((int)index, value);
}
else
{
list.SetValue(LuaValue.NewInteger(index), value);
}
}

private static long GetInsertEnd(
ScriptExecutionContext executionContext,
LuaValue tableValue,
LuaCompatibilityVersion version
)
{
if (
version == LuaCompatibilityVersion.Lua51
|| !executionContext.TryGetMetamethod(
tableValue,
Metamethods.Len,
out LuaValue lengthMetamethod
)
)
{
int rawLength = tableValue.Table.Length;
return version <= LuaCompatibilityVersion.Lua52
? unchecked(rawLength + 1)
: (long)rawLength + 1;
}

LuaValue length = executionContext
.Script.CallValues(lengthMetamethod, tableValue, tableValue)
.ToScalar();
LuaNumber? number = GetInsertNumber(length, version);
if (version == LuaCompatibilityVersion.Lua52)
{
if (!number.HasValue)
{
throw new ScriptRuntimeException("object length is not a number");
}

return unchecked(NarrowInsertNumber(number.Value) + 1);
}

if (!number.HasValue || !number.Value.TryToInteger(out long integerLength))
{
throw new ScriptRuntimeException("object length is not an integer");
}

return unchecked(integerLength + 1);
}

private static int NarrowInsertNumber(LuaNumber number)
{
// Lua 5.1 and 5.2 truncate toward zero before narrowing to C int.
double value = number.AsFloat;
return value >= long.MinValue && value < -(double)long.MinValue
? unchecked((int)(long)value)
: 0;
}

private static LuaNumber? GetInsertNumber(
LuaValue argument,
LuaCompatibilityVersion version
)
{
if (argument.Type == DataType.Number)
{
return argument.LuaNumber;
}

if (argument.Type != DataType.String)
{
return null;
}

string text = argument.String;
ReadOnlySpan<char> numeral = text.AsSpan();
int terminator = numeral.IndexOf('\0');
if (terminator >= 0)
{
// Lua 5.1 converts a C string. Later versions require the full Lua string.
if (version != LuaCompatibilityVersion.Lua51)
{
return null;
}

numeral = numeral.Slice(0, terminator);
}

// The shared parser also trims Unicode whitespace, which Lua numerals reject.
foreach (char character in numeral)
{
if (character > 0x7f)
{
return null;
}
}

string numericText = terminator >= 0 ? text.Substring(0, terminator) : text;
return LuaNumber.TryParse(numericText, version, out LuaNumber number) ? number : null;
}

private static void ShiftSparseInsertRange(Table list, long position, long end)
{
using PooledResource<List<TablePair>> lease = ListPool<TablePair>.Get(
out List<TablePair> entries
);
foreach (TablePair pair in list.GetNonNilPairsEnumerator())
{
if (
pair.Key.Type == DataType.Number
&& pair.Key.LuaNumber.TryToInteger(out long key)
&& key >= position
&& key <= end
)
{
entries.Add(pair);
}
}

// Keep the source values before clearing overwritten slots, including the old end.
foreach (TablePair pair in entries)
{
list.SetValue(pair.Key, LuaValue.Nil);
}

foreach (TablePair pair in entries)
{
long key = pair.Key.LuaNumber.AsInteger;
if (key < end)
{
SetInsertValue(list, key + 1, pair.Value);
}
}
}

/// <summary>
Expand Down
Loading
Loading