Skip to main content

rustia/
value.rs

1use crate::{Error, Result};
2use rustia_vm::{Error as VmError, ErrorKind as VmErrorKind, Value as RawValue, ValueKind, Vm};
3use std::any::type_name;
4use std::collections::BTreeMap;
5
6const SNAPSHOT_DEPTH_LIMIT: usize = 64;
7
8/// A Rust-owned copy of a script value.
9///
10/// Use this for ordinary data that should outlive the VM or a
11/// [`reset_decision`](crate::Rustia::reset_decision). Tables are copied
12/// recursively; changes to the original script table do not affect the copy.
13///
14/// This representation supports UTF-8 strings and acyclic tables with boolean,
15/// number, or string keys. Use a live [`crate::Value`] for binary strings,
16/// functions, buffers, vectors, userdata, or shared and cyclic table identity.
17#[derive(Clone, Debug, PartialEq)]
18pub enum OwnedValue {
19    Nil,
20    Boolean(bool),
21    Number(f64),
22    String(String),
23    Table(OwnedTable),
24}
25
26/// A Rust-owned table, split into sequence values and keyed entries.
27///
28/// The `array` field uses zero-based Rust indices, corresponding to Luau
29/// keys `1`, `2`, and so on. When a script table is copied, a contiguous sequence
30/// becomes `array`; a sparse or mixed-key table becomes `entries`.
31#[derive(Clone, Debug, Default, PartialEq)]
32pub struct OwnedTable {
33    /// Sequence values, starting at Luau index `1`.
34    pub array: Vec<OwnedValue>,
35    /// Keyed values in their snapshot order.
36    pub entries: Vec<(OwnedKey, OwnedValue)>,
37}
38
39/// A key supported by an [`OwnedTable`].
40#[derive(Clone, Debug, PartialEq)]
41pub enum OwnedKey {
42    Boolean(bool),
43    Number(f64),
44    String(String),
45}
46
47impl OwnedTable {
48    /// Creates an empty table.
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    /// Creates a sequence from values that are already converted.
54    pub fn array(values: impl IntoIterator<Item = OwnedValue>) -> Self {
55        Self {
56            array: values.into_iter().collect(),
57            entries: Vec::new(),
58        }
59    }
60
61    /// Creates a table from keys and values that are already converted.
62    pub fn entries(entries: impl IntoIterator<Item = (OwnedKey, OwnedValue)>) -> Self {
63        Self {
64            array: Vec::new(),
65            entries: entries.into_iter().collect(),
66        }
67    }
68
69    /// Looks up a string key without converting or cloning its value.
70    pub fn get_string(&self, key: &str) -> Option<&OwnedValue> {
71        self.entries.iter().find_map(|(entry_key, value)| {
72            matches!(entry_key, OwnedKey::String(found) if found == key).then_some(value)
73        })
74    }
75
76    /// Returns a borrowed table for a string key, or an error if the key holds a non-table value.
77    pub fn get_string_table(&self, key: &str) -> Result<Option<&OwnedTable>> {
78        self.get_string(key).map(expect_table_ref).transpose()
79    }
80
81    /// Returns an owned-array slot by zero-based Rust index. Luau index 1 is slot 0.
82    pub fn get_array(&self, index: usize) -> Option<&OwnedValue> {
83        self.array.get(index)
84    }
85
86    /// Returns a borrowed table for an array slot, or an error if the slot holds a non-table value.
87    pub fn get_array_table(&self, index: usize) -> Result<Option<&OwnedTable>> {
88        self.get_array(index).map(expect_table_ref).transpose()
89    }
90}
91
92impl OwnedValue {
93    /// Returns the corresponding Luau type name.
94    pub fn type_name(&self) -> &'static str {
95        match self {
96            Self::Nil => "nil",
97            Self::Boolean(_) => "boolean",
98            Self::Number(_) => "number",
99            Self::String(_) => "string",
100            Self::Table(_) => "table",
101        }
102    }
103
104    /// Borrows the table contents, or returns `None` for another value kind.
105    pub fn table(&self) -> Option<&OwnedTable> {
106        match self {
107            Self::Table(table) => Some(table),
108            _ => None,
109        }
110    }
111}
112
113/// Converts a Rust value to an owned script value.
114///
115/// Implementations include numbers, strings, `Option<T>`, `Vec<T>`, and
116/// `BTreeMap<String, T>`. `None` becomes `nil`; vectors become one-based Luau
117/// sequences. Integer conversions reject values that cannot be represented
118/// exactly as a Luau number.
119pub trait IntoRustia {
120    /// Converts this value, returning an error if it cannot be represented.
121    fn into_rustia(self) -> Result<OwnedValue>;
122}
123
124/// Converts an owned script value to a Rust value.
125///
126/// Conversions check the requested type rather than applying Luau coercions.
127/// `Option<T>` accepts `nil` as `None`; integer types require a finite, whole
128/// number in range. `Vec<T>` requires a sequence without keyed entries, while
129/// `BTreeMap<String, T>` requires string keys without sequence entries.
130pub trait FromRustia: Sized {
131    /// Converts a value, returning an error for an incompatible type or range.
132    fn from_rustia(value: OwnedValue) -> Result<Self>;
133}
134
135impl OwnedTable {
136    /// Converts Rust values into a one-based Luau sequence.
137    pub fn array_values<T>(values: impl IntoIterator<Item = T>) -> Result<Self>
138    where
139        T: IntoRustia,
140    {
141        Ok(Self {
142            array: values
143                .into_iter()
144                .map(IntoRustia::into_rustia)
145                .collect::<Result<Vec<_>>>()?,
146            entries: Vec::new(),
147        })
148    }
149
150    /// Converts Rust values into a table with string keys.
151    pub fn string_entries<K, V>(entries: impl IntoIterator<Item = (K, V)>) -> Result<Self>
152    where
153        K: Into<String>,
154        V: IntoRustia,
155    {
156        Ok(Self {
157            array: Vec::new(),
158            entries: entries
159                .into_iter()
160                .map(|(key, value)| {
161                    value
162                        .into_rustia()
163                        .map(|value| (OwnedKey::String(key.into()), value))
164                })
165                .collect::<Result<Vec<_>>>()?,
166        })
167    }
168
169    /// Reads and converts a string-keyed value. Missing keys return `None`.
170    pub fn get_string_as<T>(&self, key: &str) -> Result<Option<T>>
171    where
172        T: FromRustia,
173    {
174        self.get_string(key)
175            .cloned()
176            .map(T::from_rustia)
177            .transpose()
178    }
179
180    /// Converts an owned-array slot by zero-based Rust index. Luau index 1 is slot 0.
181    pub fn get_array_as<T>(&self, index: usize) -> Result<Option<T>>
182    where
183        T: FromRustia,
184    {
185        self.get_array(index)
186            .cloned()
187            .map(T::from_rustia)
188            .transpose()
189    }
190}
191
192/// Converts function arguments or results to a list of script values.
193///
194/// A single value becomes one argument, `()` becomes no arguments, and tuples
195/// through eight elements become separate arguments. A `Vec<T>` is one Luau
196/// sequence table, not a list of arguments.
197pub trait IntoRustiaMulti {
198    /// Converts the complete argument or result list.
199    fn into_rustia_multi(self) -> Result<Vec<OwnedValue>>;
200
201    /// Returns Rust type names used by host-function signature metadata.
202    fn rustia_type_names() -> Vec<&'static str>
203    where
204        Self: Sized,
205    {
206        vec![type_name::<Self>()]
207    }
208}
209
210/// Converts a script's return values to a Rust value or tuple.
211///
212/// A single type reads the first result; tuples through eight elements read
213/// successive results. Missing results are treated as `nil`, extra results are
214/// ignored, and `()` discards all results. Each selected result still has to
215/// satisfy its [`FromRustia`] conversion.
216///
217/// Owned execution methods copy every result into [`OwnedValue`] before calling
218/// this trait, including results that will be discarded. Use live-value methods
219/// when any result cannot be represented by [`OwnedValue`].
220pub trait FromRustiaMulti: Sized {
221    /// Converts the selected return values.
222    fn from_rustia_multi(values: Vec<OwnedValue>) -> Result<Self>;
223}
224
225impl IntoRustia for OwnedValue {
226    fn into_rustia(self) -> Result<OwnedValue> {
227        Ok(self)
228    }
229}
230
231impl FromRustia for OwnedValue {
232    fn from_rustia(value: OwnedValue) -> Result<Self> {
233        Ok(value)
234    }
235}
236
237impl IntoRustia for OwnedTable {
238    fn into_rustia(self) -> Result<OwnedValue> {
239        Ok(OwnedValue::Table(self))
240    }
241}
242
243impl FromRustia for OwnedTable {
244    fn from_rustia(value: OwnedValue) -> Result<Self> {
245        match value {
246            OwnedValue::Table(table) => Ok(table),
247            other => type_error("table", &other),
248        }
249    }
250}
251
252impl IntoRustia for () {
253    fn into_rustia(self) -> Result<OwnedValue> {
254        Ok(OwnedValue::Nil)
255    }
256}
257
258impl FromRustia for () {
259    fn from_rustia(_value: OwnedValue) -> Result<Self> {
260        Ok(())
261    }
262}
263
264impl IntoRustia for bool {
265    fn into_rustia(self) -> Result<OwnedValue> {
266        Ok(OwnedValue::Boolean(self))
267    }
268}
269
270impl FromRustia for bool {
271    fn from_rustia(value: OwnedValue) -> Result<Self> {
272        match value {
273            OwnedValue::Boolean(value) => Ok(value),
274            other => type_error("boolean", &other),
275        }
276    }
277}
278
279impl IntoRustia for f64 {
280    fn into_rustia(self) -> Result<OwnedValue> {
281        Ok(OwnedValue::Number(self))
282    }
283}
284
285impl FromRustia for f64 {
286    fn from_rustia(value: OwnedValue) -> Result<Self> {
287        match value {
288            OwnedValue::Number(value) => Ok(value),
289            other => type_error("number", &other),
290        }
291    }
292}
293
294impl IntoRustia for f32 {
295    fn into_rustia(self) -> Result<OwnedValue> {
296        Ok(OwnedValue::Number(f64::from(self)))
297    }
298}
299
300impl FromRustia for f32 {
301    fn from_rustia(value: OwnedValue) -> Result<Self> {
302        f64::from_rustia(value).map(|value| value as f32)
303    }
304}
305
306macro_rules! impl_signed_integer_value {
307    ($($ty:ty),* $(,)?) => {
308        $(
309            impl IntoRustia for $ty {
310                fn into_rustia(self) -> Result<OwnedValue> {
311                    let number = self as f64;
312                    if number as i128 != self as i128 {
313                        return Err(Error::embed(format!(
314                            "{} value {self} cannot be represented exactly as a Luau number",
315                            stringify!($ty)
316                        )));
317                    }
318                    Ok(OwnedValue::Number(number))
319                }
320            }
321
322            impl FromRustia for $ty {
323                fn from_rustia(value: OwnedValue) -> Result<Self> {
324                    let number = f64::from_rustia(value)?;
325                    if !number.is_finite() || number.fract() != 0.0 {
326                        return Err(Error::embed(format!(
327                            "expected integer-compatible number, got {number}"
328                        )));
329                    }
330                    let integer = number as i128;
331                    if integer < <$ty>::MIN as i128 || integer > <$ty>::MAX as i128 {
332                        return Err(Error::embed(format!(
333                            "number {number} is outside {} range",
334                            stringify!($ty)
335                        )));
336                    }
337                    Ok(integer as $ty)
338                }
339            }
340        )*
341    };
342}
343
344macro_rules! impl_unsigned_integer_value {
345    ($($ty:ty),* $(,)?) => {
346        $(
347            impl IntoRustia for $ty {
348                fn into_rustia(self) -> Result<OwnedValue> {
349                    let number = self as f64;
350                    if number as u128 != self as u128 {
351                        return Err(Error::embed(format!(
352                            "{} value {self} cannot be represented exactly as a Luau number",
353                            stringify!($ty)
354                        )));
355                    }
356                    Ok(OwnedValue::Number(number))
357                }
358            }
359
360            impl FromRustia for $ty {
361                fn from_rustia(value: OwnedValue) -> Result<Self> {
362                    let number = f64::from_rustia(value)?;
363                    if !number.is_finite() || number.fract() != 0.0 {
364                        return Err(Error::embed(format!(
365                            "expected integer-compatible number, got {number}"
366                        )));
367                    }
368                    if number < 0.0 {
369                        return Err(Error::embed(format!(
370                            "number {number} is outside {} range",
371                            stringify!($ty)
372                        )));
373                    }
374                    let integer = number as u128;
375                    if integer > <$ty>::MAX as u128 {
376                        return Err(Error::embed(format!(
377                            "number {number} is outside {} range",
378                            stringify!($ty)
379                        )));
380                    }
381                    Ok(integer as $ty)
382                }
383            }
384        )*
385    };
386}
387
388impl_signed_integer_value!(i8, i16, i32, i64, isize);
389impl_unsigned_integer_value!(u8, u16, u32, u64, usize);
390
391impl IntoRustia for String {
392    fn into_rustia(self) -> Result<OwnedValue> {
393        Ok(OwnedValue::String(self))
394    }
395}
396
397impl IntoRustia for &str {
398    fn into_rustia(self) -> Result<OwnedValue> {
399        Ok(OwnedValue::String(self.to_owned()))
400    }
401}
402
403impl FromRustia for String {
404    fn from_rustia(value: OwnedValue) -> Result<Self> {
405        match value {
406            OwnedValue::String(value) => Ok(value),
407            other => type_error("string", &other),
408        }
409    }
410}
411
412impl<T> IntoRustia for Option<T>
413where
414    T: IntoRustia,
415{
416    fn into_rustia(self) -> Result<OwnedValue> {
417        self.map_or(Ok(OwnedValue::Nil), IntoRustia::into_rustia)
418    }
419}
420
421impl<T> FromRustia for Option<T>
422where
423    T: FromRustia,
424{
425    fn from_rustia(value: OwnedValue) -> Result<Self> {
426        match value {
427            OwnedValue::Nil => Ok(None),
428            value => T::from_rustia(value).map(Some),
429        }
430    }
431}
432
433impl<T> IntoRustia for Vec<T>
434where
435    T: IntoRustia,
436{
437    fn into_rustia(self) -> Result<OwnedValue> {
438        OwnedTable::array_values(self).map(OwnedValue::Table)
439    }
440}
441
442impl<T> FromRustia for Vec<T>
443where
444    T: FromRustia,
445{
446    fn from_rustia(value: OwnedValue) -> Result<Self> {
447        match value {
448            OwnedValue::Table(table) if table.entries.is_empty() => {
449                table.array.into_iter().map(T::from_rustia).collect()
450            }
451            OwnedValue::Table(_) => Err(Error::embed(
452                "expected array table, got table with keyed entries".to_owned(),
453            )),
454            other => type_error("array table", &other),
455        }
456    }
457}
458
459impl<T> IntoRustia for BTreeMap<String, T>
460where
461    T: IntoRustia,
462{
463    fn into_rustia(self) -> Result<OwnedValue> {
464        OwnedTable::string_entries(self).map(OwnedValue::Table)
465    }
466}
467
468impl<T> FromRustia for BTreeMap<String, T>
469where
470    T: FromRustia,
471{
472    fn from_rustia(value: OwnedValue) -> Result<Self> {
473        let table = OwnedTable::from_rustia(value)?;
474        if !table.array.is_empty() {
475            return Err(Error::embed(
476                "expected string-keyed table, got table with array entries".to_owned(),
477            ));
478        }
479        table
480            .entries
481            .into_iter()
482            .map(|(key, value)| match key {
483                OwnedKey::String(key) => T::from_rustia(value).map(|value| (key, value)),
484                _ => Err(Error::embed(
485                    "expected string-keyed table, got non-string key".to_owned(),
486                )),
487            })
488            .collect()
489    }
490}
491
492macro_rules! impl_single_multi {
493    ($($ty:ty),* $(,)?) => {
494        $(
495            impl IntoRustiaMulti for $ty {
496                fn into_rustia_multi(self) -> Result<Vec<OwnedValue>> {
497                    self.into_rustia().map(|value| vec![value])
498                }
499            }
500
501            impl FromRustiaMulti for $ty {
502                fn from_rustia_multi(mut values: Vec<OwnedValue>) -> Result<Self> {
503                    let value = if values.is_empty() {
504                        OwnedValue::Nil
505                    } else {
506                        values.remove(0)
507                    };
508                    Self::from_rustia(value)
509                }
510            }
511        )*
512    };
513}
514
515impl_single_multi!(
516    OwnedValue, OwnedTable, bool, f64, f32, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize,
517    String
518);
519
520impl IntoRustiaMulti for &str {
521    fn into_rustia_multi(self) -> Result<Vec<OwnedValue>> {
522        self.into_rustia().map(|value| vec![value])
523    }
524}
525
526impl<T> IntoRustiaMulti for Option<T>
527where
528    T: IntoRustia,
529{
530    fn into_rustia_multi(self) -> Result<Vec<OwnedValue>> {
531        self.into_rustia().map(|value| vec![value])
532    }
533}
534
535impl<T> FromRustiaMulti for Option<T>
536where
537    T: FromRustia,
538{
539    fn from_rustia_multi(mut values: Vec<OwnedValue>) -> Result<Self> {
540        let value = if values.is_empty() {
541            OwnedValue::Nil
542        } else {
543            values.remove(0)
544        };
545        Self::from_rustia(value)
546    }
547}
548
549impl<T> IntoRustiaMulti for Vec<T>
550where
551    T: IntoRustia,
552{
553    fn into_rustia_multi(self) -> Result<Vec<OwnedValue>> {
554        self.into_rustia().map(|value| vec![value])
555    }
556}
557
558impl<T> FromRustiaMulti for Vec<T>
559where
560    T: FromRustia,
561{
562    fn from_rustia_multi(mut values: Vec<OwnedValue>) -> Result<Self> {
563        let value = if values.is_empty() {
564            OwnedValue::Nil
565        } else {
566            values.remove(0)
567        };
568        Self::from_rustia(value)
569    }
570}
571
572impl<T> IntoRustiaMulti for BTreeMap<String, T>
573where
574    T: IntoRustia,
575{
576    fn into_rustia_multi(self) -> Result<Vec<OwnedValue>> {
577        self.into_rustia().map(|value| vec![value])
578    }
579}
580
581impl<T> FromRustiaMulti for BTreeMap<String, T>
582where
583    T: FromRustia,
584{
585    fn from_rustia_multi(mut values: Vec<OwnedValue>) -> Result<Self> {
586        let value = if values.is_empty() {
587            OwnedValue::Nil
588        } else {
589            values.remove(0)
590        };
591        Self::from_rustia(value)
592    }
593}
594
595impl IntoRustiaMulti for () {
596    fn into_rustia_multi(self) -> Result<Vec<OwnedValue>> {
597        Ok(Vec::new())
598    }
599
600    fn rustia_type_names() -> Vec<&'static str> {
601        Vec::new()
602    }
603}
604
605impl FromRustiaMulti for () {
606    fn from_rustia_multi(_values: Vec<OwnedValue>) -> Result<Self> {
607        Ok(())
608    }
609}
610
611macro_rules! impl_tuple_multi {
612    ($($name:ident),+ $(,)?) => {
613        impl<$($name),+> IntoRustiaMulti for ($($name,)+)
614        where
615            $($name: IntoRustia,)+
616        {
617            #[allow(non_snake_case)]
618            fn into_rustia_multi(self) -> Result<Vec<OwnedValue>> {
619                let ($($name,)+) = self;
620                Ok(vec![$($name.into_rustia()?,)+])
621            }
622
623            fn rustia_type_names() -> Vec<&'static str> {
624                vec![$(type_name::<$name>()),+]
625            }
626        }
627
628        impl<$($name),+> FromRustiaMulti for ($($name,)+)
629        where
630            $($name: FromRustia,)+
631        {
632            #[allow(non_snake_case)]
633            fn from_rustia_multi(values: Vec<OwnedValue>) -> Result<Self> {
634                let mut values = values.into_iter();
635                Ok(($({
636                    let value = values.next().unwrap_or(OwnedValue::Nil);
637                    $name::from_rustia(value)?
638                },)+))
639            }
640        }
641    };
642}
643
644impl_tuple_multi!(A);
645impl_tuple_multi!(A, B);
646impl_tuple_multi!(A, B, C);
647impl_tuple_multi!(A, B, C, D);
648impl_tuple_multi!(A, B, C, D, E);
649impl_tuple_multi!(A, B, C, D, E, F);
650impl_tuple_multi!(A, B, C, D, E, F, G);
651impl_tuple_multi!(A, B, C, D, E, F, G, H);
652
653pub(crate) fn snapshot_value(vm: &mut Vm, value: RawValue) -> Result<OwnedValue> {
654    snapshot_value_inner(vm, value, 0)
655}
656
657fn snapshot_value_inner(vm: &mut Vm, value: RawValue, depth: usize) -> Result<OwnedValue> {
658    if depth > SNAPSHOT_DEPTH_LIMIT {
659        return Err(Error::embed(
660            "value snapshot exceeded recursive table depth limit".to_owned(),
661        ));
662    }
663
664    match value.kind() {
665        ValueKind::Nil => Ok(OwnedValue::Nil),
666        ValueKind::Boolean => Ok(OwnedValue::Boolean(value.as_bool().unwrap_or(false))),
667        ValueKind::Number => Ok(OwnedValue::Number(value.as_number().unwrap_or(f64::NAN))),
668        ValueKind::String => vm
669            .string_value(value)
670            .map_err(Error::from_engine)?
671            .map(OwnedValue::String)
672            .ok_or_else(|| Error::embed("string value is missing".to_owned())),
673        ValueKind::Table => snapshot_table(vm, value, depth + 1),
674        ValueKind::Function => Err(Error::embed(
675            "function values must be retained as Function handles".to_owned(),
676        )),
677        ValueKind::Userdata | ValueKind::Buffer | ValueKind::Vector => Err(Error::embed(format!(
678            "{} values cannot be represented as OwnedValue",
679            raw_kind_name(value.kind())
680        ))),
681        _ => Err(Error::embed(
682            "unknown VM value kind cannot be represented as OwnedValue".to_owned(),
683        )),
684    }
685}
686
687fn snapshot_table(vm: &mut Vm, value: RawValue, depth: usize) -> Result<OwnedValue> {
688    let mut ordered = Vec::new();
689    let mut all_array_keys = true;
690
691    for (key, value) in vm
692        .raw_table_entries_value(value)
693        .map_err(Error::from_engine)?
694    {
695        let key = snapshot_key(vm, key)?;
696        let array_index = match key {
697            OwnedKey::Number(number) => number_to_array_index(number),
698            _ => None,
699        };
700        if array_index.is_none() {
701            all_array_keys = false;
702        }
703        ordered.push((
704            key,
705            snapshot_value_inner(vm, value, depth + 1)?,
706            array_index,
707        ));
708    }
709
710    if all_array_keys {
711        let mut array_entries = ordered
712            .iter()
713            .filter_map(|(_, value, index)| index.map(|index| (index, value.clone())))
714            .collect::<Vec<_>>();
715        array_entries.sort_by_key(|(index, _)| *index);
716        let contiguous = array_entries
717            .iter()
718            .enumerate()
719            .all(|(position, (index, _))| *index == position + 1);
720        if contiguous {
721            let array = array_entries
722                .into_iter()
723                .map(|(_, value)| value)
724                .collect::<Vec<_>>();
725            return Ok(OwnedValue::Table(OwnedTable {
726                array,
727                entries: Vec::new(),
728            }));
729        }
730    }
731
732    Ok(OwnedValue::Table(OwnedTable {
733        array: Vec::new(),
734        entries: ordered
735            .into_iter()
736            .map(|(key, value, _)| (key, value))
737            .collect(),
738    }))
739}
740
741fn snapshot_key(vm: &mut Vm, key: RawValue) -> Result<OwnedKey> {
742    match key.kind() {
743        ValueKind::Boolean => Ok(OwnedKey::Boolean(key.as_bool().unwrap_or(false))),
744        ValueKind::Number => Ok(OwnedKey::Number(key.as_number().unwrap_or(f64::NAN))),
745        ValueKind::String => vm
746            .string_value(key)
747            .map_err(Error::from_engine)?
748            .map(OwnedKey::String)
749            .ok_or_else(|| Error::embed("string key is missing".to_owned())),
750        _ => Err(Error::embed(format!(
751            "{} table keys cannot be represented as OwnedKey",
752            raw_kind_name(key.kind())
753        ))),
754    }
755}
756
757pub(crate) fn load_owned_value(vm: &mut Vm, value: &OwnedValue) -> Result<RawValue> {
758    match value {
759        OwnedValue::Nil => Ok(RawValue::nil()),
760        OwnedValue::Boolean(value) => Ok(RawValue::boolean(*value)),
761        OwnedValue::Number(value) => Ok(RawValue::number(*value)),
762        OwnedValue::String(value) => Ok(vm.string(value)),
763        OwnedValue::Table(table) => {
764            let raw_table = vm.empty_table();
765            // Nested values can force quota collection before they are attached
766            // to this table. Keep the partial parent reachable throughout.
767            let _table_root = vm.retain_value(raw_table).map_err(Error::from_engine)?;
768            for (index, value) in table.array.iter().enumerate() {
769                let key = RawValue::number((index + 1) as f64);
770                let value = load_owned_value(vm, value)?;
771                vm.raw_table_set_value(raw_table, key, value)
772                    .map_err(Error::from_engine)?;
773            }
774            for (key, value) in &table.entries {
775                let key = load_owned_key(vm, key);
776                let _key_root = if key.kind() == ValueKind::String {
777                    Some(vm.retain_value(key).map_err(Error::from_engine)?)
778                } else {
779                    None
780                };
781                let value = load_owned_value(vm, value)?;
782                vm.raw_table_set_value(raw_table, key, value)
783                    .map_err(Error::from_engine)?;
784            }
785            Ok(raw_table)
786        }
787    }
788}
789
790/// Keeps earlier arguments alive while later owned graphs allocate or collect.
791pub(crate) fn load_owned_arguments(
792    vm: &mut Vm,
793    values: &[OwnedValue],
794) -> Result<(Vec<RawValue>, Vec<rustia_vm::RetainedValue>)> {
795    let mut arguments = Vec::with_capacity(values.len());
796    let mut roots = Vec::new();
797    for value in values {
798        let value = load_owned_value(vm, value)?;
799        if !matches!(
800            value.kind(),
801            ValueKind::Nil | ValueKind::Boolean | ValueKind::Number
802        ) {
803            roots.push(vm.retain_value(value).map_err(Error::from_engine)?);
804        }
805        arguments.push(value);
806    }
807    Ok((arguments, roots))
808}
809
810fn load_owned_key(vm: &mut Vm, key: &OwnedKey) -> RawValue {
811    match key {
812        OwnedKey::Boolean(value) => RawValue::boolean(*value),
813        OwnedKey::Number(value) => RawValue::number(*value),
814        OwnedKey::String(value) => vm.string(value),
815    }
816}
817
818fn number_to_array_index(number: f64) -> Option<usize> {
819    if !number.is_finite() || number.fract() != 0.0 || number < 1.0 {
820        return None;
821    }
822    if number > usize::MAX as f64 {
823        return None;
824    }
825    Some(number as usize)
826}
827
828fn expect_table_ref(value: &OwnedValue) -> Result<&OwnedTable> {
829    match value {
830        OwnedValue::Table(table) => Ok(table),
831        other => type_error("table", other),
832    }
833}
834
835fn type_error<T>(expected: &'static str, value: &OwnedValue) -> Result<T> {
836    Err(Error::embed(format!(
837        "expected {expected}, got {}",
838        value.type_name()
839    )))
840}
841
842pub(crate) fn embed_to_vm_error(error: Error) -> VmError {
843    match error {
844        Error {
845            kind: crate::ErrorKind::Vm(error),
846            ..
847        } => (*error).into_core(),
848        error => {
849            let mut vm_error = VmError::new(VmErrorKind::RuntimeError {
850                message: error.to_string(),
851            });
852            vm_error.diagnostic = Some(std::sync::Arc::new(rustia_vm::diagnostic::Diagnostic {
853                host_cause: Some(std::sync::Arc::new(error)),
854                ..rustia_vm::diagnostic::Diagnostic::default()
855            }));
856            vm_error
857        }
858    }
859}
860
861fn raw_kind_name(kind: ValueKind) -> &'static str {
862    match kind {
863        ValueKind::Nil => "nil",
864        ValueKind::Boolean => "boolean",
865        ValueKind::Number => "number",
866        ValueKind::String => "string",
867        ValueKind::Table => "table",
868        ValueKind::Function => "function",
869        ValueKind::Userdata => "userdata",
870        ValueKind::Buffer => "buffer",
871        ValueKind::Vector => "vector",
872        _ => "unknown",
873    }
874}