Skip to main content

lua_stdlib/
utf8_lib.rs

1//! UTF-8 standard library for Lua 5.4.
2//!
3//! Port of `lutf8lib.c` (291 lines, 9 functions).
4//!
5//! Provides the `utf8` module with `char`, `codepoint`, `codes`, `len`,
6//! `offset`, and `charpattern`. Supports both strict (Unicode-conformant)
7//! and lax (extended UTF-8, up to `MAX_UTF = 0x7FFFFFFF`) decoding modes.
8//!
9//! Strict mode rejects surrogates (U+D800..U+DFFF) and values above U+10FFFF.
10//! Lax mode accepts any well-formed byte sequence with a value ≤ MAX_UTF.
11
12use lua_types::error::LuaError;
13use lua_types::value::LuaValue;
14use crate::state_stub::{LuaState, LuaStateStubExt as _};
15
16const MAX_UNICODE: u32 = 0x10_FFFF;
17
18const MAX_UTF: u32 = 0x7FFF_FFFF;
19
20// 31 bits are needed for MAX_UTF; u32 is sufficient on all Rust targets.
21type UtfInt = u32;
22
23// sizeof(UTF8PATT)/sizeof(char) - 1 = 14 bytes (contains an embedded NUL).
24const UTF8_PATT: &[u8] = b"[\x00-\x7F\xC2-\xFD][\x80-\xBF]*";
25
26// ── Internal helpers ───────────────────────────────────────────────────────
27
28/// Translate a relative string position: negative values count backward from end.
29///
30fn pos_relat(pos: i64, len: usize) -> i64 {
31    if pos >= 0 {
32        pos
33    } else {
34        // 0u - (size_t)pos is the magnitude of pos as an unsigned value.
35        let abs_pos = pos.unsigned_abs() as u64;
36        if abs_pos > len as u64 {
37            0
38        } else {
39            len as i64 + pos + 1
40        }
41    }
42}
43
44/// Return `true` if byte `c` is a UTF-8 continuation byte (`10xxxxxx`).
45///
46#[inline]
47fn is_cont(c: u8) -> bool {
48    (c & 0xC0) == 0x80
49}
50
51/// Return `true` if the byte at 0-based index `pos` in `s` is a continuation
52/// byte, treating out-of-bounds positions as non-continuation.
53///
54/// C strings carry a NUL terminator that is never a continuation byte;
55/// the bounds-check here replaces that guarantee.
56#[inline]
57fn is_cont_at(s: &[u8], pos: i64) -> bool {
58    if pos < 0 {
59        return false;
60    }
61    s.get(pos as usize).map_or(false, |&b| is_cont(b))
62}
63
64/// Decode one UTF-8 sequence from the start of `s`.
65///
66/// Returns `None` if the byte sequence is invalid.
67/// Returns `Some((remaining_slice, codepoint))` on success.
68///
69/// When `strict` is `true`, surrogates and values above `MAX_UNICODE` are
70/// rejected. When `false`, any value ≤ `MAX_UTF` is accepted (extended UTF-8).
71///
72fn utf8_decode(s: &[u8], strict: bool) -> Option<(&[u8], UtfInt)> {
73    // LIMITS[count] is the minimum value for a sequence with `count` continuation bytes.
74    // LIMITS[0] = u32::MAX forces an error when a non-ASCII byte has no continuation bytes.
75    const LIMITS: [UtfInt; 6] = [u32::MAX, 0x80, 0x800, 0x10000, 0x200000, 0x4000000];
76
77    if s.is_empty() {
78        return None;
79    }
80
81    let mut c = s[0] as u32;
82    let res: UtfInt;
83    let advance: usize;
84
85    if c < 0x80 {
86        // ASCII fast path — no continuation bytes needed.
87        res = c;
88        advance = 1;
89    } else {
90        let mut count: usize = 0;
91        let mut r: UtfInt = 0;
92
93        // The C for-loop runs the body first, then applies `c <<= 1` as the update.
94        while c & 0x40 != 0 {
95            count += 1;
96            if count >= s.len() {
97                return None; // string too short for the indicated sequence length
98            }
99            let cc = s[count] as u32;
100
101            if (cc & 0xC0) != 0x80 {
102                return None; // expected continuation byte, got something else
103            }
104
105            r = (r << 6) | (cc & 0x3F);
106
107            // C for-loop update: c <<= 1
108            c <<= 1;
109        }
110
111        r |= (c & 0x7F) << (count as u32 * 5);
112
113        if count > 5 || r > MAX_UTF || r < LIMITS[count] {
114            return None; // invalid (overlong, too large, or excess continuation bytes)
115        }
116
117        res = r;
118        advance = count + 1;
119        if advance > s.len() {
120            return None;
121        }
122    }
123
124    if strict && (res > MAX_UNICODE || (0xD800 <= res && res <= 0xDFFF)) {
125        return None; // surrogate or out-of-Unicode-range value in strict mode
126    }
127
128    Some((&s[advance..], res))
129}
130
131/// Encode a codepoint (≤ `MAX_UTF`) as extended UTF-8 bytes.
132///
133/// Mirrors `luaO_utf8esc` from `lobject.c`, which fills a fixed buffer backwards.
134/// This Rust version builds the bytes naturally and returns a `Vec<u8>`.
135///
136fn encode_utf8_codepoint(code: u32) -> Vec<u8> {
137    debug_assert!(code <= MAX_UTF);
138
139    if code < 0x80 {
140        return vec![code as u8];
141    }
142
143    let mut x = code;
144    let mut mfb: u32 = 0x3F;
145    // Continuation bytes built in reverse, then reversed at the end.
146    let mut bytes_rev: Vec<u8> = Vec::with_capacity(6);
147
148    //    while (x > mfb);
149    loop {
150        bytes_rev.push(0x80 | (x & 0x3F) as u8);
151        x >>= 6;
152        mfb >>= 1;
153        if x <= mfb {
154            break;
155        }
156    }
157
158    // wrapping_shl avoids a Rust debug-mode overflow panic on `!mfb << 1`
159    // (e.g., !0x1Fu32 = 0xFFFF_FFE0; << 1 = 0xFFFF_FFC0; as u8 = 0xC0).
160    let leading = ((!mfb).wrapping_shl(1) as u8) | (x as u8);
161
162    let mut result = Vec::with_capacity(bytes_rev.len() + 1);
163    result.push(leading);
164    for &b in bytes_rev.iter().rev() {
165        result.push(b);
166    }
167    result
168}
169
170// ── Library functions ──────────────────────────────────────────────────────
171
172/// `utf8.len(s [, i [, j [, lax]]])` → integer | (nil, integer)
173///
174/// Returns the number of UTF-8 characters that start in the byte range `[i,j]`
175/// of string `s` (1-based, defaulting to the whole string).
176/// On a malformed sequence, returns `(nil, position)` where `position` is the
177/// 1-based byte offset of the first bad byte.
178///
179fn utf_len(state: &mut LuaState) -> Result<usize, LuaError> {
180    // Clone to avoid holding a borrow across subsequent mutable state calls.
181    let s: Vec<u8> = state.check_arg_string(1)?.to_vec();
182    let len = s.len();
183
184    // TODO(port): opt_arg_integer(narg, default) not yet in LuaState API; adjust in Phase B.
185    let raw_posi: i64 = state.opt_arg_integer(2, 1)?;
186    let mut posi: i64 = pos_relat(raw_posi, len);
187
188    // TODO(port): opt_arg_integer API (second call site).
189    let raw_posj: i64 = state.opt_arg_integer(3, -1)?;
190    let mut posj: i64 = pos_relat(raw_posj, len);
191
192    // TODO(port): to_boolean(n) method not yet confirmed in LuaState API.
193    let lax: bool = state.to_boolean(4);
194
195    // Note: C short-circuits, so --posi only executes when 1 <= posi.
196    if posi < 1 {
197        return Err(LuaError::arg_error(2, "initial position out of bounds"));
198    }
199    posi -= 1; // 1-based → 0-based
200    if posi > len as i64 {
201        return Err(LuaError::arg_error(2, "initial position out of bounds"));
202    }
203
204    posj -= 1; // 1-based → 0-based (always decremented, no short-circuit)
205    if posj >= len as i64 {
206        return Err(LuaError::arg_error(3, "final position out of bounds"));
207    }
208
209    let mut n: i64 = 0;
210
211    while posi <= posj {
212        match utf8_decode(&s[posi as usize..], !lax) {
213            None => {
214                state.push(LuaValue::Nil); // luaL_pushfail
215                state.push(LuaValue::Int(posi + 1)); // 1-based position of failure
216                return Ok(2);
217            }
218            Some((remaining, _)) => {
219                posi = (len - remaining.len()) as i64;
220                n += 1;
221            }
222        }
223    }
224
225    state.push(LuaValue::Int(n));
226    Ok(1)
227}
228
229/// `utf8.codepoint(s [, i [, j [, lax]]])` → integer, ...
230///
231/// Returns the codepoints (as integers) for all characters starting in `s[i..j]`.
232///
233fn codepoint(state: &mut LuaState) -> Result<usize, LuaError> {
234    let s: Vec<u8> = state.check_arg_string(1)?.to_vec();
235    let len = s.len();
236
237    // TODO(port): opt_arg_integer API (codepoint start position).
238    let raw_posi: i64 = state.opt_arg_integer(2, 1)?;
239    let posi: i64 = pos_relat(raw_posi, len);
240
241    // Default for the end position is posi (1-based), giving a single character.
242    // TODO(port): opt_arg_integer API (codepoint end position).
243    let raw_pose: i64 = state.opt_arg_integer(3, posi)?;
244    let pose: i64 = pos_relat(raw_pose, len);
245
246    // TODO(port): to_boolean API (codepoint lax mode).
247    let lax: bool = state.to_boolean(4);
248
249    if posi < 1 {
250        return Err(LuaError::arg_error(2, "out of bounds"));
251    }
252
253    if pose > len as i64 {
254        return Err(LuaError::arg_error(3, "out of bounds"));
255    }
256
257    if posi > pose {
258        return Ok(0); // empty interval: no values
259    }
260
261    if pose - posi >= i32::MAX as i64 {
262        return Err(LuaError::runtime(format_args!("string slice too long")));
263    }
264
265    let n_max = (pose - posi + 1) as i32;
266    state.ensure_stack(n_max, "string slice too long")?;
267
268    // 0-based: start at (posi - 1), stop before byte index `pose`.
269    let mut pos: usize = (posi - 1) as usize; // 0-based start
270    let end: usize = pose as usize; // 0-based exclusive end
271    let mut count: usize = 0;
272
273    while pos < end {
274        match utf8_decode(&s[pos..], !lax) {
275            None => return Err(LuaError::runtime(format_args!("invalid UTF-8 code"))),
276            Some((remaining, code)) => {
277                state.push(LuaValue::Int(code as i64));
278                count += 1;
279                pos = len - remaining.len(); // advance by decoded character width
280            }
281        }
282    }
283
284    Ok(count)
285}
286
287/// Encode the codepoint at stack argument `arg` and return the UTF-8 bytes.
288///
289/// `Vec<u8>` directly rather than pushing to the stack, avoiding the push/pop
290/// dance that `luaL_Buffer` required.
291///
292/// PORT NOTE: C's `pushutfchar` called `lua_pushfstring(L, "%U", code)` to encode
293/// and push in one step. Here the encoding is extracted so `utf_char` can build
294/// the concatenated result without intermediate stack operations.
295fn get_utf_char_bytes(state: &mut LuaState, arg: i32) -> Result<Vec<u8>, LuaError> {
296    let code = state.check_arg_integer(arg)? as u64;
297
298    if code > MAX_UTF as u64 {
299        return Err(LuaError::arg_error(arg, "value out of range"));
300    }
301
302    Ok(encode_utf8_codepoint(code as u32))
303}
304
305/// `utf8.char(n1, n2, ...)` → string
306///
307/// Returns a string formed by the UTF-8 encoding of the given codepoints.
308///
309fn utf_char(state: &mut LuaState) -> Result<usize, LuaError> {
310    // TODO(port): stack_top() / arg_count() API on LuaState not yet confirmed.
311    let n: i32 = state.stack_top() as i32;
312
313    if n == 1 {
314        let bytes = get_utf_char_bytes(state, 1)?;
315        let s = state.intern_str(&bytes)?;
316        state.push(LuaValue::Str(s));
317    } else {
318        //    for (i = 1; i <= n; i++) { pushutfchar(L, i); luaL_addvalue(&b); }
319        //    luaL_pushresult(&b);
320        // PORT NOTE: luaL_Buffer replaced by Vec<u8>; codepoints are encoded
321        // directly into the accumulator without intermediate stack push/pop.
322        let mut buf: Vec<u8> = Vec::new();
323        for i in 1..=n {
324            buf.extend_from_slice(&get_utf_char_bytes(state, i)?);
325        }
326        let s = state.intern_str(&buf)?;
327        state.push(LuaValue::Str(s));
328    }
329
330    Ok(1)
331}
332
333/// `utf8.offset(s, n [, i])` → integer | nil
334///
335/// Returns the byte offset where the n-th character (counting from position `i`)
336/// starts. Negative `n` counts from the end. `n == 0` returns the start of the
337/// character that contains position `i`.
338/// Returns `nil` if the character cannot be found.
339///
340fn byte_offset(state: &mut LuaState) -> Result<usize, LuaError> {
341    let s: Vec<u8> = state.check_arg_string(1)?.to_vec();
342    let len = s.len();
343
344    let n: i64 = state.check_arg_integer(2)?;
345
346    let default_posi: i64 = if n >= 0 { 1 } else { len as i64 + 1 };
347
348    // TODO(port): opt_arg_integer API (byte_offset position argument).
349    let raw_posi: i64 = state.opt_arg_integer(3, default_posi)?;
350    let posi_1based: i64 = pos_relat(raw_posi, len);
351
352    if posi_1based < 1 {
353        return Err(LuaError::arg_error(3, "position out of bounds"));
354    }
355    let mut posi: i64 = posi_1based - 1; // 1-based → 0-based
356    if posi > len as i64 {
357        return Err(LuaError::arg_error(3, "position out of bounds"));
358    }
359
360    // `count` is a mutable copy of `n`; driven to 0 when the target character is found.
361    let mut count = n;
362
363    if count == 0 {
364        // Scan backward to find the start of the character containing `posi`.
365        while posi > 0 && is_cont_at(&s, posi) {
366            posi -= 1;
367        }
368        // count remains 0
369    } else {
370        if is_cont_at(&s, posi) {
371            return Err(LuaError::runtime(format_args!(
372                "initial position is a continuation byte"
373            )));
374        }
375
376        if count < 0 {
377            //      do { posi--; } while (posi > 0 && iscontp(s + posi));
378            //      n++;
379            //    }
380            while count < 0 && posi > 0 {
381                // do-while: always decrements at least once, then skips back over
382                // any continuation bytes to land on a leading byte.
383                loop {
384                    posi -= 1;
385                    if posi == 0 || !is_cont_at(&s, posi) {
386                        break;
387                    }
388                }
389                count += 1;
390            }
391        } else {
392            //    while (n > 0 && posi < (lua_Integer)len) {
393            //      do { posi++; } while (iscontp(s + posi));  /* cannot pass '\0' */
394            //      n--;
395            //    }
396            count -= 1; // do not move for the 1st character
397            while count > 0 && posi < len as i64 {
398                // C relies on the NUL terminator to stop the inner do-while.
399                // Rust uses an explicit bounds check instead.
400                loop {
401                    posi += 1;
402                    if !is_cont_at(&s, posi) {
403                        break;
404                    }
405                }
406                count -= 1;
407            }
408        }
409    }
410
411    if count == 0 {
412        state.push(LuaValue::Int(posi + 1)); // 0-based → 1-based
413    } else {
414        state.push(LuaValue::Nil); // luaL_pushfail: character not found
415    }
416    Ok(1)
417}
418
419/// Internal iterator body shared by `iter_aux_strict` and `iter_aux_lax`.
420///
421/// Stack on entry (from the generic for): (1) string, (2) current byte position
422/// (0-based; initially pushed as 0 by `iter_codes`).
423///
424/// Advances past any leading continuation bytes, decodes the next character,
425/// and returns `(next_1based_pos, codepoint)`.  Returns nothing (0) when the
426/// string is exhausted.
427///
428fn iter_aux(state: &mut LuaState, strict: bool) -> Result<usize, LuaError> {
429    let s: Vec<u8> = state.check_arg_string(1)?.to_vec();
430    let len = s.len();
431
432    // TODO(port): to_integer(n) exact return type (i64/Option<i64>) not yet confirmed;
433    // treating as i64 cast to u64 for unsigned byte-index arithmetic.
434    let mut n: u64 = state.to_integer(2).unwrap_or(0) as u64;
435
436    if (n as usize) < len {
437        while (n as usize) < len && is_cont(s[n as usize]) {
438            n += 1;
439        }
440    }
441
442    if (n as usize) >= len {
443        return Ok(0); // no more codepoints
444    }
445
446    //    if (next == NULL || iscontp(next)) return luaL_error(L, MSGInvalid);
447    match utf8_decode(&s[n as usize..], strict) {
448        None => Err(LuaError::runtime(format_args!("invalid UTF-8 code"))),
449        Some((remaining, code)) => {
450            let next_pos = len - remaining.len(); // 0-based index of the next character
451            // valid sequence indicates a malformed input stream.
452            if next_pos < len && is_cont(s[next_pos]) {
453                return Err(LuaError::runtime(format_args!("invalid UTF-8 code")));
454            }
455            state.push(LuaValue::Int((n + 1) as i64)); // 1-based position for next iteration
456            state.push(LuaValue::Int(code as i64));
457            Ok(2)
458        }
459    }
460}
461
462/// Strict iterator body: rejects surrogates and values > MAX_UNICODE.
463///
464fn iter_aux_strict(state: &mut LuaState) -> Result<usize, LuaError> {
465    iter_aux(state, true)
466}
467
468/// Lax iterator body: accepts extended UTF-8 up to MAX_UTF.
469///
470fn iter_aux_lax(state: &mut LuaState) -> Result<usize, LuaError> {
471    iter_aux(state, false)
472}
473
474/// `utf8.codes(s [, lax])` → function, string, integer
475///
476/// Returns the iterator triple `(f, s, 0)` for use in a generic for loop.
477/// Each call to `f(s, pos)` returns the next `(pos, codepoint)` pair.
478///
479fn iter_codes(state: &mut LuaState) -> Result<usize, LuaError> {
480    // TODO(port): to_boolean API (iter_codes lax mode).
481    let lax: bool = state.to_boolean(2);
482
483    let s: Vec<u8> = state.check_arg_string(1)?.to_vec();
484
485    // The very first byte of the string must not be a continuation byte.
486    if s.first().map_or(false, |&b| is_cont(b)) {
487        return Err(LuaError::arg_error(1, "invalid UTF-8 code"));
488    }
489
490    // TODO(phase-b): LuaClosure::LightC in lua-types is fn() -> i32; needs widening to the real lua_CFunction signature. Stub via push_c_function until then.
491    let iter_fn: fn(&mut LuaState) -> Result<usize, LuaError> =
492        if lax { iter_aux_lax } else { iter_aux_strict };
493    state.push_c_function(iter_fn)?;
494
495    // TODO(port): push_value_at(idx) not yet confirmed in LuaState API.
496    state.push_value_at(1)?;
497
498    state.push(LuaValue::Int(0));
499
500    Ok(3)
501}
502
503// ── Library registration ───────────────────────────────────────────────────
504
505/// Function registration table for the `utf8` library.
506///
507/// "charpattern" is intentionally absent here; it is a string value and is
508/// registered separately inside `open_utf8` via `lua_setfield`.
509pub const FUNCS: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
510    (b"offset", byte_offset),
511    (b"codepoint", codepoint),
512    (b"char", utf_char),
513    (b"len", utf_len),
514    (b"codes", iter_codes),
515];
516
517/// Open the `utf8` library.
518///
519/// Registers all functions from `FUNCS` into a new table, then sets
520/// `utf8.charpattern` to the byte-string pattern matching one UTF-8 sequence.
521///
522pub fn open_utf8(state: &mut LuaState) -> Result<usize, LuaError> {
523    // TODO(port): new_lib(funcs) API on LuaState not yet confirmed; expected to
524    // create a new table and register all (name, fn) pairs from FUNCS.
525    state.new_lib(FUNCS)?;
526
527    let patt = state.intern_str(UTF8_PATT)?;
528    state.push(LuaValue::Str(patt));
529
530    // TODO(port): set_field(table_idx, field_name) API on LuaState not yet confirmed.
531    state.set_field(-2, b"charpattern")?;
532
533    Ok(1)
534}
535
536// ──────────────────────────────────────────────────────────────────────────
537// PORT STATUS
538//   source:        src/lutf8lib.c  (291 lines, 9 functions)
539//   target_crate:  lua-stdlib
540//   confidence:    medium
541//   todos:         13
542//   port_notes:    2
543//   unsafe_blocks: 0   (must be 0 outside explicit unsafe-budget crates)
544//   notes:         Core UTF-8 logic (utf8_decode, encode_utf8_codepoint,
545//                  pos_relat, is_cont_at) is a faithful translation and should
546//                  be correct. All 13 TODOs are unresolved LuaState API names:
547//                  opt_arg_integer, to_boolean, stack_top, push_value_at,
548//                  new_lib, set_field, and to_integer — Phase B reconciles
549//                  these against the actual method signatures. No unsafe
550//                  blocks; NUL-terminator reliance in C replaced by Rust
551//                  bounds checks throughout.
552// ──────────────────────────────────────────────────────────────────────────