Skip to main content

yomi_core/
value.rs

1//! Values and types.
2
3mod list;
4mod map;
5mod str;
6
7pub use list::ListData;
8pub use map::{MapData, MapEntries};
9pub use str::StrValue;
10
11use serde::{Deserialize, Serialize};
12use std::sync::Arc;
13
14/// A type of the script language.
15///
16/// `int`, `float`, `bool`, `str`, `list<T>`, `map<K, V>`, `Option<T>`, and `struct`s and `enum`s declared by users can be
17/// made by script expressions. `Identity` is a value that comes from quote line declarations
18/// (`identity 案内人 = "案内人"`) and can also be written in type annotations.
19#[non_exhaustive]
20#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
21pub enum Ty {
22    /// No return value.
23    Unit,
24    /// A 64-bit integer.
25    Int,
26    /// A 64-bit floating point number. `NaN` and `±∞` never appear as values.
27    Float,
28    /// A boolean.
29    Bool,
30    /// A string.
31    Str,
32    /// The built-in `Identity` (`{ id: str, name: str }`).
33    Identity,
34    /// `list<T>`.
35    List(Box<Ty>),
36    /// `map<K, V>` (keys and values; iteration is in insertion order).
37    Map(Box<Ty>, Box<Ty>),
38    /// `Option<T>`.
39    Option(Box<Ty>),
40    /// A `struct` declared by users. The name is `module.TypeName` (the declaration is a [`TypeDecl`]).
41    Struct(String),
42    /// An `enum` declared by users. The name is `module.TypeName` (the declaration is a [`TypeDecl`]).
43    Enum(String),
44    /// A function type `fn(parameter types, ...) -> return type`. Cannot be put into saves.
45    Fn(Vec<Ty>, Box<Ty>),
46}
47
48/// The maximum nesting depth of types (the depth following `list`, `Option`, `struct` fields and `enum` arguments).
49/// Recursive types are not allowed, so the nesting depth of values does not exceed this either (a limit so that the
50/// recursion of drop, cloning and serialization does not overflow even a 1 MiB stack).
51pub const MAX_TYPE_DEPTH: u32 = 32;
52
53/// The maximum nesting depth when reading saved values (so that broken saves do not exhaust the stack).
54pub(crate) const MAX_VALUE_DEPTH: u32 = 64;
55
56/// The declaration of a type declared by users.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct TypeDecl {
59    /// `module.TypeName`.
60    pub name: String,
61    /// Contents.
62    pub kind: TypeKind,
63}
64
65/// The contents of a type declaration.
66#[non_exhaustive]
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub enum TypeKind {
69    /// A `struct`. Fields are in declaration order.
70    Struct {
71        /// Fields (name and type).
72        fields: Vec<(String, Ty)>,
73    },
74    /// An `enum`. Variants are in declaration order.
75    Enum {
76        /// Variants.
77        variants: Vec<VariantDecl>,
78    },
79}
80
81/// The declaration of an `enum` variant.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct VariantDecl {
84    /// The name of the variant.
85    pub name: String,
86    /// The argument types (empty if none).
87    pub args: Vec<Ty>,
88}
89
90impl TypeDecl {
91    /// A string describing the shape of the declaration (put into saves and compared with the script's declaration on load).
92    pub fn signature(&self) -> String {
93        match &self.kind {
94            TypeKind::Struct { fields } => {
95                let parts: Vec<String> = fields
96                    .iter()
97                    .map(|(n, t)| format!("{n}: {}", t.name()))
98                    .collect();
99                if parts.is_empty() {
100                    "struct {}".to_string()
101                } else {
102                    format!("struct {{ {} }}", parts.join(", "))
103                }
104            }
105            TypeKind::Enum { variants } => {
106                let parts: Vec<String> = variants
107                    .iter()
108                    .map(|v| {
109                        if v.args.is_empty() {
110                            v.name.clone()
111                        } else {
112                            let a: Vec<String> = v.args.iter().map(Ty::name).collect();
113                            format!("{}({})", v.name, a.join(", "))
114                        }
115                    })
116                    .collect();
117                format!("enum {{ {} }}", parts.join(", "))
118            }
119        }
120    }
121
122    /// The names of user-defined types that this declaration uses directly.
123    pub(crate) fn used_types(&self) -> Vec<&str> {
124        let mut out = Vec::new();
125        match &self.kind {
126            TypeKind::Struct { fields } => {
127                fields.iter().for_each(|(_, t)| t.collect_user(&mut out))
128            }
129            TypeKind::Enum { variants } => variants
130                .iter()
131                .flat_map(|v| &v.args)
132                .for_each(|t| t.collect_user(&mut out)),
133        }
134        out
135    }
136}
137
138/// Finds a type declaration by name.
139pub fn find_type<'a>(types: &'a [TypeDecl], name: &str) -> Option<&'a TypeDecl> {
140    types.iter().find(|t| t.name == name)
141}
142
143/// The part of a type name without the module (`main.Chara` → `Chara`).
144pub(crate) fn short_type_name(name: &str) -> &str {
145    name.rsplit('.').next().unwrap_or(name)
146}
147
148impl Ty {
149    /// The name of a type in scripts (`int`, `list<str>`, `Option<Identity>`, and so on).
150    pub fn name(&self) -> String {
151        match self {
152            Ty::Unit => "()".to_string(),
153            Ty::Int => "int".to_string(),
154            Ty::Float => "float".to_string(),
155            Ty::Bool => "bool".to_string(),
156            Ty::Str => "str".to_string(),
157            Ty::Identity => "Identity".to_string(),
158            Ty::List(t) => format!("list<{}>", t.name()),
159            Ty::Map(k, v) => format!("map<{}, {}>", k.name(), v.name()),
160            Ty::Option(t) => format!("Option<{}>", t.name()),
161            Ty::Struct(n) | Ty::Enum(n) => n.clone(),
162            Ty::Fn(params, ret) => {
163                let ps: Vec<String> = params.iter().map(Ty::name).collect();
164                format!("fn({}) -> {}", ps.join(", "), ret.name())
165            }
166        }
167    }
168
169    /// Whether it contains a function type (also looks inside `list`, `map` and `Option`). Function values cannot be put into
170    /// saves, so variables of a type for which this is true cannot be held across stop points. `struct`s and `enum`s cannot
171    /// have function types.
172    pub fn contains_fn(&self) -> bool {
173        match self {
174            Ty::Fn(..) => true,
175            Ty::List(t) | Ty::Option(t) => t.contains_fn(),
176            Ty::Map(k, v) => k.contains_fn() || v.contains_fn(),
177            _ => false,
178        }
179    }
180
181    /// The default value of a type. `types` are the declarations of `struct`s and `enum`s (without them, user-defined types
182    /// give `()`).
183    ///
184    /// A `struct` has default values for all fields. An `enum` is its first variant (with default arguments).
185    pub fn default_in(&self, types: &[TypeDecl]) -> Value {
186        match self {
187            Ty::Unit => Value::Unit,
188            Ty::Int => Value::Int(0),
189            Ty::Float => Value::Float(0.0),
190            Ty::Bool => Value::Bool(false),
191            Ty::Str => Value::Str(String::new().into()),
192            Ty::Identity => Value::Identity(Arc::default()),
193            Ty::List(_) => Value::List(ListData::new()),
194            Ty::Map(..) => Value::Map(MapData::new()),
195            Ty::Option(_) => Value::Option(None),
196            // Variables of function types always have an initial value (the default is never used)
197            Ty::Fn(..) => Value::Unit,
198            Ty::Struct(n) | Ty::Enum(n) => match find_type(types, n).map(|d| &d.kind) {
199                Some(TypeKind::Struct { fields }) => Value::Struct(Arc::new(StructValue {
200                    ty: n.clone().into(),
201                    fields: fields
202                        .iter()
203                        .map(|(f, t)| (f.clone(), t.default_in(types)))
204                        .collect::<Vec<_>>(),
205                })),
206                Some(TypeKind::Enum { variants }) => match variants.first() {
207                    Some(v) => Value::Enum(Arc::new(EnumValue {
208                        ty: n.clone().into(),
209                        variant: v.name.clone().into(),
210                        args: v
211                            .args
212                            .iter()
213                            .map(|t| t.default_in(types))
214                            .collect::<Vec<_>>(),
215                    })),
216                    None => Value::Unit,
217                },
218                None => Value::Unit,
219            },
220        }
221    }
222
223    /// The nesting depth (`list<int>` is 2, `int` is 1). For `struct`s and `enum`s, follows the declarations (`types`).
224    /// On meeting a recursive type (rejected by declaration checks), stops and returns the limit ([`MAX_TYPE_DEPTH`] + 1).
225    pub fn depth_in(&self, types: &[TypeDecl]) -> u32 {
226        self.depth_rec(types, 0)
227    }
228
229    /// Counts the nesting depth of a type. `from` is the current depth. Stops when the limit is exceeded.
230    fn depth_rec(&self, types: &[TypeDecl], from: u32) -> u32 {
231        if from > MAX_TYPE_DEPTH {
232            return from;
233        }
234        match self {
235            Ty::List(t) | Ty::Option(t) => 1 + t.depth_rec(types, from + 1),
236            Ty::Map(k, v) => {
237                1 + k
238                    .depth_rec(types, from + 1)
239                    .max(v.depth_rec(types, from + 1))
240            }
241            Ty::Fn(params, ret) => {
242                1 + params
243                    .iter()
244                    .chain(std::iter::once(&**ret))
245                    .map(|t| t.depth_rec(types, from + 1))
246                    .max()
247                    .unwrap_or(0)
248            }
249            Ty::Struct(n) | Ty::Enum(n) => {
250                let inner = match find_type(types, n).map(|d| &d.kind) {
251                    Some(TypeKind::Struct { fields }) => fields
252                        .iter()
253                        .map(|(_, t)| t.depth_rec(types, from + 1))
254                        .max()
255                        .unwrap_or(0),
256                    Some(TypeKind::Enum { variants }) => variants
257                        .iter()
258                        .flat_map(|v| &v.args)
259                        .map(|t| t.depth_rec(types, from + 1))
260                        .max()
261                        .unwrap_or(0),
262                    None => 0,
263                };
264                1 + inner
265            }
266            _ => 1,
267        }
268    }
269
270    /// Collects the names of user-defined types used by a type.
271    pub(crate) fn collect_user<'a>(&'a self, out: &mut Vec<&'a str>) {
272        match self {
273            Ty::List(t) | Ty::Option(t) => t.collect_user(out),
274            Ty::Map(k, v) => {
275                k.collect_user(out);
276                v.collect_user(out);
277            }
278            Ty::Fn(params, ret) => {
279                params.iter().for_each(|t| t.collect_user(out));
280                ret.collect_user(out);
281            }
282            Ty::Struct(n) | Ty::Enum(n) => out.push(n),
283            _ => {}
284        }
285    }
286
287    /// Whether the type can be a key of `map<K, V>` (section 3.1 of `spec/language/03-statements.md`). `int`, `str`, `bool`,
288    /// `Identity` (`{ id: str, name: str }`), and `struct`s and `enum`s whose fields (arguments) all have key types. `float`,
289    /// `list`, `map` and `Option` cannot be keys.
290    pub fn is_key_in(&self, types: &[TypeDecl]) -> bool {
291        self.key_rec(types, 0)
292    }
293
294    /// Checks whether the type can be a key of a `map`.
295    fn key_rec(&self, types: &[TypeDecl], from: u32) -> bool {
296        if from > MAX_TYPE_DEPTH {
297            return false;
298        }
299        match self {
300            Ty::Int | Ty::Str | Ty::Bool | Ty::Identity => true,
301            Ty::Struct(n) | Ty::Enum(n) => match find_type(types, n).map(|d| &d.kind) {
302                Some(TypeKind::Struct { fields }) => {
303                    fields.iter().all(|(_, t)| t.key_rec(types, from + 1))
304                }
305                Some(TypeKind::Enum { variants }) => variants
306                    .iter()
307                    .flat_map(|v| &v.args)
308                    .all(|t| t.key_rec(types, from + 1)),
309                None => false,
310            },
311            _ => false,
312        }
313    }
314}
315
316/// The built-in type `Identity` (the identity of quote lines; `案内人` and `"案内人"` in `identity 案内人 = "案内人"`).
317#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
318pub struct Identity {
319    /// The declared name (`案内人`).
320    pub id: String,
321    /// The display name given in the declaration (`"案内人"`).
322    pub name: String,
323}
324
325/// The contents of a `struct` value.
326#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
327pub struct StructValue {
328    /// The type name (`module.TypeName`).
329    pub ty: Arc<str>,
330    /// Fields (in declaration order; name and value).
331    pub fields: Vec<(String, Value)>,
332}
333
334/// The contents of an `enum` value.
335#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
336pub struct EnumValue {
337    /// The type name (`module.TypeName`).
338    pub ty: Arc<str>,
339    /// The name of the variant.
340    pub variant: Arc<str>,
341    /// The arguments of the variant.
342    pub args: Vec<Value>,
343}
344
345/// A value.
346///
347/// `==` compares contents. `map`s are equal if they have the same values for the same keys, regardless of insertion order
348/// (other types are equal only if order and names match too).
349#[non_exhaustive]
350#[derive(Clone, Serialize, Deserialize)]
351pub enum Value {
352    /// No return value.
353    Unit,
354    /// An integer.
355    Int(i64),
356    /// A floating point number. Finite, and never `-0.0` (normalized to `0.0`).
357    Float(f64),
358    /// A boolean.
359    Bool(bool),
360    /// A string. The contents are shared (cloning only copies the `Arc`; strings are never modified).
361    Str(StrValue),
362    /// An `Identity` (shared; the contents live behind an `Arc` to keep `Value` small).
363    Identity(Arc<Identity>),
364    /// `list<T>`. The elements are a [`ListData`] (cloning shares them; an update copies the contents if shared).
365    List(ListData),
366    /// `map<K, V>`. Holds pairs of keys and values in insertion order (keys do not repeat).
367    Map(MapData),
368    /// `Option<T>` (`None` is `None`).
369    Option(Option<Box<Value>>),
370    /// A `struct` value (shared; the contents live behind an `Arc` to keep `Value` small). To modify it, use
371    /// `Arc::make_mut`, which copies first if shared.
372    Struct(Arc<StructValue>),
373    /// An `enum` value (shared; the contents live behind an `Arc` to keep `Value` small). To modify it, use
374    /// `Arc::make_mut`, which copies first if shared.
375    Enum(Arc<EnumValue>),
376    /// A function value (a reference to a `fn`, or a closure made by a lambda). It does not go into saves, so it cannot be
377    /// serialized.
378    #[serde(skip)]
379    Fn(Arc<FnValue>),
380}
381
382/// The contents of a function value.
383#[derive(Debug, Clone, PartialEq)]
384pub struct FnValue {
385    /// The function to call (a sequential number within the program; meaningful only within the same program).
386    pub(crate) f: u32,
387    /// The values captured when it was made (by value).
388    pub(crate) captures: Box<[Value]>,
389}
390
391/// `struct`s and `enum`s are shown with their fields, without showing the inner `Arc` (`Struct { ty, fields }`).
392impl std::fmt::Debug for Value {
393    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394        match self {
395            Value::Unit => f.write_str("Unit"),
396            Value::Int(n) => f.debug_tuple("Int").field(n).finish(),
397            Value::Float(x) => f.debug_tuple("Float").field(x).finish(),
398            Value::Bool(b) => f.debug_tuple("Bool").field(b).finish(),
399            Value::Str(s) => f.debug_tuple("Str").field(s).finish(),
400            Value::Identity(i) => f.debug_tuple("Identity").field(i).finish(),
401            Value::List(items) => f.debug_tuple("List").field(items).finish(),
402            Value::Map(entries) => f.debug_tuple("Map").field(entries).finish(),
403            Value::Option(v) => f.debug_tuple("Option").field(v).finish(),
404            Value::Struct(st) => f
405                .debug_struct("Struct")
406                .field("ty", &st.ty)
407                .field("fields", &st.fields)
408                .finish(),
409            Value::Enum(e) => f
410                .debug_struct("Enum")
411                .field("ty", &e.ty)
412                .field("variant", &e.variant)
413                .field("args", &e.args)
414                .finish(),
415            Value::Fn(fv) => f.debug_tuple("Fn").field(&fv.f).finish(),
416        }
417    }
418}
419
420impl PartialEq for Value {
421    fn eq(&self, other: &Self) -> bool {
422        match (self, other) {
423            (Value::Unit, Value::Unit) => true,
424            (Value::Int(a), Value::Int(b)) => a == b,
425            (Value::Float(a), Value::Float(b)) => a == b,
426            (Value::Bool(a), Value::Bool(b)) => a == b,
427            (Value::Str(a), Value::Str(b)) => a == b,
428            (Value::Identity(a), Value::Identity(b)) => a == b,
429            (Value::List(a), Value::List(b)) => a == b,
430            (Value::Map(a), Value::Map(b)) => a == b,
431            (Value::Option(a), Value::Option(b)) => a == b,
432            (Value::Struct(a), Value::Struct(b)) => a == b,
433            (Value::Enum(a), Value::Enum(b)) => a == b,
434            // Function values cannot be compared with `==` (rejected by type checking). Only checks whether they are the same value
435            (Value::Fn(a), Value::Fn(b)) => Arc::ptr_eq(a, b),
436            _ => false,
437        }
438    }
439}
440
441/// Turns the result of a floating point operation into a script value. `None` for `NaN` or `±∞`. `-0.0` becomes `0.0`.
442pub(crate) fn finite_float(x: f64) -> Option<f64> {
443    if !x.is_finite() {
444        None
445    } else if x == 0.0 {
446        Some(0.0)
447    } else {
448        Some(x)
449    }
450}
451
452/// The string form of a floating point number (the shortest round trip of Rust's `{}`; integer values in the form `1.0`).
453pub(crate) fn float_text(x: f64) -> String {
454    let mut s = x.to_string();
455    if !s.contains('.') {
456        s.push_str(".0");
457    }
458    s
459}
460
461impl Value {
462    /// Makes floating point numbers finite with `-0.0` normalized to `0.0` (also inside nesting). `None` if it contains `NaN`
463    /// or `±∞`.
464    pub(crate) fn normalized(self) -> Option<Value> {
465        Some(match self {
466            Value::Float(x) => Value::Float(finite_float(x)?),
467            Value::List(items) => Value::List(
468                items
469                    .into_vec()
470                    .into_iter()
471                    .map(Value::normalized)
472                    .collect::<Option<Vec<_>>>()?
473                    .into(),
474            ),
475            Value::Map(entries) => Value::Map(MapData::from_pairs(
476                entries
477                    .into_entries()
478                    .into_iter()
479                    .map(|(k, v)| Some((k.normalized()?, v.normalized()?)))
480                    .collect::<Option<Vec<_>>>()?,
481            )),
482            Value::Option(Some(v)) => Value::Option(Some(Box::new((*v).normalized()?))),
483            Value::Struct(st) => {
484                let StructValue { ty, fields } = Arc::unwrap_or_clone(st);
485                Value::Struct(Arc::new(StructValue {
486                    ty,
487                    fields: fields
488                        .into_iter()
489                        .map(|(n, v)| Some((n, v.normalized()?)))
490                        .collect::<Option<Vec<_>>>()?,
491                }))
492            }
493            Value::Enum(e) => {
494                let EnumValue { ty, variant, args } = Arc::unwrap_or_clone(e);
495                Value::Enum(Arc::new(EnumValue {
496                    ty,
497                    variant,
498                    args: args
499                        .into_iter()
500                        .map(Value::normalized)
501                        .collect::<Option<Vec<_>>>()?,
502                }))
503            }
504            other => other,
505        })
506    }
507
508    /// The type of the value (as far as can be known). The element type of an empty `list` and the content type of `None`
509    /// cannot be decided, so they are returned as `()`. Use [`Value::matches`] to check types.
510    pub fn ty(&self) -> Ty {
511        match self {
512            Value::Unit => Ty::Unit,
513            Value::Int(_) => Ty::Int,
514            Value::Float(_) => Ty::Float,
515            Value::Bool(_) => Ty::Bool,
516            Value::Str(_) => Ty::Str,
517            Value::Identity(_) => Ty::Identity,
518            Value::List(items) => Ty::List(Box::new(items.first().map_or(Ty::Unit, Value::ty))),
519            Value::Map(entries) => Ty::Map(
520                Box::new(entries.entries().next().map_or(Ty::Unit, |(k, _)| k.ty())),
521                Box::new(entries.entries().next().map_or(Ty::Unit, |(_, v)| v.ty())),
522            ),
523            Value::Option(inner) => {
524                Ty::Option(Box::new(inner.as_deref().map_or(Ty::Unit, Value::ty)))
525            }
526            Value::Struct(st) => Ty::Struct(st.ty.to_string()),
527            Value::Enum(e) => Ty::Enum(e.ty.to_string()),
528            // Function values do not carry parameter and return types
529            Value::Fn(_) => Ty::Fn(Vec::new(), Box::new(Ty::Unit)),
530        }
531    }
532
533    /// Whether the value matches type `ty` (`list` and `Option` are checked down to their contents). For `struct`s and
534    /// `enum`s, only the type name is checked (to check fields too, use [`Value::matches_in`]).
535    pub fn matches(&self, ty: &Ty) -> bool {
536        self.matches_in(ty, &[])
537    }
538
539    /// Whether the value matches type `ty`. For `struct`s and `enum`s declared in `types`, names and types of fields and
540    /// arguments are checked too (without a declaration, only the type name).
541    pub fn matches_in(&self, ty: &Ty, types: &[TypeDecl]) -> bool {
542        match (self, ty) {
543            (Value::Unit, Ty::Unit)
544            | (Value::Int(_), Ty::Int)
545            | (Value::Float(_), Ty::Float)
546            | (Value::Bool(_), Ty::Bool)
547            | (Value::Str(_), Ty::Str)
548            | (Value::Identity(_), Ty::Identity) => true,
549            (Value::List(items), Ty::List(t)) => items.iter().all(|v| v.matches_in(t, types)),
550            (Value::Map(entries), Ty::Map(kt, vt)) => entries
551                .iter()
552                .all(|(k, v)| k.matches_in(kt, types) && v.matches_in(vt, types)),
553            (Value::Option(None), Ty::Option(_)) | (Value::Fn(_), Ty::Fn(..)) => true,
554            (Value::Option(Some(v)), Ty::Option(t)) => v.matches_in(t, types),
555            (Value::Struct(st), Ty::Struct(tn)) => {
556                let StructValue { ty: vn, fields } = &**st;
557                **vn == **tn
558                    && match find_type(types, tn).map(|d| &d.kind) {
559                        Some(TypeKind::Struct { fields: decl }) => {
560                            decl.len() == fields.len()
561                                && decl.iter().zip(fields.iter()).all(|((dn, dt), (fnm, fv))| {
562                                    dn == fnm && fv.matches_in(dt, types)
563                                })
564                        }
565                        Some(_) => false,
566                        None => true,
567                    }
568            }
569            (Value::Enum(e), Ty::Enum(tn)) => {
570                let EnumValue {
571                    ty: vn,
572                    variant,
573                    args,
574                } = &**e;
575                **vn == **tn
576                    && match find_type(types, tn).map(|d| &d.kind) {
577                        Some(TypeKind::Enum { variants }) => variants
578                            .iter()
579                            .find(|v| *v.name == **variant)
580                            .is_some_and(|v| {
581                                v.args.len() == args.len()
582                                    && v.args
583                                        .iter()
584                                        .zip(args.iter())
585                                        .all(|(t, a)| a.matches_in(t, types))
586                            }),
587                        Some(_) => false,
588                        None => true,
589                    }
590            }
591            _ => false,
592        }
593    }
594
595    /// The nesting depth of the value (scalars are 1).
596    pub fn depth(&self) -> u32 {
597        match self {
598            Value::List(items) => 1 + items.iter().map(Value::depth).max().unwrap_or(0),
599            Value::Map(entries) => {
600                1 + entries
601                    .iter()
602                    .map(|(k, v)| k.depth().max(v.depth()))
603                    .max()
604                    .unwrap_or(0)
605            }
606            Value::Option(Some(v)) => 1 + v.depth(),
607            Value::Struct(st) => 1 + st.fields.iter().map(|(_, v)| v.depth()).max().unwrap_or(0),
608            Value::Enum(e) => 1 + e.args.iter().map(Value::depth).max().unwrap_or(0),
609            _ => 1,
610        }
611    }
612
613    /// An approximate size of the value (bytes). Used to check `VmConfig::max_value_bytes`. Scalars are 8, strings are length
614    /// + 24, and `list`, `struct`, `enum` and `Option` are 24 + the sum of their contents.
615    #[inline]
616    pub fn approx_bytes(&self) -> usize {
617        match self {
618            Value::Unit | Value::Int(_) | Value::Float(_) | Value::Bool(_) => 8,
619            _ => self.approx_bytes_composite(),
620        }
621    }
622
623    /// The non-number part of `approx_bytes` (not inlined into callers, to keep the number case fast).
624    #[inline(never)]
625    fn approx_bytes_composite(&self) -> usize {
626        match self {
627            Value::Unit | Value::Int(_) | Value::Float(_) | Value::Bool(_) => 8,
628            Value::Str(s) => 24 + s.len(),
629            Value::Identity(i) => 48 + i.id.len() + i.name.len(),
630            // The size of the contents is held by `ListData` and `MapData` (not recounted on every read)
631            Value::List(items) => 24 + items.content_bytes(),
632            Value::Map(entries) => 24 + entries.content_bytes(),
633            Value::Option(None) => 8,
634            Value::Option(Some(v)) => 8 + v.approx_bytes(),
635            Value::Struct(st) => {
636                24 + st
637                    .fields
638                    .iter()
639                    .map(|(_, v)| v.approx_bytes())
640                    .sum::<usize>()
641            }
642            Value::Enum(e) => 24 + e.args.iter().map(Value::approx_bytes).sum::<usize>(),
643            Value::Fn(fv) => 24 + fv.captures.iter().map(Value::approx_bytes).sum::<usize>(),
644        }
645    }
646
647    /// The value as a string (used for `${expr}` interpolation).
648    pub fn to_text(&self) -> String {
649        self.render(false)
650    }
651
652    /// The display string for the REPL and `:vars` (section 7.2.4 of spec/host/07-repl.md). Same as the `${expr}` form
653    /// ([`Value::to_text`]), except that `str` is enclosed in `"` including inside nesting (escaped with `\"`, `\\`, `\n`,
654    /// `\t`, `\$`), and `Identity` is written `Identity { id: "…", name: "…" }`.
655    pub fn to_repl_text(&self) -> String {
656        self.render(true)
657    }
658
659    /// The body of `to_text` (`repl` false) and `to_repl_text` (true).
660    fn render(&self, repl: bool) -> String {
661        match self {
662            Value::Unit => String::new(),
663            Value::Int(n) => n.to_string(),
664            Value::Float(x) => float_text(*x),
665            Value::Bool(b) => b.to_string(),
666            Value::Str(s) if repl => quoted_text(s),
667            Value::Str(s) => s.to_string(),
668            Value::Identity(i) if repl => format!(
669                "Identity {{ id: {}, name: {} }}",
670                quoted_text(&i.id),
671                quoted_text(&i.name)
672            ),
673            Value::Identity(i) => i.name.clone(),
674            Value::List(items) => {
675                let parts: Vec<String> = items.iter().map(|v| v.render(repl)).collect();
676                format!("[{}]", parts.join(", "))
677            }
678            Value::Map(entries) => {
679                if entries.is_empty() {
680                    return "map {}".to_string();
681                }
682                let parts: Vec<String> = entries
683                    .iter()
684                    .map(|(k, v)| format!("{}: {}", k.render(repl), v.render(repl)))
685                    .collect();
686                format!("map {{ {} }}", parts.join(", "))
687            }
688            Value::Option(None) => "None".to_string(),
689            Value::Option(Some(v)) => format!("Some({})", v.render(repl)),
690            Value::Struct(st) => {
691                let StructValue { ty, fields } = &**st;
692                let parts: Vec<String> = fields
693                    .iter()
694                    .map(|(n, v)| format!("{n}: {}", v.render(repl)))
695                    .collect();
696                if parts.is_empty() {
697                    format!("{} {{ }}", short_type_name(ty))
698                } else {
699                    format!("{} {{ {} }}", short_type_name(ty), parts.join(", "))
700                }
701            }
702            Value::Enum(e) => {
703                let EnumValue { ty, variant, args } = &**e;
704                if args.is_empty() {
705                    format!("{}.{variant}", short_type_name(ty))
706                } else {
707                    let parts: Vec<String> = args.iter().map(|v| v.render(repl)).collect();
708                    format!("{}.{variant}({})", short_type_name(ty), parts.join(", "))
709                }
710            }
711            Value::Fn(_) => "<fn>".to_string(),
712        }
713    }
714}
715
716/// Turns a string into string literal form (enclosed in `"`, escaped with `\"`, `\\`, `\n`, `\t`, `\$`).
717fn quoted_text(s: &str) -> String {
718    let mut out = String::with_capacity(s.len() + 2);
719    out.push('"');
720    for c in s.chars() {
721        match c {
722            '"' => out.push_str("\\\""),
723            '\\' => out.push_str("\\\\"),
724            '\n' => out.push_str("\\n"),
725            '\t' => out.push_str("\\t"),
726            '$' => out.push_str("\\$"),
727            c => out.push(c),
728        }
729    }
730    out.push('"');
731    out
732}
733
734impl Value {
735    /// A type-tagged string of a value that can be a key. Two keys are equal exactly when these strings are equal (used to
736    /// check for duplicate keys in saved `map`s).
737    pub(crate) fn key_repr(&self) -> String {
738        let mut out = String::new();
739        self.key_repr_into(&mut out);
740        out
741    }
742
743    /// Appends the `key_repr` string to `out`.
744    fn key_repr_into(&self, out: &mut String) {
745        use std::fmt::Write;
746        match self {
747            Value::Int(n) => {
748                let _ = write!(out, "i{n};");
749            }
750            Value::Bool(b) => out.push_str(if *b { "b1;" } else { "b0;" }),
751            Value::Str(t) => {
752                let _ = write!(out, "s{}:{t};", t.len());
753            }
754            Value::Identity(i) => {
755                let _ = write!(out, "I{}:{}{}:{};", i.id.len(), i.id, i.name.len(), i.name);
756            }
757            Value::Struct(st) => {
758                let StructValue { ty, fields } = &**st;
759                let _ = write!(out, "S{}:{ty}(", ty.len());
760                for (_, v) in fields.iter() {
761                    v.key_repr_into(out);
762                }
763                out.push_str(");");
764            }
765            Value::Enum(e) => {
766                let EnumValue { ty, variant, args } = &**e;
767                let _ = write!(out, "E{}:{ty}{}:{variant}(", ty.len(), variant.len());
768                for a in args.iter() {
769                    a.key_repr_into(out);
770                }
771                out.push_str(");");
772            }
773            // Types that cannot be keys (rejected by type checking)
774            other => {
775                let t = other.to_text();
776                let _ = write!(out, "?{}:{t};", t.len());
777            }
778        }
779    }
780}
781
782#[cfg(test)]
783mod tests {
784    use super::*;
785
786    #[test]
787    fn values_are_checked_against_expected_type_including_nesting() {
788        let list = Value::List(vec![Value::Str("a".into()), Value::Str("b".into())].into());
789        assert!(list.matches(&Ty::List(Box::new(Ty::Str))));
790        assert!(!list.matches(&Ty::List(Box::new(Ty::Int))));
791        assert!(!list.matches(&Ty::Str));
792        // An empty list matches any element type
793        assert!(Value::List(vec![].into()).matches(&Ty::List(Box::new(Ty::Int))));
794        let some = Value::Option(Some(Box::new(Value::Identity(Arc::new(
795            Identity::default(),
796        )))));
797        assert!(some.matches(&Ty::Option(Box::new(Ty::Identity))));
798        assert!(Value::Option(None).matches(&Ty::Option(Box::new(Ty::Int))));
799        assert!(!some.matches(&Ty::Option(Box::new(Ty::Str))));
800    }
801
802    #[test]
803    fn display_form_quotes_and_escapes_nested_strings() {
804        let list = Value::List(vec![Value::Str("お面".into()), Value::Str("a\"b".into())].into());
805        assert_eq!(list.to_text(), "[お面, a\"b]");
806        assert_eq!(list.to_repl_text(), "[\"お面\", \"a\\\"b\"]");
807        let s = Value::Str("x\\y\n\t$1".into());
808        assert_eq!(s.to_repl_text(), "\"x\\\\y\\n\\t\\$1\"");
809        let some = Value::Option(Some(Box::new(Value::Str("a".into()))));
810        assert_eq!(some.to_repl_text(), "Some(\"a\")");
811        assert_eq!(Value::Int(-3).to_repl_text(), "-3");
812        assert_eq!(Value::Float(3.0).to_repl_text(), "3.0");
813        let id = Value::Identity(Arc::new(Identity {
814            id: "案内人".into(),
815            name: "リオン".into(),
816        }));
817        assert_eq!(id.to_text(), "リオン");
818        assert_eq!(
819            id.to_repl_text(),
820            "Identity { id: \"案内人\", name: \"リオン\" }"
821        );
822    }
823
824    #[test]
825    fn type_names_use_script_notation() {
826        assert_eq!(Ty::Identity.name(), "Identity");
827        assert_eq!(Ty::List(Box::new(Ty::Str)).name(), "list<str>");
828        assert_eq!(Ty::Option(Box::new(Ty::Int)).name(), "Option<int>");
829    }
830
831    #[test]
832    fn values_round_trip_through_postcard_including_identity() {
833        let id = Identity {
834            id: "案内人".into(),
835            name: "案内人".into(),
836        };
837        let bytes = postcard::to_allocvec(&id).unwrap();
838        let back: Identity = postcard::from_bytes(&bytes).unwrap();
839        assert_eq!(back, id);
840    }
841}