Skip to main content

lua_stdlib/
table_lib.rs

1//! Rust port of `ltablib.c` — Lua `table` standard library.
2//!
3//! Provides: `table.concat`, `table.insert`, `table.move`, `table.pack`,
4//! `table.remove`, `table.sort`, `table.unpack`.
5//!
6//! C source: `reference/lua-5.4.7/src/ltablib.c` (430 lines, 14 functions)
7
8use lua_types::{GcRef, LuaError, LuaTable, LuaType, LuaValue};
9use crate::state_stub::{LuaState, LuaStateStubExt as _, CompareOp};
10
11// ─── Operation flags ──────────────────────────────────────────────────────────
12const TAB_R: u32 = 1;
13const TAB_W: u32 = 2;
14const TAB_L: u32 = 4;
15const TAB_RW: u32 = TAB_R | TAB_W;
16
17const RANLIMIT: u32 = 100;
18
19type IdxT = u32;
20
21// ─── Internal helpers ─────────────────────────────────────────────────────────
22
23/// currently sitting at stack depth `n`; returns `true` if the result is not nil.
24///
25/// ```c
26/// static int checkfield (lua_State *L, const char *key, int n) {
27///   lua_pushstring(L, key);
28///   return (lua_rawget(L, -n) != LUA_TNIL);
29/// }
30/// ```
31fn check_field(state: &mut LuaState, key: &[u8], n: i32) -> Result<bool, LuaError> {
32    // TODO(port): state.push_string pushes a Lua string from &[u8]; verify method name
33    state.push_string(key)?;
34    // raw_get(-n): looks up MT[key] (MT is at -n after the key push), replaces key with value
35    let ty = state.raw_get(-n)?;
36    Ok(ty != LuaType::Nil)
37}
38
39/// metatable with the metamethods required by `what`
40/// (`TAB_R` → `__index`, `TAB_W` → `__newindex`, `TAB_L` → `__len`).
41///
42/// ```c
43/// static void checktab (lua_State *L, int arg, int what) {
44///   if (lua_type(L, arg) != LUA_TTABLE) {
45///     int n = 1;
46///     if (lua_getmetatable(L, arg) &&
47///         (!(what & TAB_R) || checkfield(L, "__index", ++n)) &&
48///         (!(what & TAB_W) || checkfield(L, "__newindex", ++n)) &&
49///         (!(what & TAB_L) || checkfield(L, "__len", ++n))) {
50///       lua_pop(L, n);
51///     }
52///     else
53///       luaL_checktype(L, arg, LUA_TTABLE);
54///   }
55/// }
56/// ```
57///
58/// PORT NOTE: stack cleanup on the error path is elided here (in C, `longjmp`
59/// unwinds automatically). Phase B should add cleanup before the `check_arg_type`
60/// call to leave the stack consistent.
61fn check_tab(state: &mut LuaState, arg: i32, what: u32) -> Result<(), LuaError> {
62    if state.type_at(arg) == LuaType::Table {
63        return Ok(());
64    }
65    // `n` tracks how many items have been pushed (MT + checked field values).
66    let mut n: i32 = 1;
67    // TODO(port): state.get_metatable returns bool (pushes MT if found); verify method name
68    let has_mt = state.get_metatable(arg)?;
69    let mut ok = has_mt;
70
71    // Short-circuit: each field is only checked if all previous checks passed.
72    if ok && (what & TAB_R) != 0 {
73        n += 1;
74        ok = check_field(state, b"__index", n)?;
75    }
76    if ok && (what & TAB_W) != 0 {
77        n += 1;
78        ok = check_field(state, b"__newindex", n)?;
79    }
80    if ok && (what & TAB_L) != 0 {
81        n += 1;
82        ok = check_field(state, b"__len", n)?;
83    }
84
85    if ok {
86        state.pop_n(n as usize);
87        Ok(())
88    } else {
89        state.check_arg_type(arg, LuaType::Table)
90    }
91}
92
93///
94/// Check that argument `n` is a table (or table-like per `w`) and return its length.
95fn aux_getn(state: &mut LuaState, n: i32, w: u32) -> Result<i64, LuaError> {
96    check_tab(state, n, w | TAB_L)?;
97    // TODO(port): state.length_at applies the `#` operator and returns i64; verify method name
98    state.length_at(n)
99}
100
101#[inline]
102fn plain_table_at(state: &mut LuaState, idx: i32) -> Option<GcRef<LuaTable>> {
103    match state.value_at(idx) {
104        LuaValue::Table(tbl) if tbl.metatable().is_none() => Some(tbl),
105        _ => None,
106    }
107}
108
109#[inline]
110fn raw_set_int(
111    state: &mut LuaState,
112    tbl: GcRef<LuaTable>,
113    key: i64,
114    value: LuaValue,
115) -> Result<(), LuaError> {
116    state.gc_barrier_back(LuaValue::Table(tbl), value);
117    tbl.try_raw_set_int(key, value)
118}
119
120// ─── table.insert ─────────────────────────────────────────────────────────────
121
122///
123/// ```c
124/// static int tinsert (lua_State *L) {
125///   lua_Integer pos;
126///   lua_Integer e = aux_getn(L, 1, TAB_RW);
127///   e = luaL_intop(+, e, 1);
128///   switch (lua_gettop(L)) {
129///     case 2: { pos = e; break; }
130///     case 3: {
131///       lua_Integer i;
132///       pos = luaL_checkinteger(L, 2);
133///       luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2,
134///                        "position out of bounds");
135///       for (i = e; i > pos; i--) {
136///         lua_geti(L, 1, i - 1);
137///         lua_seti(L, 1, i);
138///       }
139///       break;
140///     }
141///     default:
142///       return luaL_error(L, "wrong number of arguments to 'insert'");
143///   }
144///   lua_seti(L, 1, pos);
145///   return 0;
146/// }
147/// ```
148pub fn insert(state: &mut LuaState) -> Result<usize, LuaError> {
149    let mut e = aux_getn(state, 1, TAB_RW)?;
150    e = (e as u64).wrapping_add(1) as i64;
151    let plain_table = plain_table_at(state, 1);
152
153    let pos: i64 = match state.get_top() {
154        2 => {
155            if let Some(tbl) = plain_table {
156                let value = state.value_at(2);
157                raw_set_int(state, tbl, e, value)?;
158                state.pop_n(1);
159                return Ok(0);
160            }
161            e
162        }
163        3 => {
164            let pos = state.check_arg_integer(2)?;
165            // Checks 1 <= pos <= e (wrapping subtraction catches pos <= 0)
166            if !((pos as u64).wrapping_sub(1) < (e as u64)) {
167                return Err(LuaError::arg_error(2, "position out of bounds"));
168            }
169            if let Some(tbl) = plain_table {
170                let value = state.value_at(3);
171                let mut i = e;
172                while i > pos {
173                    let shifted = tbl.get_int(i - 1);
174                    raw_set_int(state, tbl, i, shifted)?;
175                    i -= 1;
176                }
177                raw_set_int(state, tbl, pos, value)?;
178                state.pop_n(1);
179                return Ok(0);
180            }
181            // Cache the table once to avoid re-resolving stack slot 1 on every
182            // iteration of the shift loop. C's lua_geti is a single pointer
183            // arithmetic operation; our index_to_value is a function call with
184            // branches, so this saves ~2N index resolutions for shift count N.
185            let tbl = state.value_at(1);
186            let mut i = e;
187            while i > pos {
188                state.table_get_i_value(&tbl, i - 1)?;
189                state.table_set_i_value(&tbl, i)?;
190                i -= 1;
191            }
192            pos
193        }
194        _ => {
195            return Err(LuaError::runtime(format_args!(
196                "wrong number of arguments to 'insert'"
197            )));
198        }
199    };
200    state.table_set_i(1, pos)?;
201    Ok(0)
202}
203
204// ─── table.remove ─────────────────────────────────────────────────────────────
205
206///
207/// ```c
208/// static int tremove (lua_State *L) {
209///   lua_Integer size = aux_getn(L, 1, TAB_RW);
210///   lua_Integer pos = luaL_optinteger(L, 2, size);
211///   if (pos != size)
212///     luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 2,
213///                      "position out of bounds");
214///   lua_geti(L, 1, pos);
215///   for ( ; pos < size; pos++) {
216///     lua_geti(L, 1, pos + 1);
217///     lua_seti(L, 1, pos);
218///   }
219///   lua_pushnil(L);
220///   lua_seti(L, 1, pos);
221///   return 1;
222/// }
223/// ```
224pub fn remove(state: &mut LuaState) -> Result<usize, LuaError> {
225    let size = aux_getn(state, 1, TAB_RW)?;
226    let mut pos = state.opt_arg_integer(2, size)?;
227    if pos != size {
228        if !((pos as u64).wrapping_sub(1) <= (size as u64)) {
229            return Err(LuaError::arg_error(2, "position out of bounds"));
230        }
231    }
232    // Cache the table once to avoid re-resolving stack slot 1 on every
233    // iteration of the shift loop. C's lua_geti is a single pointer
234    // arithmetic operation; our index_to_value is a function call with
235    // branches, so this saves ~2N index resolutions for shift count N.
236    if let Some(tbl) = plain_table_at(state, 1) {
237        let result = tbl.get_int(pos);
238        state.push(result);
239        while pos < size {
240            let shifted = tbl.get_int(pos + 1);
241            raw_set_int(state, tbl, pos, shifted)?;
242            pos += 1;
243        }
244        raw_set_int(state, tbl, pos, LuaValue::Nil)?;
245        return Ok(1);
246    }
247    let tbl = state.value_at(1);
248    state.table_get_i_value(&tbl, pos)?;   // push element to be returned
249    while pos < size {
250        state.table_get_i_value(&tbl, pos + 1)?;
251        state.table_set_i_value(&tbl, pos)?;
252        pos += 1;
253    }
254    state.push(LuaValue::Nil);
255    state.table_set_i_value(&tbl, pos)?;   // remove last slot (table[pos] = nil)
256    Ok(1)
257}
258
259// ─── table.move ───────────────────────────────────────────────────────────────
260
261///
262/// Copies elements `a1[f..e]` into `a2[t..]` (or `a1[t..]` if `a2` is absent).
263/// Copies in increasing order when safe, decreasing when ranges overlap.
264///
265/// ```c
266/// static int tmove (lua_State *L) {
267///   lua_Integer f = luaL_checkinteger(L, 2);
268///   lua_Integer e = luaL_checkinteger(L, 3);
269///   lua_Integer t = luaL_checkinteger(L, 4);
270///   int tt = !lua_isnoneornil(L, 5) ? 5 : 1;
271///   checktab(L, 1, TAB_R);
272///   checktab(L, tt, TAB_W);
273///   if (e >= f) {
274///     lua_Integer n, i;
275///     luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3, "too many elements to move");
276///     n = e - f + 1;
277///     luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4, "destination wrap around");
278///     if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) {
279///       for (i = 0; i < n; i++) { lua_geti(L, 1, f + i); lua_seti(L, tt, t + i); }
280///     } else {
281///       for (i = n - 1; i >= 0; i--) { lua_geti(L, 1, f + i); lua_seti(L, tt, t + i); }
282///     }
283///   }
284///   lua_pushvalue(L, tt);
285///   return 1;
286/// }
287/// ```
288pub fn tmove(state: &mut LuaState) -> Result<usize, LuaError> {
289    let f = state.check_arg_integer(2)?;
290    let e = state.check_arg_integer(3)?;
291    let t = state.check_arg_integer(4)?;
292    let tt: i32 = if !matches!(state.type_at(5), LuaType::None | LuaType::Nil) {
293        5
294    } else {
295        1
296    };
297    check_tab(state, 1, TAB_R)?;
298    check_tab(state, tt, TAB_W)?;
299
300    if e >= f {
301        if !(f > 0 || e < i64::MAX + f) {
302            return Err(LuaError::arg_error(3, "too many elements to move"));
303        }
304        let n = e - f + 1;
305        if !(t <= i64::MAX - n + 1) {
306            return Err(LuaError::arg_error(4, "destination wrap around"));
307        }
308        // Copy forward (increasing) when safe to do so; backward when ranges overlap.
309        // TODO(port): state.compare(a, b, CompareOp::Eq) → lua_compare LUA_OPEQ; verify method
310        let copy_forward = t > e
311            || t <= f
312            || (tt != 1 && !state.compare(1, tt, CompareOp::Eq)?);
313        if copy_forward {
314            for i in 0..n {
315                state.table_get_i(1, f + i)?;
316                state.table_set_i(tt, t + i)?;
317            }
318        } else {
319            for i in (0..n).rev() {
320                state.table_get_i(1, f + i)?;
321                state.table_set_i(tt, t + i)?;
322            }
323        }
324    }
325    // TODO(port): state.push_value_at → lua_pushvalue; verify method name
326    state.push_value_at(tt)?;
327    Ok(1)
328}
329
330// ─── table.concat ─────────────────────────────────────────────────────────────
331
332/// a string-or-number, add its string representation to `buf`, then pop it.
333///
334/// ```c
335/// static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) {
336///   lua_geti(L, 1, i);
337///   if (l_unlikely(!lua_isstring(L, -1)))
338///     luaL_error(L, "invalid value (%s) at index %I in table for 'concat'",
339///                   luaL_typename(L, -1), (LUAI_UACINT)i);
340///   luaL_addvalue(b);
341/// }
342/// ```
343///
344/// PORT NOTE: `luaL_Buffer` in C accumulates bytes and then pushes the result;
345/// Rust uses a `Vec<u8>` accumulator passed by mutable reference instead.
346fn add_field(state: &mut LuaState, buf: &mut Vec<u8>, idx: i64) -> Result<(), LuaError> {
347    state.table_get_i(1, idx)?;
348    if !matches!(state.type_at(-1), LuaType::String | LuaType::Number) {
349        // TODO(port): state.type_name_str_at(-1) returns &'static str for the base type name
350        let type_name = state.type_name_str_at(-1);
351        return Err(LuaError::runtime(format_args!(
352            "invalid value ({:?}) at index {} in table for 'concat'",
353            type_name, idx
354        )));
355    }
356    // TODO(port): state.to_bytes_at(-1) converts via Lua's tostring coercion; verify method name
357    let bytes = state.to_bytes_at(-1).ok_or_else(|| LuaError::runtime(format_args!("invalid value at index {}", idx)))?;
358    buf.extend_from_slice(&bytes);
359    state.pop_n(1);
360    Ok(())
361}
362
363///
364/// ```c
365/// static int tconcat (lua_State *L) {
366///   luaL_Buffer b;
367///   lua_Integer last = aux_getn(L, 1, TAB_R);
368///   size_t lsep;
369///   const char *sep = luaL_optlstring(L, 2, "", &lsep);
370///   lua_Integer i = luaL_optinteger(L, 3, 1);
371///   last = luaL_optinteger(L, 4, last);
372///   luaL_buffinit(L, &b);
373///   for (; i < last; i++) { addfield(L, &b, i); luaL_addlstring(&b, sep, lsep); }
374///   if (i == last) addfield(L, &b, i);
375///   luaL_pushresult(&b);
376///   return 1;
377/// }
378/// ```
379pub fn concat(state: &mut LuaState) -> Result<usize, LuaError> {
380    let last = aux_getn(state, 1, TAB_R)?;
381    // TODO(port): state.opt_arg_lstring(n, default) → luaL_optlstring; verify method name
382    // Clone the separator before any stack-mutating calls that might invalidate it.
383    let sep: Vec<u8> = state.opt_arg_lstring(2, Some(b""))?.unwrap_or_default();
384    let mut i = state.opt_arg_integer(3, 1)?;
385    let last = state.opt_arg_integer(4, last)?;
386
387    // PORT NOTE: C uses luaL_Buffer (which may back-patch the stack);
388    // Rust uses a plain Vec<u8> accumulator and pushes the result at the end.
389    let mut buf: Vec<u8> = Vec::new();
390    while i < last {
391        add_field(state, &mut buf, i)?;
392        buf.extend_from_slice(&sep);
393        i += 1;
394    }
395    if i == last {
396        add_field(state, &mut buf, i)?;
397    }
398    // TODO(port): state.push_lstring pushes a Lua string from &[u8]; verify method name
399    state.push_lstring(&buf)?;
400    Ok(1)
401}
402
403// ─── table.pack / table.unpack ────────────────────────────────────────────────
404
405///
406/// Creates a new table `t` with all arguments as integer keys and `t.n` set
407/// to the argument count.
408///
409/// ```c
410/// static int tpack (lua_State *L) {
411///   int i;
412///   int n = lua_gettop(L);
413///   lua_createtable(L, n, 1);
414///   lua_insert(L, 1);
415///   for (i = n; i >= 1; i--)
416///     lua_seti(L, 1, i);
417///   lua_pushinteger(L, n);
418///   lua_setfield(L, 1, "n");
419///   return 1;
420/// }
421/// ```
422pub fn pack(state: &mut LuaState) -> Result<usize, LuaError> {
423    let n = state.get_top();
424    // TODO(port): state.create_table(narr, nrec) → lua_createtable; verify method name
425    state.create_table(n, 1)?;
426    state.insert(1)?;
427    // table_set_i pops the top; args shift from n+1..=2 down to 1..=n as we pop
428    for i in (1..=n).rev() {
429        state.table_set_i(1, i as i64)?;
430    }
431    state.push(LuaValue::Int(n as i64));
432    // TODO(port): state.set_field(stack_pos, key_bytes) → lua_setfield; verify method name
433    state.set_field(1, b"n")?;
434    Ok(1)
435}
436
437///
438/// Pushes `t[i], t[i+1], …, t[j]` and returns the count.
439///
440/// ```c
441/// static int tunpack (lua_State *L) {
442///   lua_Unsigned n;
443///   lua_Integer i = luaL_optinteger(L, 2, 1);
444///   lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));
445///   if (i > e) return 0;
446///   n = (lua_Unsigned)e - i;
447///   if (l_unlikely(n >= (unsigned int)INT_MAX ||
448///                  !lua_checkstack(L, (int)(++n))))
449///     return luaL_error(L, "too many results to unpack");
450///   for (; i < e; i++) lua_geti(L, 1, i);
451///   lua_geti(L, 1, e);
452///   return (int)n;
453/// }
454/// ```
455pub fn unpack(state: &mut LuaState) -> Result<usize, LuaError> {
456    let i = state.opt_arg_integer(2, 1)?;
457    let e = if matches!(state.type_at(3), LuaType::None | LuaType::Nil) {
458        state.length_at(1)?
459    } else {
460        state.check_arg_integer(3)?
461    };
462    if i > e {
463        return Ok(0); // empty range
464    }
465    let n = (e as u64).wrapping_sub(i as u64);
466    // The size check uses the pre-increment value so that a wrapped-to-0 result
467    // (e.g. i=minI, e=maxI yields n = 2^64-1 pre-inc, 0 post-inc) still trips
468    // the error rather than silently entering a 2^64-iteration loop.
469    if n >= i32::MAX as u64 {
470        return Err(LuaError::runtime(format_args!("too many results to unpack")));
471    }
472    let n = n + 1;
473    if !state.check_stack_growth(n as i32) {
474        return Err(LuaError::runtime(format_args!("too many results to unpack")));
475    }
476    let n = n as i64;
477    let mut k = i;
478    while k < e {
479        state.table_get_i(1, k)?;
480        k += 1;
481    }
482    state.table_get_i(1, e)?; // push last element
483    Ok(n as usize)
484}
485
486// ─── Quicksort ────────────────────────────────────────────────────────────────
487
488/// selection when a partition is severely imbalanced.
489///
490/// `unsigned int` array whose elements are summed.
491///
492/// PORT NOTE: Rust uses `SystemTime` as an entropy source instead of
493/// POSIX `clock()`/`time()`. The mixing is simplified (subsecond nanos XOR-
494/// shifted) but serves the same purpose: breaking pathological patterns.
495fn randomize_pivot() -> u32 {
496    use std::time::{SystemTime, UNIX_EPOCH};
497    let nanos = SystemTime::now()
498        .duration_since(UNIX_EPOCH)
499        .map(|d| d.subsec_nanos())
500        .unwrap_or(0u32);
501    nanos ^ nanos.wrapping_shr(16)
502}
503
504/// `table[i]` and `table[j]` respectively (table is at stack position 1).
505///
506/// ```c
507/// static void set2 (lua_State *L, IdxT i, IdxT j) {
508///   lua_seti(L, 1, i);
509///   lua_seti(L, 1, j);
510/// }
511/// ```
512fn set2(state: &mut LuaState, i: IdxT, j: IdxT) -> Result<(), LuaError> {
513    // First seti pops the stack top; second seti pops the new top.
514    state.table_set_i(1, i as i64)?;
515    state.table_set_i(1, j as i64)?;
516    Ok(())
517}
518
519/// sort order: either the `<` operator (if arg 2 is nil) or the user's
520/// comparison function at stack position 2.
521///
522/// ```c
523/// static int sort_comp (lua_State *L, int a, int b) {
524///   if (lua_isnil(L, 2))
525///     return lua_compare(L, a, b, LUA_OPLT);
526///   else {
527///     int res;
528///     lua_pushvalue(L, 2);
529///     lua_pushvalue(L, a-1);
530///     lua_pushvalue(L, b-2);
531///     lua_call(L, 2, 1);
532///     res = lua_toboolean(L, -1);
533///     lua_pop(L, 1);
534///     return res;
535///   }
536/// }
537/// ```
538///
539/// The offsets `a-1` and `b-2` compensate for the function and first-argument
540/// copies pushed before the respective values: `a-1` accounts for the function
541/// push; `b-2` accounts for both the function push and the copy of `a`.
542fn sort_comp(state: &mut LuaState, a: i32, b: i32) -> Result<bool, LuaError> {
543    if state.type_at(2) == LuaType::Nil {
544        // No user comparator: use the default `<` operator.
545        return state.compare(a, b, CompareOp::Lt);
546    }
547    // User comparator at stack position 2.
548    state.push_value_at(2)?;       // push function
549    state.push_value_at(a - 1)?;   // push copy of a (compensate for function push)
550    state.push_value_at(b - 2)?;   // push copy of b (compensate for function + a copy)
551    state.call(2, 1)?;
552    // TODO(port): state.to_boolean(-1) → lua_toboolean (never fails); verify method name
553    let res = state.to_boolean(-1);
554    state.pop_n(1);
555    Ok(res)
556}
557
558/// is already on the top of the Lua stack.
559///
560/// Precondition: `a[lo] <= P == a[up-1] <= a[up]` and `P` is at stack top.
561/// Postcondition: `a[lo..i-1] <= a[i] == P <= a[i+1..up]`; stack is clean.
562/// Returns the final pivot index `i`.
563///
564/// ```c
565/// static IdxT partition (lua_State *L, IdxT lo, IdxT up) {
566///   IdxT i = lo;
567///   IdxT j = up - 1;
568///   for (;;) {
569///     while ((void)lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) {
570///       if (l_unlikely(i == up - 1))
571///         luaL_error(L, "invalid order function for sorting");
572///       lua_pop(L, 1);
573///     }
574///     while ((void)lua_geti(L, 1, --j), sort_comp(L, -3, -1)) {
575///       if (l_unlikely(j < i))
576///         luaL_error(L, "invalid order function for sorting");
577///       lua_pop(L, 1);
578///     }
579///     if (j < i) {
580///       lua_pop(L, 1);
581///       set2(L, up - 1, i);
582///       return i;
583///     }
584///     set2(L, i, j);
585///   }
586/// }
587/// ```
588fn partition(state: &mut LuaState, lo: IdxT, up: IdxT) -> Result<IdxT, LuaError> {
589    let mut i: IdxT = lo;
590    let mut j: IdxT = up - 1;
591    // Entry: stack top is P (pivot value).
592    loop {
593        // Advance i: find first a[i] >= P.
594        // Stack during i-loop body: P(-2), a[i](-1)
595        loop {
596            i += 1;
597            state.table_get_i(1, i as i64)?; // push a[i]
598            if !sort_comp(state, -1, -2)? {
599                // a[i] >= P: leave a[i] on stack and exit
600                break;
601            }
602            // a[i] < P; check for invalid comparator
603            if i == up - 1 {
604                return Err(LuaError::runtime(format_args!(
605                    "invalid order function for sorting"
606                )));
607            }
608            state.pop_n(1); // remove a[i]
609        }
610        // Retreat j: find last a[j] <= P.
611        // Stack during j-loop body: P(-3), a[i](-2), a[j](-1)
612        loop {
613            // PERF(port): wrapping_sub mirrors C unsigned IdxT behaviour for edge cases
614            j = j.wrapping_sub(1);
615            state.table_get_i(1, j as i64)?; // push a[j]
616            if !sort_comp(state, -3, -1)? {
617                // P >= a[j]: leave a[j] on stack and exit
618                break;
619            }
620            // P < a[j]; check for invalid comparator
621            if j < i {
622                return Err(LuaError::runtime(format_args!(
623                    "invalid order function for sorting"
624                )));
625            }
626            state.pop_n(1); // remove a[j]
627        }
628        // Stack: P(-3), a[i](-2), a[j](-1)
629        if j < i {
630            // No out-of-place elements; finalize: place pivot at position i.
631            state.pop_n(1); // pop a[j]; stack: P(-2), a[i](-1)
632            set2(state, up - 1, i)?; // table[up-1] = a[i], table[i] = P; stack clean
633            return Ok(i);
634        }
635        // Swap a[i] and a[j] to restore loop invariant.
636        // set2: table[i] = a[j] (pops -1), table[j] = a[i] (pops new -1); stack: P(-1)
637        set2(state, i, j)?;
638    }
639}
640
641/// `[lo, up]`, randomised by `rnd`.
642///
643/// ```c
644/// static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) {
645///   IdxT r4 = (up - lo) / 4;
646///   IdxT p = rnd % (r4 * 2) + (lo + r4);
647///   lua_assert(lo + r4 <= p && p <= up - r4);
648///   return p;
649/// }
650/// ```
651fn choose_pivot(lo: IdxT, up: IdxT, rnd: u32) -> IdxT {
652    let r4 = (up - lo) / 4; // range / 4
653    let p = rnd % (r4 * 2) + (lo + r4);
654    debug_assert!(lo + r4 <= p && p <= up - r4);
655    p
656}
657
658///
659/// Sorts `table[lo..=up]` in place, recursing on the smaller partition and
660/// tail-looping on the larger (to bound Rust's call stack). Randomises pivot
661/// selection when a partition is badly imbalanced.
662///
663/// ```c
664/// static void auxsort (lua_State *L, IdxT lo, IdxT up, unsigned int rnd) {
665///   while (lo < up) {
666///     IdxT p, n;
667///     lua_geti(L, 1, lo); lua_geti(L, 1, up);
668///     if (sort_comp(L, -1, -2)) set2(L, lo, up); else lua_pop(L, 2);
669///     if (up - lo == 1) return;
670///     if (up - lo < RANLIMIT || rnd == 0) p = (lo + up)/2;
671///     else p = choosePivot(lo, up, rnd);
672///     lua_geti(L, 1, p); lua_geti(L, 1, lo);
673///     if (sort_comp(L, -2, -1)) set2(L, p, lo);
674///     else {
675///       lua_pop(L, 1); lua_geti(L, 1, up);
676///       if (sort_comp(L, -1, -2)) set2(L, p, up); else lua_pop(L, 2);
677///     }
678///     if (up - lo == 2) return;
679///     lua_geti(L, 1, p); lua_pushvalue(L, -1); lua_geti(L, 1, up - 1);
680///     set2(L, p, up - 1);
681///     p = partition(L, lo, up);
682///     if (p - lo < up - p) {
683///       auxsort(L, lo, p - 1, rnd); n = p - lo; lo = p + 1;
684///     } else {
685///       auxsort(L, p + 1, up, rnd); n = up - p; up = p - 1;
686///     }
687///     if ((up - lo) / 128 > n) rnd = l_randomizePivot();
688///   }
689/// }
690/// ```
691fn aux_sort(state: &mut LuaState, mut lo: IdxT, mut up: IdxT, mut rnd: u32) -> Result<(), LuaError> {
692    while lo < up {
693        // Step 1: ensure a[lo] <= a[up] (cheap two-element sort)
694        state.table_get_i(1, lo as i64)?; // push a[lo]
695        state.table_get_i(1, up as i64)?; // push a[up]
696        if sort_comp(state, -1, -2)? {
697            set2(state, lo, up)?; // swap so a[lo] <= a[up]
698        } else {
699            state.pop_n(2);
700        }
701        if up - lo == 1 {
702            return Ok(()); // only 2 elements, now sorted
703        }
704
705        // Step 2: choose pivot index
706        let mut p: IdxT = if up - lo < RANLIMIT || rnd == 0 {
707            (lo + up) / 2 // midpoint pivot for small/non-random runs
708        } else {
709            choose_pivot(lo, up, rnd)
710        };
711
712        // Step 3: median-of-three: sort a[lo], a[p], a[up]
713        state.table_get_i(1, p as i64)?;  // push a[p]
714        state.table_get_i(1, lo as i64)?; // push a[lo]
715        if sort_comp(state, -2, -1)? {
716            set2(state, p, lo)?; // swap a[p] ↔ a[lo]; stack clean
717        } else {
718            state.pop_n(1); // remove a[lo]; stack: a[p]
719            state.table_get_i(1, up as i64)?; // push a[up]; stack: a[p], a[up]
720            if sort_comp(state, -1, -2)? {
721                set2(state, p, up)?; // swap a[p] ↔ a[up]; stack clean
722            } else {
723                state.pop_n(2); // remove a[up] and a[p]; stack clean
724            }
725        }
726        // Stack is clean at this point.
727        if up - lo == 2 {
728            return Ok(()); // only 3 elements, now sorted
729        }
730
731        // Step 4: move pivot to a[up-1] and call partition.
732        //
733        // Stack evolution:
734        //   table_get_i(p):    a[p]  (-1)
735        //   push_value_at(-1): a[p]  (-2), a[p]_copy  (-1)
736        //   table_get_i(up-1): a[p]  (-3), a[p]_copy  (-2), a[up-1]  (-1)
737        //   set2(p, up-1):     table[p] = a[up-1], table[up-1] = a[p]_copy;
738        //                      stack: a[p] (-1)  ← pivot for partition
739        state.table_get_i(1, p as i64)?;
740        state.push_value_at(-1)?; // duplicate: two copies of pivot on stack
741        state.table_get_i(1, (up - 1) as i64)?;
742        set2(state, p, up - 1)?;
743        // One copy of the pivot value remains at the stack top for partition.
744
745        p = partition(state, lo, up)?;
746        // Stack is clean after partition returns.
747
748        // Step 5: recurse on smaller partition; tail-loop on larger.
749        let n: IdxT;
750        if p - lo < up - p {
751            aux_sort(state, lo, p - 1, rnd)?;
752            n = p - lo;
753            lo = p + 1; // tail: sort [p+1 .. up]
754        } else {
755            aux_sort(state, p + 1, up, rnd)?;
756            n = up - p;
757            up = p - 1; // tail: sort [lo .. p-1]
758        }
759
760        // Re-randomise if the partition was severely imbalanced.
761        if (up - lo) / 128 > n {
762            rnd = randomize_pivot();
763        }
764    }
765    Ok(())
766}
767
768///
769/// ```c
770/// static int sort (lua_State *L) {
771///   lua_Integer n = aux_getn(L, 1, TAB_RW);
772///   if (n > 1) {
773///     luaL_argcheck(L, n < INT_MAX, 1, "array too big");
774///     if (!lua_isnoneornil(L, 2))
775///       luaL_checktype(L, 2, LUA_TFUNCTION);
776///     lua_settop(L, 2);
777///     auxsort(L, 1, (IdxT)n, 0);
778///   }
779///   return 0;
780/// }
781/// ```
782pub fn sort(state: &mut LuaState) -> Result<usize, LuaError> {
783    let n = aux_getn(state, 1, TAB_RW)?;
784    if n > 1 {
785        if !(n < i32::MAX as i64) {
786            return Err(LuaError::arg_error(1, "array too big"));
787        }
788        if !matches!(state.type_at(2), LuaType::None | LuaType::Nil) {
789            state.check_arg_type(2, LuaType::Function)?;
790        }
791        // Must go through the public C-API set_top (relative to the call
792        // frame); the inherent LuaState::set_top treats its argument as
793        // an absolute stack slot and would corrupt the frame.
794        lua_vm::api::set_top(state, 2)?;
795        aux_sort(state, 1, n as IdxT, 0)?;
796    }
797    Ok(0)
798}
799
800// ─── Registration ─────────────────────────────────────────────────────────────
801
802///
803/// ```c
804/// static const luaL_Reg tab_funcs[] = {
805///   {"concat", tconcat}, {"insert", tinsert}, {"pack", tpack},
806///   {"unpack", tunpack}, {"remove", tremove}, {"move", tmove},
807///   {"sort", sort}, {NULL, NULL}
808/// };
809/// ```
810///
811/// PORT NOTE: In Rust we represent this as a slice of `(&[u8], fn-ptr)` pairs;
812/// the sentinel `{NULL, NULL}` is implicit (the slice has a known length).
813pub const TABLE_FUNCS: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
814    (b"concat", concat),
815    (b"insert", insert),
816    (b"pack", pack),
817    (b"unpack", unpack),
818    (b"remove", remove),
819    (b"move", tmove),
820    (b"sort", sort),
821];
822
823// ─── Module opener ────────────────────────────────────────────────────────────
824
825///
826/// ```c
827/// LUAMOD_API int luaopen_table (lua_State *L) {
828///   luaL_newlib(L, tab_funcs);
829///   return 1;
830/// }
831/// ```
832pub fn open_table(state: &mut LuaState) -> Result<usize, LuaError> {
833    // TODO(port): state.new_lib → luaL_newlib; creates a new table and registers functions;
834    //             verify method name and signature
835    state.new_lib(TABLE_FUNCS)?;
836    Ok(1)
837}
838
839// ──────────────────────────────────────────────────────────────────────────────
840// PORT STATUS
841//   source:        src/ltablib.c  (430 lines, 14 functions)
842//   target_crate:  lua-stdlib
843//   confidence:    medium
844//   todos:         17
845//   port_notes:    5
846//   unsafe_blocks: 0
847//   notes:         Logic is faithfully translated. All TODOs are method-name
848//                  uncertainties for LuaState API calls (table_get_i, table_set_i,
849//                  opt_arg_integer, opt_arg_lstring, get_metatable, to_bytes_at,
850//                  push_lstring, push_value_at, compare, new_lib, set_top,
851//                  check_stack_growth, type_name_str_at, create_table) — Phase B
852//                  maps these to the real method names once lua-vm is drafted.
853//                  Stack cleanup on error paths is elided (C uses longjmp);
854//                  needs Phase B attention in check_tab and add_field.
855//                  PERF: remove() and insert() shift loops now cache the table
856//                  value once (via value_at) and call table_get_i_value /
857//                  table_set_i_value, bypassing the per-iteration index_to_value
858//                  call. This shrank the index_to_value hot frame and improved
859//                  table_ops_long from ~4.76x to ~4.02x vs reference.
860// ──────────────────────────────────────────────────────────────────────────────