diff --git a/PLAN.md b/PLAN.md index 0963b688..a3ddea34 100644 --- a/PLAN.md +++ b/PLAN.md @@ -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: @@ -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 diff --git a/docs/lua51-stdlib-reference.md b/docs/lua51-stdlib-reference.md index 7ba6ee6b..47cbd947 100644 --- a/docs/lua51-stdlib-reference.md +++ b/docs/lua51-stdlib-reference.md @@ -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 diff --git a/progress/session-192-table-insert-arity.md b/progress/session-192-table-insert-arity.md new file mode 100644 index 00000000..8d8b54b0 --- /dev/null +++ b/progress/session-192-table-insert-arity.md @@ -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). diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/TableModule.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/TableModule.cs index b403c63d..175d6b49 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/TableModule.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/TableModule.cs @@ -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 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> lease = ListPool.Get( + out List 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); + } + } } /// diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs index 37b11b88..2ccf78c9 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs @@ -343,7 +343,7 @@ public async Task InsertUsesLenMetamethodWhenPresent(LuaCompatibilityVersion ver }) table.insert(values, 'sentinel') - return values[5] + return values[_VERSION == 'Lua 5.1' and 2 or 5] " ); @@ -1006,6 +1006,210 @@ await Assert .ConfigureAwait(false); } + [global::TUnit.Core.Test] + [AllLuaVersions] + public void InsertUsesArgumentCountAndReturnsNoValues(LuaCompatibilityVersion version) + { + Script script = CreateScript(version); + script.DoString( + @" + local function none() end + local function pair() return 2, nil end + local function extra() return 2, 4, 6 end + + local appended = {3, 5} + assert(select('#', table.insert(appended, 7, none())) == 0, 'append result count') + assert(appended[1] == 3 and appended[2] == 5 and appended[3] == 7) + assert(select('#', table.insert(appended, nil)) == 0, 'append nil result count') + assert(appended[3] == 7 and appended[4] == nil) + + local inserted = {3, 5} + assert(select('#', table.insert(inserted, 2, 4)) == 0, 'insert result count') + assert(inserted[1] == 3 and inserted[2] == 4 and inserted[3] == 5) + assert(select('#', table.insert(inserted, 2, nil)) == 0, 'explicit nil result count') + assert(inserted[1] == 3 and inserted[2] == nil and inserted[3] == 4 and inserted[4] == 5) + + local expanded = {3, 5} + assert(select('#', table.insert(expanded, pair())) == 0, 'expanded result count') + assert(expanded[1] == 3 and expanded[2] == nil and expanded[3] == 5 and expanded[4] == nil) + + local rejected = {3, 5} + local ok, message = pcall(function() table.insert(rejected, none()) end) + assert(not ok and string.find(message, ""wrong number of arguments"", 1, true), 'too few arguments') + ok, message = pcall(function() table.insert(rejected, extra()) end) + assert(not ok and string.find(message, ""wrong number of arguments"", 1, true), 'too many arguments') + assert(rejected[1] == 3 and rejected[2] == 5 and rejected[3] == nil) + + local lengthCalls = 0 + local measured = setmetatable({}, {__len = function() + lengthCalls = lengthCalls + 1 + return 0 + end}) + assert(not pcall(table.insert, measured)) + assert(lengthCalls == (_VERSION == 'Lua 5.1' and 0 or 1), 'length before arity') + + local binaryPosition = {3, 5} + ok = pcall(table.insert, binaryPosition, '2' .. string.char(0) .. 'tail', 4) + if _VERSION == 'Lua 5.1' then + assert(ok and binaryPosition[2] == 4 and binaryPosition[3] == 5) + else + assert(not ok and binaryPosition[2] == 5 and binaryPosition[3] == nil) + end + + local unicodePosition = {3, 5} + ok = pcall(table.insert, unicodePosition, ' 2 ', 4) + assert(not ok and unicodePosition[2] == 5 and unicodePosition[3] == nil) + + local positioned = {3, 5} + table.insert(positioned, '2', 4) + assert(positioned[1] == 3 and positioned[2] == 4 and positioned[3] == 5) + ok, message = pcall(function() table.insert(positioned, 0, 2) end) + if _VERSION == 'Lua 5.1' then + assert(ok and positioned[0] == 2 and positioned[1] == nil and positioned[2] == 3 and positioned[3] == 4 and positioned[4] == 5) + table.insert(positioned, 6, 6) + assert(positioned[6] == 6) + local fractional = {3, 5} + table.insert(fractional, -0.5, 2) + assert(fractional[-1] == nil and fractional[0] == 2 and fractional[2] == 3) + + local sparse = {3, 5, [-101] = 'unchanged', [-99] = 'a', [-98] = 'b', + [-2] = 'c', [0] = 'd', [-50.5] = 'fractional'} + table.insert(sparse, -100, 'new') + assert(sparse[-101] == 'unchanged' and sparse[-100] == 'new') + assert(sparse[-99] == nil and sparse[-98] == 'a' and sparse[-97] == 'b') + assert(sparse[-2] == nil and sparse[-1] == 'c' and sparse[0] == nil) + assert(sparse[1] == 'd' and sparse[2] == 3 and sparse[3] == 5) + assert(sparse[-50.5] == 'fractional') + else + assert(not ok and string.find(message, ""position out of bounds"", 1, true)) + ok, message = pcall(function() table.insert(positioned, 6, 6) end) + assert(not ok and string.find(message, ""position out of bounds"", 1, true)) + assert(positioned[1] == 3 and positioned[2] == 4 and positioned[3] == 5 and positioned[6] == nil) + end + " + ); + } + + [global::TUnit.Core.Test] + [AllLuaVersions] + public void InsertAppendUsesProfileLengthSemantics(LuaCompatibilityVersion version) + { + Script script = CreateScript(version); + script.DoString( + @" + local lua51 = _VERSION == 'Lua 5.1' + local lua52 = _VERSION == 'Lua 5.2' + local invalidLength = lua52 and 'object length is not a number' + or 'object length is not an integer' + + local function check(length, index, expectedError) + local calls = 0 + local values = {} + setmetatable(values, {__len = function(first, second) + assert(first == values and second == values, 'length operands') + calls = calls + 1 + return length + end}) + + local ok, result = pcall(function() + return select('#', table.insert(values, 'new')) + end) + if lua51 then + assert(ok and result == 0 and calls == 0 and rawget(values, 1) == 'new') + elseif expectedError then + assert(not ok and calls == 1 and next(values) == nil, 'invalid length') + assert(string.find(result, expectedError, 1, true), result) + else + assert(ok and result == 0 and calls == 1, 'append length') + assert(rawget(values, index) == 'new', 'append index') + end + end + + check(-2, -1) + check(-1, 0) + check('2', 3) + check(false, nil, invalidLength) + check('2' .. string.char(0) .. 'tail', nil, invalidLength) + check(2.75, 3, not lua52 and invalidLength) + check(2147483647, lua52 and -2147483648 or 2147483648) + check(4294967296, lua52 and 1 or 4294967297) + if math.maxinteger then + check(math.maxinteger, math.mininteger) + end + " + ); + } + + [global::TUnit.Core.Test] + [AllLuaVersions] + public void InsertPositionalUsesProfileLengthSemantics(LuaCompatibilityVersion version) + { + Script script = CreateScript(version); + script.DoString( + @" + local lua51 = _VERSION == 'Lua 5.1' + local lua52 = _VERSION == 'Lua 5.2' + + if not lua51 then + local wide = setmetatable({}, {__len = function() return 4294967298 end}) + local endIndex = lua52 and 3 or 4294967299 + assert(select('#', table.insert(wide, endIndex, 'new')) == 0, 'wide position') + assert(rawget(wide, endIndex) == 'new') + + local shorter = setmetatable({3, 5, 7}, {__len = function() return 2.75 end}) + local ok, errorText = pcall(table.insert, shorter, 2, 'new') + if lua52 then + assert(ok and shorter[2] == 'new' and shorter[3] == 5) + else + assert(not ok and shorter[2] == 5 and shorter[3] == 7) + assert(string.find(errorText, 'object length is not an integer', 1, true)) + end + + local calls = 0 + local sparse = {[1] = 'head', [50] = 'middle', [101] = 'removed', [102] = 'kept'} + setmetatable(sparse, {__len = function(first, second) + assert(first == sparse and second == sparse, 'length operands') + calls = calls + 1 + return 100 + end}) + table.insert(sparse, 2, 'new') + assert(calls == 1 and sparse[1] == 'head' and sparse[2] == 'new') + assert(sparse[50] == nil and sparse[51] == 'middle') + assert(sparse[101] == nil and sparse[102] == 'kept') + end + + if not lua51 and not lua52 then + local high = 4294967298 + local t = setmetatable({[high] = 'high', [high - 1] = 'previous'}, { + __len = function() return high end + }) + table.insert(t, high - 1, 'new') + assert(t[high - 1] == 'new' and t[high] == 'previous' and t[high + 1] == 'high') + + local unsignedBounds = _VERSION ~= 'Lua 5.3' + local wrapped = setmetatable({}, {__len = function() return math.maxinteger end}) + local ok = pcall(table.insert, wrapped, 1, 'new') + assert(ok == unsignedBounds) + if unsignedBounds then + assert(wrapped[1] == 'new') + else + assert(next(wrapped) == nil) + end + + local negative = setmetatable({[-2] = 'prior'}, {__len = function() return -2 end}) + ok = pcall(table.insert, negative, -2, 'new') + assert(ok == unsignedBounds) + if unsignedBounds then + assert(negative[-2] == 'new' and negative[-1] == 'prior') + else + assert(negative[-2] == 'prior' and negative[-1] == nil) + end + assert(not pcall(table.insert, negative, 0, 'invalid')) + end + " + ); + } + #endregion } } diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertAppendUsesProfileLengthSemantics.lua b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertAppendUsesProfileLengthSemantics.lua new file mode 100644 index 00000000..6c317be4 --- /dev/null +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertAppendUsesProfileLengthSemantics.lua @@ -0,0 +1,45 @@ +-- @lua-versions: 5.1+ +-- @novasharp-only: false +-- @expects-error: false +-- @source: src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs:1098 +-- @test: TableModuleTUnitTests.InsertAppendUsesProfileLengthSemantics +-- Compatibility notes: Lua 5.3+: math.maxinteger (5.3+); Lua 5.3+: math.mininteger (5.3+) +local lua51 = _VERSION == 'Lua 5.1' + local lua52 = _VERSION == 'Lua 5.2' + local invalidLength = lua52 and 'object length is not a number' + or 'object length is not an integer' + + local function check(length, index, expectedError) + local calls = 0 + local values = {} + setmetatable(values, {__len = function(first, second) + assert(first == values and second == values, 'length operands') + calls = calls + 1 + return length + end}) + + local ok, result = pcall(function() + return select('#', table.insert(values, 'new')) + end) + if lua51 then + assert(ok and result == 0 and calls == 0 and rawget(values, 1) == 'new') + elseif expectedError then + assert(not ok and calls == 1 and next(values) == nil, 'invalid length') + assert(string.find(result, expectedError, 1, true), result) + else + assert(ok and result == 0 and calls == 1, 'append length') + assert(rawget(values, index) == 'new', 'append index') + end + end + + check(-2, -1) + check(-1, 0) + check('2', 3) + check(false, nil, invalidLength) + check('2' .. string.char(0) .. 'tail', nil, invalidLength) + check(2.75, 3, not lua52 and invalidLength) + check(2147483647, lua52 and -2147483648 or 2147483648) + check(4294967296, lua52 and 1 or 4294967297) + if math.maxinteger then + check(math.maxinteger, math.mininteger) + end diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertPositionalUsesProfileLengthSemantics.lua b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertPositionalUsesProfileLengthSemantics.lua new file mode 100644 index 00000000..ef50859c --- /dev/null +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertPositionalUsesProfileLengthSemantics.lua @@ -0,0 +1,65 @@ +-- @lua-versions: 5.1+ +-- @novasharp-only: false +-- @expects-error: false +-- @source: src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs:1148 +-- @test: TableModuleTUnitTests.InsertPositionalUsesProfileLengthSemantics +-- Compatibility notes: Lua 5.3+: math.maxinteger (5.3+) +local lua51 = _VERSION == 'Lua 5.1' + local lua52 = _VERSION == 'Lua 5.2' + + if not lua51 then + local wide = setmetatable({}, {__len = function() return 4294967298 end}) + local endIndex = lua52 and 3 or 4294967299 + assert(select('#', table.insert(wide, endIndex, 'new')) == 0, 'wide position') + assert(rawget(wide, endIndex) == 'new') + + local shorter = setmetatable({3, 5, 7}, {__len = function() return 2.75 end}) + local ok, errorText = pcall(table.insert, shorter, 2, 'new') + if lua52 then + assert(ok and shorter[2] == 'new' and shorter[3] == 5) + else + assert(not ok and shorter[2] == 5 and shorter[3] == 7) + assert(string.find(errorText, 'object length is not an integer', 1, true)) + end + + local calls = 0 + local sparse = {[1] = 'head', [50] = 'middle', [101] = 'removed', [102] = 'kept'} + setmetatable(sparse, {__len = function(first, second) + assert(first == sparse and second == sparse, 'length operands') + calls = calls + 1 + return 100 + end}) + table.insert(sparse, 2, 'new') + assert(calls == 1 and sparse[1] == 'head' and sparse[2] == 'new') + assert(sparse[50] == nil and sparse[51] == 'middle') + assert(sparse[101] == nil and sparse[102] == 'kept') + end + + if not lua51 and not lua52 then + local high = 4294967298 + local t = setmetatable({[high] = 'high', [high - 1] = 'previous'}, { + __len = function() return high end + }) + table.insert(t, high - 1, 'new') + assert(t[high - 1] == 'new' and t[high] == 'previous' and t[high + 1] == 'high') + + local unsignedBounds = _VERSION ~= 'Lua 5.3' + local wrapped = setmetatable({}, {__len = function() return math.maxinteger end}) + local ok = pcall(table.insert, wrapped, 1, 'new') + assert(ok == unsignedBounds) + if unsignedBounds then + assert(wrapped[1] == 'new') + else + assert(next(wrapped) == nil) + end + + local negative = setmetatable({[-2] = 'prior'}, {__len = function() return -2 end}) + ok = pcall(table.insert, negative, -2, 'new') + assert(ok == unsignedBounds) + if unsignedBounds then + assert(negative[-2] == 'new' and negative[-1] == 'prior') + else + assert(negative[-2] == 'prior' and negative[-1] == nil) + end + assert(not pcall(table.insert, negative, 0, 'invalid')) + end diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertUsesArgumentCountAndReturnsNoValues.lua b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertUsesArgumentCountAndReturnsNoValues.lua new file mode 100644 index 00000000..09dbfe54 --- /dev/null +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertUsesArgumentCountAndReturnsNoValues.lua @@ -0,0 +1,78 @@ +-- @lua-versions: 5.1+ +-- @novasharp-only: false +-- @expects-error: false +-- @source: src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs:1014 +-- @test: TableModuleTUnitTests.InsertUsesArgumentCountAndReturnsNoValues +local function none() end + local function pair() return 2, nil end + local function extra() return 2, 4, 6 end + + local appended = {3, 5} + assert(select('#', table.insert(appended, 7, none())) == 0, 'append result count') + assert(appended[1] == 3 and appended[2] == 5 and appended[3] == 7) + assert(select('#', table.insert(appended, nil)) == 0, 'append nil result count') + assert(appended[3] == 7 and appended[4] == nil) + + local inserted = {3, 5} + assert(select('#', table.insert(inserted, 2, 4)) == 0, 'insert result count') + assert(inserted[1] == 3 and inserted[2] == 4 and inserted[3] == 5) + assert(select('#', table.insert(inserted, 2, nil)) == 0, 'explicit nil result count') + assert(inserted[1] == 3 and inserted[2] == nil and inserted[3] == 4 and inserted[4] == 5) + + local expanded = {3, 5} + assert(select('#', table.insert(expanded, pair())) == 0, 'expanded result count') + assert(expanded[1] == 3 and expanded[2] == nil and expanded[3] == 5 and expanded[4] == nil) + + local rejected = {3, 5} + local ok, message = pcall(function() table.insert(rejected, none()) end) + assert(not ok and string.find(message, "wrong number of arguments", 1, true), 'too few arguments') + ok, message = pcall(function() table.insert(rejected, extra()) end) + assert(not ok and string.find(message, "wrong number of arguments", 1, true), 'too many arguments') + assert(rejected[1] == 3 and rejected[2] == 5 and rejected[3] == nil) + + local lengthCalls = 0 + local measured = setmetatable({}, {__len = function() + lengthCalls = lengthCalls + 1 + return 0 + end}) + assert(not pcall(table.insert, measured)) + assert(lengthCalls == (_VERSION == 'Lua 5.1' and 0 or 1), 'length before arity') + + local binaryPosition = {3, 5} + ok = pcall(table.insert, binaryPosition, '2' .. string.char(0) .. 'tail', 4) + if _VERSION == 'Lua 5.1' then + assert(ok and binaryPosition[2] == 4 and binaryPosition[3] == 5) + else + assert(not ok and binaryPosition[2] == 5 and binaryPosition[3] == nil) + end + + local unicodePosition = {3, 5} + ok = pcall(table.insert, unicodePosition, ' 2 ', 4) + assert(not ok and unicodePosition[2] == 5 and unicodePosition[3] == nil) + + local positioned = {3, 5} + table.insert(positioned, '2', 4) + assert(positioned[1] == 3 and positioned[2] == 4 and positioned[3] == 5) + ok, message = pcall(function() table.insert(positioned, 0, 2) end) + if _VERSION == 'Lua 5.1' then + assert(ok and positioned[0] == 2 and positioned[1] == nil and positioned[2] == 3 and positioned[3] == 4 and positioned[4] == 5) + table.insert(positioned, 6, 6) + assert(positioned[6] == 6) + local fractional = {3, 5} + table.insert(fractional, -0.5, 2) + assert(fractional[-1] == nil and fractional[0] == 2 and fractional[2] == 3) + + local sparse = {3, 5, [-101] = 'unchanged', [-99] = 'a', [-98] = 'b', + [-2] = 'c', [0] = 'd', [-50.5] = 'fractional'} + table.insert(sparse, -100, 'new') + assert(sparse[-101] == 'unchanged' and sparse[-100] == 'new') + assert(sparse[-99] == nil and sparse[-98] == 'a' and sparse[-97] == 'b') + assert(sparse[-2] == nil and sparse[-1] == 'c' and sparse[0] == nil) + assert(sparse[1] == 'd' and sparse[2] == 3 and sparse[3] == 5) + assert(sparse[-50.5] == 'fractional') + else + assert(not ok and string.find(message, "position out of bounds", 1, true)) + ok, message = pcall(function() table.insert(positioned, 6, 6) end) + assert(not ok and string.find(message, "position out of bounds", 1, true)) + assert(positioned[1] == 3 and positioned[2] == 4 and positioned[3] == 5 and positioned[6] == nil) + end diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertUsesLenMetamethodWhenPresent.lua b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertUsesLenMetamethodWhenPresent.lua index bc290ab2..a9f76756 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertUsesLenMetamethodWhenPresent.lua +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/InsertUsesLenMetamethodWhenPresent.lua @@ -1,9 +1,8 @@ --- @lua-versions: 5.1 +-- @lua-versions: 5.1+ -- @novasharp-only: false -- @expects-error: false -- @source: src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs:261 -- @test: TableModuleTUnitTests.InsertUsesLenMetamethodWhenPresent --- Test targets Lua 5.1 local values = setmetatable({ [1] = 'seed' }, { __len = function() return 4 @@ -11,4 +10,4 @@ local values = setmetatable({ [1] = 'seed' }, { }) table.insert(values, 'sentinel') - return values[5] + return values[_VERSION == 'Lua 5.1' and 2 or 5] diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/manifest.json b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/manifest.json index 6af3f724..d1f065d8 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/manifest.json +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/manifest.json @@ -1,14 +1,14 @@ { "generated_by": "tools/LuaCorpusExtractor/lua_corpus_extractor_v2.py", - "total_snippets": 2001, + "total_snippets": 2004, "novasharp_only": 498, - "comparable": 1503, + "comparable": 1506, "by_version": { - "5.1": 1002, - "5.2": 705, - "5.3": 949, - "5.4": 1018, - "5.5": 1059 + "5.1": 1005, + "5.2": 709, + "5.3": 953, + "5.4": 1022, + "5.5": 1063 }, "snippets": [ { @@ -11714,7 +11714,11 @@ "source": "src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs:261", "test": "TableModuleTUnitTests.InsertUsesLenMetamethodWhenPresent", "lua_versions": [ - "5.1" + "5.1", + "5.2", + "5.3", + "5.4", + "5.5" ], "novasharp_only": false, "expects_error": false @@ -22214,6 +22218,48 @@ ], "novasharp_only": false, "expects_error": false + }, + { + "path": "TableModuleTUnitTests/InsertUsesArgumentCountAndReturnsNoValues.lua", + "source": "src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs:1014", + "test": "TableModuleTUnitTests.InsertUsesArgumentCountAndReturnsNoValues", + "lua_versions": [ + "5.1", + "5.2", + "5.3", + "5.4", + "5.5" + ], + "novasharp_only": false, + "expects_error": false + }, + { + "path": "TableModuleTUnitTests/InsertAppendUsesProfileLengthSemantics.lua", + "source": "src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs:1098", + "test": "TableModuleTUnitTests.InsertAppendUsesProfileLengthSemantics", + "lua_versions": [ + "5.1", + "5.2", + "5.3", + "5.4", + "5.5" + ], + "novasharp_only": false, + "expects_error": false + }, + { + "path": "TableModuleTUnitTests/InsertPositionalUsesProfileLengthSemantics.lua", + "source": "src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs:1148", + "test": "TableModuleTUnitTests.InsertPositionalUsesProfileLengthSemantics", + "lua_versions": [ + "5.1", + "5.2", + "5.3", + "5.4", + "5.5" + ], + "novasharp_only": false, + "expects_error": false } ] } \ No newline at end of file