Skip to main content

mq_lang/runtime/
runtime_value.rs

1#[cfg(any(feature = "file-io", feature = "http"))]
2use crate::runtime::reader_handle::ReaderHandle;
3use crate::{
4    Ident, Shared,
5    number::Number,
6    tarn::interpreter::coroutine::{CoroutineHandle, CoroutineWeakHandle},
7    tarn::value::ClosureValue,
8};
9use mq_markdown::Node;
10use std::{
11    borrow::Cow,
12    cmp::Ordering,
13    ops::{Index, IndexMut},
14};
15
16pub use crate::runtime::dict::DictMap;
17
18/// Runtime selector for indexing into markdown nodes.
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub enum Selector {
21    Index(std::num::NonZeroU32),
22}
23
24impl Selector {
25    /// `None` if `i` doesn't fit (indices `>= u32::MAX`); callers treat that the same as any
26    /// other out-of-range index (e.g. `RuntimeValue::NONE`), not an error. `NonZeroU32` was
27    /// chosen over a plain `usize` because `Option<Selector>` still fits in the padding
28    /// alongside `Shared<Node>`, so `RuntimeValue` stays 16 bytes instead of growing to 24.
29    #[inline(always)]
30    pub(crate) fn index(i: usize) -> Option<Self> {
31        i.checked_add(1)
32            .and_then(|n| u32::try_from(n).ok())
33            .and_then(std::num::NonZeroU32::new)
34            .map(Selector::Index)
35    }
36
37    #[inline(always)]
38    pub(crate) fn index_value(self) -> usize {
39        let Selector::Index(n) = self;
40        (n.get() - 1) as usize
41    }
42}
43
44/// A coroutine resumption helper represented as a first-class runtime value.
45///
46/// These helpers require VM execution state and therefore cannot use the ordinary native
47/// builtin dispatcher. Keeping them distinct from [`RuntimeValue::NativeFunction`] also leaves
48/// the dynamic native-builtin hot path free of coroutine-specific checks.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum ResumeBuiltin {
51    /// Advances a coroutine without sending a value to its suspended `yield` expression.
52    Next,
53    /// Advances a coroutine and sends a value to its suspended `yield` expression.
54    Send,
55}
56
57/// A value in the mq runtime.
58///
59/// This enum represents all possible value types that can exist during
60/// program execution, including numbers, strings, markdown nodes, functions,
61/// and more complex data structures.
62#[derive(Clone, Default)]
63pub enum RuntimeValue {
64    /// A numeric value.
65    Number(Number),
66    /// A boolean value (`true` or `false`).
67    Boolean(bool),
68    /// A string value.
69    ///
70    /// Same clone-on-write scheme as [`RuntimeValue::Array`]; see `string_mut`.
71    String(Shared<String>),
72    /// A symbol (interned identifier).
73    Symbol(Ident),
74    /// An array of runtime values.
75    ///
76    /// Behind [`Shared`] for clone-on-write: cloning is an O(1) refcount bump; mutating
77    /// builtins must go through `array_mut` instead of mutating directly.
78    Array(Shared<Vec<RuntimeValue>>),
79    /// A markdown node with an optional selector for indexing.
80    ///
81    /// Same clone-on-write scheme as [`RuntimeValue::Array`]; see `markdown_mut`.
82    Markdown(Shared<Node>, Option<Selector>),
83    /// A built-in native function identified by name.
84    NativeFunction(Ident),
85    /// A first-class coroutine resumption helper (`next` or `send`).
86    CoroutineBuiltin(ResumeBuiltin),
87    /// A VM closure that has crossed into plain-value territory (stored in an array/dict,
88    /// passed to `partial`, ...): see `tarn::value::ClosureValue`. `ClosureValue` is
89    /// deliberately `pub(crate)`; this variant is constructible only from within the crate.
90    ///
91    /// `Shared`-wrapped, not inline: `ClosureValue` is 64 bytes (chunks/upvalues/bound_args),
92    /// which would otherwise force every `RuntimeValue` variant to that size.
93    #[doc(hidden)]
94    #[allow(private_interfaces)]
95    Closure(Shared<ClosureValue>),
96    /// A dictionary mapping identifiers to runtime values.
97    ///
98    /// Same clone-on-write scheme as [`RuntimeValue::Array`]; see `dict_mut`.
99    Dict(Shared<DictMap>),
100    /// Raw binary data (e.g. CBOR byte strings).
101    ///
102    /// Same clone-on-write scheme as [`RuntimeValue::Array`]; see `bytes_mut`.
103    Bytes(Shared<Vec<u8>>),
104    /// A generator function's coroutine, see `tarn::interpreter::coroutine::CoroutineState`.
105    /// `CoroutineState` is deliberately `pub(crate)`, so this variant is constructible only
106    /// from within the crate. Cloning shares progress: every clone drives the same coroutine.
107    #[doc(hidden)]
108    #[allow(private_interfaces)]
109    Coroutine(CoroutineHandle),
110    /// A coroutine downgraded to break a capture cycle. Only ever lives inside a
111    /// `StackValue::NestedWeakCoroutine` cell, resolved before any other code sees it.
112    #[doc(hidden)]
113    #[allow(private_interfaces)]
114    WeakCoroutine(CoroutineWeakHandle),
115    /// An open read-only file handle from `open_file`. Cloning shares the handle.
116    #[cfg(any(feature = "file-io", feature = "http"))]
117    #[doc(hidden)]
118    #[allow(private_interfaces)]
119    ReaderHandle(Shared<ReaderHandle>),
120    /// An empty or null value.
121    #[default]
122    None,
123}
124
125impl PartialEq for RuntimeValue {
126    fn eq(&self, other: &Self) -> bool {
127        match (self, other) {
128            (RuntimeValue::Number(a), RuntimeValue::Number(b)) => a == b,
129            (RuntimeValue::Boolean(a), RuntimeValue::Boolean(b)) => a == b,
130            (RuntimeValue::String(a), RuntimeValue::String(b)) => a == b,
131            (RuntimeValue::Symbol(a), RuntimeValue::Symbol(b)) => a == b,
132            (RuntimeValue::Array(a), RuntimeValue::Array(b)) => a == b,
133            (RuntimeValue::Markdown(a, sa), RuntimeValue::Markdown(b, sb)) => a == b && sa == sb,
134            (RuntimeValue::Closure(a), RuntimeValue::Closure(b)) => {
135                Shared::ptr_eq(&a.chunks, &b.chunks) && a.chunk_index == b.chunk_index && a.bound_args == b.bound_args
136            }
137            (RuntimeValue::NativeFunction(a), RuntimeValue::NativeFunction(b)) => a == b,
138            (RuntimeValue::CoroutineBuiltin(a), RuntimeValue::CoroutineBuiltin(b)) => a == b,
139            (RuntimeValue::Dict(a), RuntimeValue::Dict(b)) => a == b,
140            (RuntimeValue::Bytes(a), RuntimeValue::Bytes(b)) => a == b,
141            (RuntimeValue::Coroutine(a), RuntimeValue::Coroutine(b)) => Shared::ptr_eq(a, b),
142            (RuntimeValue::WeakCoroutine(a), RuntimeValue::WeakCoroutine(b)) => a.ptr_eq(b),
143            #[cfg(any(feature = "file-io", feature = "http"))]
144            (RuntimeValue::ReaderHandle(a), RuntimeValue::ReaderHandle(b)) => Shared::ptr_eq(a, b),
145            (RuntimeValue::None, RuntimeValue::None) => true,
146            _ => false,
147        }
148    }
149}
150
151impl From<Node> for RuntimeValue {
152    fn from(node: Node) -> Self {
153        RuntimeValue::new_markdown(node)
154    }
155}
156
157impl From<bool> for RuntimeValue {
158    fn from(b: bool) -> Self {
159        RuntimeValue::Boolean(b)
160    }
161}
162
163impl From<String> for RuntimeValue {
164    fn from(s: String) -> Self {
165        RuntimeValue::String(Shared::new(s))
166    }
167}
168
169impl From<&str> for RuntimeValue {
170    fn from(s: &str) -> Self {
171        RuntimeValue::String(Shared::new(s.to_string()))
172    }
173}
174
175impl From<&mut str> for RuntimeValue {
176    fn from(s: &mut str) -> Self {
177        RuntimeValue::String(Shared::new(s.to_string()))
178    }
179}
180
181impl From<Shared<String>> for RuntimeValue {
182    fn from(s: Shared<String>) -> Self {
183        RuntimeValue::String(s)
184    }
185}
186
187impl From<Vec<u8>> for RuntimeValue {
188    fn from(b: Vec<u8>) -> Self {
189        RuntimeValue::Bytes(Shared::new(b))
190    }
191}
192
193impl From<Shared<Vec<u8>>> for RuntimeValue {
194    fn from(b: Shared<Vec<u8>>) -> Self {
195        RuntimeValue::Bytes(b)
196    }
197}
198
199impl From<Number> for RuntimeValue {
200    fn from(n: Number) -> Self {
201        RuntimeValue::Number(n)
202    }
203}
204
205impl From<Ident> for RuntimeValue {
206    fn from(i: Ident) -> Self {
207        RuntimeValue::Symbol(i)
208    }
209}
210
211impl From<usize> for RuntimeValue {
212    fn from(n: usize) -> Self {
213        RuntimeValue::Number(Number::from(n))
214    }
215}
216
217impl From<Vec<RuntimeValue>> for RuntimeValue {
218    fn from(arr: Vec<RuntimeValue>) -> Self {
219        RuntimeValue::Array(Shared::new(arr))
220    }
221}
222
223impl From<DictMap> for RuntimeValue {
224    fn from(map: DictMap) -> Self {
225        RuntimeValue::Dict(Shared::new(map))
226    }
227}
228
229impl From<Vec<(String, Number)>> for RuntimeValue {
230    fn from(v: Vec<(String, Number)>) -> Self {
231        RuntimeValue::Dict(Shared::new(
232            v.into_iter()
233                .map(|(k, v)| (Ident::new(&k), RuntimeValue::Number(v)))
234                .collect::<DictMap>(),
235        ))
236    }
237}
238
239impl From<mq_markdown::AttrValue> for RuntimeValue {
240    fn from(attr_value: mq_markdown::AttrValue) -> Self {
241        match attr_value {
242            mq_markdown::AttrValue::String(s) => RuntimeValue::String(Shared::new(s)),
243            mq_markdown::AttrValue::Number(n) => RuntimeValue::Number(n.into()),
244            mq_markdown::AttrValue::Integer(n) => RuntimeValue::Number(n.into()),
245            mq_markdown::AttrValue::Boolean(b) => RuntimeValue::Boolean(b),
246            mq_markdown::AttrValue::Array(arr) => {
247                RuntimeValue::Array(Shared::new(arr.into_iter().map(RuntimeValue::from).collect()))
248            }
249            mq_markdown::AttrValue::Null => RuntimeValue::NONE,
250        }
251    }
252}
253
254/// Renders a YAML mapping key as a string. Composite keys use flow notation (`[1, 2]`, `{a: 1}`).
255fn yaml_key_to_string(key: &yaml_rust2::Yaml) -> String {
256    use yaml_rust2::Yaml;
257    match key {
258        Yaml::String(s) | Yaml::Real(s) => s.clone(),
259        Yaml::Integer(i) => i.to_string(),
260        Yaml::Boolean(b) => b.to_string(),
261        Yaml::Null | Yaml::BadValue | Yaml::Alias(_) => "null".to_string(),
262        Yaml::Array(arr) => format!(
263            "[{}]",
264            arr.iter().map(yaml_key_to_string).collect::<Vec<_>>().join(", ")
265        ),
266        Yaml::Hash(map) => format!(
267            "{{{}}}",
268            map.iter()
269                .map(|(k, v)| format!("{}: {}", yaml_key_to_string(k), yaml_key_to_string(v)))
270                .collect::<Vec<_>>()
271                .join(", ")
272        ),
273    }
274}
275
276impl From<yaml_rust2::Yaml> for RuntimeValue {
277    fn from(value: yaml_rust2::Yaml) -> Self {
278        match value {
279            yaml_rust2::Yaml::Null | yaml_rust2::Yaml::BadValue => RuntimeValue::NONE,
280            yaml_rust2::Yaml::Boolean(b) => RuntimeValue::Boolean(b),
281            yaml_rust2::Yaml::Integer(i) => RuntimeValue::Number((i as f64).into()),
282            // `as_f64` also understands the YAML core schema `.inf` / `-.inf` / `.nan`.
283            real @ yaml_rust2::Yaml::Real(_) => real
284                .as_f64()
285                .map(|f| RuntimeValue::Number(f.into()))
286                .unwrap_or(RuntimeValue::NONE),
287            yaml_rust2::Yaml::String(s) => RuntimeValue::String(Shared::new(s)),
288            yaml_rust2::Yaml::Array(arr) => {
289                RuntimeValue::Array(Shared::new(arr.into_iter().map(RuntimeValue::from).collect()))
290            }
291            yaml_rust2::Yaml::Hash(map) => {
292                let mut btree = DictMap::default();
293                for (k, v) in map {
294                    let key = yaml_key_to_string(&k);
295                    btree.insert(Ident::new(&key), RuntimeValue::from(v));
296                }
297                RuntimeValue::Dict(Shared::new(btree))
298            }
299            yaml_rust2::Yaml::Alias(_) => RuntimeValue::NONE,
300        }
301    }
302}
303
304impl From<serde_json::Value> for RuntimeValue {
305    fn from(value: serde_json::Value) -> Self {
306        match value {
307            serde_json::Value::Null => RuntimeValue::NONE,
308            serde_json::Value::Bool(b) => RuntimeValue::Boolean(b),
309            serde_json::Value::Number(n) => {
310                if let Some(f) = n.as_f64() {
311                    RuntimeValue::Number(f.into())
312                } else {
313                    RuntimeValue::Number(0.into())
314                }
315            }
316            serde_json::Value::String(s) => RuntimeValue::String(Shared::new(s)),
317            serde_json::Value::Array(arr) => {
318                RuntimeValue::Array(Shared::new(arr.into_iter().map(RuntimeValue::from).collect()))
319            }
320            serde_json::Value::Object(obj) => {
321                let mut map = DictMap::default();
322                for (k, v) in obj {
323                    map.insert(Ident::new(&k), RuntimeValue::from(v));
324                }
325                RuntimeValue::Dict(Shared::new(map))
326            }
327        }
328    }
329}
330
331impl From<ciborium::Value> for RuntimeValue {
332    fn from(value: ciborium::Value) -> Self {
333        match value {
334            ciborium::Value::Null => RuntimeValue::NONE,
335            ciborium::Value::Bool(b) => RuntimeValue::Boolean(b),
336            ciborium::Value::Integer(i) => {
337                let n: i128 = i.into();
338                RuntimeValue::Number(Number::from(n as f64))
339            }
340            ciborium::Value::Float(f) => RuntimeValue::Number(Number::from(f)),
341            ciborium::Value::Text(s) => RuntimeValue::String(Shared::new(s)),
342            ciborium::Value::Bytes(b) => RuntimeValue::Bytes(Shared::new(b)),
343            ciborium::Value::Array(arr) => {
344                let items = arr.into_iter().map(Into::into).collect();
345                RuntimeValue::Array(Shared::new(items))
346            }
347            ciborium::Value::Map(pairs) => {
348                let mut map = DictMap::default();
349                for (k, v) in pairs {
350                    let key = match k {
351                        ciborium::Value::Text(s) => Ident::new(&s),
352                        other => Ident::new(&format!("{:?}", other)),
353                    };
354                    map.insert(key, v.into());
355                }
356                RuntimeValue::Dict(Shared::new(map))
357            }
358            ciborium::Value::Tag(_, inner) => (*inner).into(),
359            _ => RuntimeValue::NONE,
360        }
361    }
362}
363
364impl PartialOrd for RuntimeValue {
365    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
366        match (self, other) {
367            (RuntimeValue::Number(a), RuntimeValue::Number(b)) => a.partial_cmp(b),
368            (RuntimeValue::Boolean(a), RuntimeValue::Boolean(b)) => a.partial_cmp(b),
369            (RuntimeValue::String(a), RuntimeValue::String(b)) => a.partial_cmp(b),
370            (RuntimeValue::Symbol(a), RuntimeValue::Symbol(b)) => a.partial_cmp(b),
371            (RuntimeValue::Array(a), RuntimeValue::Array(b)) => a.partial_cmp(b),
372            (RuntimeValue::Markdown(a, _), RuntimeValue::Markdown(b, _)) => a.to_string().partial_cmp(&b.to_string()),
373            (RuntimeValue::Bytes(a), RuntimeValue::Bytes(b)) => a.partial_cmp(b),
374            (RuntimeValue::Dict(_), _) => None,
375            (_, RuntimeValue::Dict(_)) => None,
376            _ => None,
377        }
378    }
379}
380
381impl RuntimeValue {
382    /// Total order for `sort`/`sort_by`: same types use `partial_cmp`, mixed types are ordered by type.
383    pub fn sort_cmp(&self, other: &Self) -> Ordering {
384        fn rank(v: &RuntimeValue) -> u8 {
385            match v {
386                RuntimeValue::None => 0,
387                RuntimeValue::Boolean(_) => 1,
388                RuntimeValue::Number(_) => 2,
389                RuntimeValue::String(_) => 3,
390                RuntimeValue::Symbol(_) => 4,
391                RuntimeValue::Markdown(_, _) => 5,
392                RuntimeValue::Bytes(_) => 6,
393                RuntimeValue::Array(_) => 7,
394                RuntimeValue::Dict(_) => 8,
395                _ => 9,
396            }
397        }
398
399        match (self, other) {
400            (RuntimeValue::Number(a), RuntimeValue::Number(b)) => a.cmp(b),
401            (RuntimeValue::Array(a), RuntimeValue::Array(b)) => a
402                .iter()
403                .zip(b.iter())
404                .map(|(x, y)| x.sort_cmp(y))
405                .find(|o| o.is_ne())
406                .unwrap_or_else(|| a.len().cmp(&b.len())),
407            _ => match rank(self).cmp(&rank(other)) {
408                Ordering::Equal => self.partial_cmp(other).unwrap_or(Ordering::Equal),
409                o => o,
410            },
411        }
412    }
413}
414
415impl std::fmt::Display for RuntimeValue {
416    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
417        let value: Cow<'_, str> = match self {
418            Self::Number(n) => Cow::Owned(n.to_string()),
419            Self::Boolean(b) => Cow::Owned(b.to_string()),
420            Self::String(s) => Cow::Borrowed(s),
421            Self::Symbol(i) => Cow::Owned(format!(":{}", i)),
422            Self::Array(_) => self.string(),
423            Self::Markdown(m, ..) => Cow::Owned(m.to_string()),
424            Self::None => Cow::Borrowed(""),
425            Self::NativeFunction(_) => Cow::Borrowed("native_function"),
426            Self::CoroutineBuiltin(_) => Cow::Borrowed("native_function"),
427            Self::Closure(_) => Cow::Borrowed("function"),
428            Self::Dict(_) => self.string(),
429            Self::Bytes(b) => Cow::Owned(bytes_to_hex(b)),
430            Self::Coroutine(_) | Self::WeakCoroutine(_) => Cow::Borrowed("coroutine"),
431            #[cfg(any(feature = "file-io", feature = "http"))]
432            Self::ReaderHandle(handle) => Cow::Borrowed(handle.kind().as_str()),
433        };
434        write!(f, "{}", value)
435    }
436}
437
438impl std::fmt::Debug for RuntimeValue {
439    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
440        let v: Cow<'_, str> = match self {
441            Self::None => Cow::Borrowed("None"),
442            Self::String(s) => Cow::Owned(format!("{:?}", s)),
443            Self::Array(arr) => Cow::Owned(format!("{:?}", arr)),
444            Self::Bytes(b) => Cow::Owned(format!("bytes({})", bytes_to_hex(b))),
445            a => a.string(),
446        };
447        write!(f, "{}", v)
448    }
449}
450
451fn bytes_to_hex(bytes: &[u8]) -> String {
452    use std::fmt::Write;
453    bytes.iter().fold(String::with_capacity(bytes.len() * 2), |mut s, b| {
454        write!(s, "{b:02x}").unwrap();
455        s
456    })
457}
458
459/// Clone-on-write access to an array's elements.
460///
461/// Bare `Shared::make_mut` is ambiguous (it also matches the `Rc<[T]>`/`Arc<[T]>` slice
462/// specialization), so this pins the type down.
463#[inline(always)]
464pub(crate) fn array_mut(array: &mut Shared<Vec<RuntimeValue>>) -> &mut Vec<RuntimeValue> {
465    Shared::<Vec<RuntimeValue>>::make_mut(array)
466}
467
468/// Clone-on-write access to a dict's entries; see [`array_mut`].
469#[inline(always)]
470pub(crate) fn dict_mut(map: &mut Shared<DictMap>) -> &mut DictMap {
471    Shared::<DictMap>::make_mut(map)
472}
473
474/// Clone-on-write access to a markdown node; see [`array_mut`].
475#[inline(always)]
476pub(crate) fn markdown_mut(node: &mut Shared<Node>) -> &mut Node {
477    Shared::<Node>::make_mut(node)
478}
479
480/// Clone-on-write access to a string's contents; see [`array_mut`].
481#[inline(always)]
482pub(crate) fn string_mut(s: &mut Shared<String>) -> &mut String {
483    Shared::<String>::make_mut(s)
484}
485
486/// Clone-on-write access to a byte buffer's contents; see [`array_mut`].
487#[inline(always)]
488pub(crate) fn bytes_mut(b: &mut Shared<Vec<u8>>) -> &mut Vec<u8> {
489    Shared::<Vec<u8>>::make_mut(b)
490}
491
492impl RuntimeValue {
493    pub(crate) fn vm_bound_value_kind(&self) -> Option<&'static str> {
494        let mut pending = vec![self];
495        while let Some(value) = pending.pop() {
496            match value {
497                Self::Coroutine(_) => return Some("coroutine"),
498                Self::Closure(_) => return Some("VM closure"),
499                Self::Array(values) => pending.extend(values.iter()),
500                Self::Dict(values) => pending.extend(values.values()),
501                _ => {}
502            }
503        }
504        None
505    }
506
507    /// The boolean `false` value.
508    pub const FALSE: RuntimeValue = Self::Boolean(false);
509    /// The `None` (null) value.
510    pub const NONE: RuntimeValue = Self::None;
511    /// The boolean `true` value.
512    pub const TRUE: RuntimeValue = Self::Boolean(true);
513
514    /// Returns a new empty array.
515    ///
516    /// Not a `const` because `Shared::new` (`Rc`/`Arc::new`) isn't const-evaluable.
517    #[inline(always)]
518    pub fn empty_array() -> RuntimeValue {
519        RuntimeValue::Array(Shared::new(Vec::new()))
520    }
521
522    /// Returns a new empty array with enough storage for `capacity` values.
523    #[inline(always)]
524    pub(crate) fn array_with_capacity(capacity: usize) -> RuntimeValue {
525        RuntimeValue::Array(Shared::new(Vec::with_capacity(capacity)))
526    }
527
528    /// Creates a new empty dictionary.
529    #[inline(always)]
530    pub fn new_dict() -> RuntimeValue {
531        RuntimeValue::Dict(Shared::new(DictMap::default()))
532    }
533
534    /// Creates a new markdown runtime value from the given node.
535    pub fn new_markdown(node: Node) -> RuntimeValue {
536        RuntimeValue::Markdown(Shared::new(node), None)
537    }
538
539    /// Returns the type name of this runtime value as a string.
540    #[inline(always)]
541    pub fn name(&self) -> &str {
542        match self {
543            RuntimeValue::Number(_) => "number",
544            RuntimeValue::Boolean(_) => "bool",
545            RuntimeValue::String(_) => "string",
546            RuntimeValue::Symbol(_) => "symbol",
547            RuntimeValue::Markdown(_, _) => "markdown",
548            RuntimeValue::Array(_) => "array",
549            RuntimeValue::None => "None",
550            RuntimeValue::NativeFunction(_) => "native_function",
551            RuntimeValue::CoroutineBuiltin(_) => "native_function",
552            RuntimeValue::Closure(_) => "function",
553            RuntimeValue::Dict(_) => "dict",
554            RuntimeValue::Bytes(_) => "bytes",
555            RuntimeValue::Coroutine(_) => "coroutine",
556            RuntimeValue::WeakCoroutine(_) => "coroutine",
557            #[cfg(any(feature = "file-io", feature = "http"))]
558            RuntimeValue::ReaderHandle(handle) => handle.kind().as_str(),
559        }
560    }
561
562    /// Returns `true` if this value is `None`.
563    #[inline(always)]
564    pub fn is_none(&self) -> bool {
565        matches!(self, RuntimeValue::None)
566    }
567
568    /// Returns `true` if this value is a user-defined function.
569    #[inline(always)]
570    pub fn is_function(&self) -> bool {
571        matches!(self, RuntimeValue::Closure(_))
572    }
573
574    /// Returns `true` if this value is a resumable coroutine.
575    ///
576    /// Weak coroutine references exist only while the VM breaks internal capture cycles and
577    /// cannot be resumed by callers, so they deliberately return `false` here.
578    #[inline(always)]
579    pub fn is_coroutine(&self) -> bool {
580        matches!(self, RuntimeValue::Coroutine(_))
581    }
582
583    /// Returns `true` if this value is a native (built-in) function.
584    #[inline(always)]
585    pub fn is_native_function(&self) -> bool {
586        matches!(
587            self,
588            RuntimeValue::NativeFunction(_) | RuntimeValue::CoroutineBuiltin(_)
589        )
590    }
591
592    /// Returns `true` if this value is an array.
593    #[inline(always)]
594    pub fn is_array(&self) -> bool {
595        matches!(self, RuntimeValue::Array(_))
596    }
597
598    /// Returns `true` if this value is a dict.
599    #[inline(always)]
600    pub fn is_dict(&self) -> bool {
601        matches!(self, RuntimeValue::Dict(_))
602    }
603
604    /// Returns `true` if this value is considered empty.
605    ///
606    /// Empty values include empty arrays, empty strings, empty markdown nodes,
607    /// empty dictionaries, and `None`.
608    #[inline(always)]
609    pub fn is_empty(&self) -> bool {
610        match self {
611            RuntimeValue::Array(a) => a.is_empty(),
612            RuntimeValue::String(s) => s.is_empty(),
613            RuntimeValue::Markdown(m, _) => m.value().is_empty(),
614            RuntimeValue::Dict(m) => m.is_empty(),
615            RuntimeValue::Bytes(b) => b.is_empty(),
616            RuntimeValue::None => true,
617            _ => false,
618        }
619    }
620
621    /// Returns `true` if this value is considered truthy in conditional contexts.
622    ///
623    /// Truthy values include non-zero numbers, non-empty strings and arrays,
624    /// `true`, functions, symbols, and modules. Falsy values include `false`,
625    /// zero, empty collections, and `None`.
626    #[inline(always)]
627    pub fn is_truthy(&self) -> bool {
628        match self {
629            RuntimeValue::Boolean(b) => *b,
630            RuntimeValue::Number(n) => n.value() != 0.0,
631            RuntimeValue::String(s) => !s.is_empty(),
632            RuntimeValue::Array(a) => !a.is_empty(),
633            RuntimeValue::Markdown(node, selector) => match selector {
634                Some(sel) => node.find_at_index(sel.index_value()).is_some(),
635                None => true,
636            },
637            RuntimeValue::Dict(m) => !m.is_empty(),
638            RuntimeValue::Symbol(_) | RuntimeValue::NativeFunction(_) | RuntimeValue::CoroutineBuiltin(_) => true,
639            RuntimeValue::Closure(_) => true,
640            RuntimeValue::Bytes(b) => !b.is_empty(),
641            RuntimeValue::Coroutine(_) | RuntimeValue::WeakCoroutine(_) => true,
642            #[cfg(any(feature = "file-io", feature = "http"))]
643            RuntimeValue::ReaderHandle(_) => true,
644            RuntimeValue::None => false,
645        }
646    }
647
648    /// Returns the length of this value.
649    ///
650    /// For numbers, returns the value as `usize`. For strings and arrays, returns
651    /// the number of elements. For dictionaries, returns the number of entries.
652    #[inline(always)]
653    pub fn len(&self) -> usize {
654        match self {
655            RuntimeValue::Number(n) => n.value() as usize,
656            RuntimeValue::Boolean(_) => 1,
657            RuntimeValue::String(s) => s.len(),
658            RuntimeValue::Symbol(i) => i.resolve_with(str::len),
659            RuntimeValue::Array(a) => a.len(),
660            RuntimeValue::Markdown(m, _) => m.value().len(),
661            RuntimeValue::Dict(m) => m.len(),
662            RuntimeValue::Bytes(b) => b.len(),
663            RuntimeValue::None => 0,
664            RuntimeValue::NativeFunction(..) => 0,
665            RuntimeValue::CoroutineBuiltin(..) => 0,
666            RuntimeValue::Closure(..) => 0,
667            RuntimeValue::Coroutine(..) | RuntimeValue::WeakCoroutine(..) => 0,
668            #[cfg(any(feature = "file-io", feature = "http"))]
669            RuntimeValue::ReaderHandle(..) => 0,
670        }
671    }
672
673    /// Returns the string if this is a `String`.
674    pub fn as_str(&self) -> Option<&str> {
675        match self {
676            RuntimeValue::String(s) => Some(s.as_str()),
677            _ => None,
678        }
679    }
680
681    /// Returns the number if this is a `Number`.
682    pub fn as_f64(&self) -> Option<f64> {
683        match self {
684            RuntimeValue::Number(n) => Some(n.value()),
685            _ => None,
686        }
687    }
688
689    /// Returns the boolean if this is a `Boolean`.
690    pub fn as_bool(&self) -> Option<bool> {
691        match self {
692            RuntimeValue::Boolean(b) => Some(*b),
693            _ => None,
694        }
695    }
696
697    /// Returns the elements if this is an `Array`.
698    pub fn as_array(&self) -> Option<&[RuntimeValue]> {
699        match self {
700            RuntimeValue::Array(values) => Some(values.as_slice()),
701            _ => None,
702        }
703    }
704
705    /// Returns the entries if this is a `Dict`.
706    pub fn as_dict(&self) -> Option<&DictMap> {
707        match self {
708            RuntimeValue::Dict(map) => Some(map),
709            _ => None,
710        }
711    }
712
713    /// Looks up `key` if this is a `Dict`.
714    pub fn get(&self, key: &str) -> Option<&RuntimeValue> {
715        self.as_dict()?.get(key)
716    }
717
718    /// Converts to a Markdown node: markdown values keep their (selected) node, anything else
719    pub fn into_markdown_node(self) -> Option<Node> {
720        match self {
721            RuntimeValue::Markdown(node, None) => Some(Shared::unwrap_or_clone(node)),
722            value @ RuntimeValue::Markdown(_, Some(_)) => value.markdown_node(),
723            value => Some(value.to_string().into()),
724        }
725    }
726
727    /// Extracts the markdown node from this value, if it is a markdown value.
728    ///
729    /// If a selector is present, returns the selected child node.
730    #[inline(always)]
731    pub fn markdown_node(&self) -> Option<Node> {
732        match self {
733            RuntimeValue::Markdown(n, Some(sel)) => n.find_at_index(sel.index_value()),
734            RuntimeValue::Markdown(n, _) => Some((**n).clone()),
735            _ => None,
736        }
737    }
738
739    /// Updates the value of a markdown node, returning a new runtime value.
740    ///
741    /// If this is not a markdown value, returns `None`.
742    #[inline(always)]
743    pub fn update_markdown_value(&self, value: &str) -> RuntimeValue {
744        match self {
745            RuntimeValue::Markdown(n, Some(sel)) => RuntimeValue::Markdown(
746                Shared::new((**n).clone().into_with_children_value(value, sel.index_value())),
747                Some(*sel),
748            ),
749            RuntimeValue::Markdown(n, selector) => {
750                RuntimeValue::Markdown(Shared::new((**n).clone().into_with_value(value)), *selector)
751            }
752            _ => RuntimeValue::NONE,
753        }
754    }
755
756    /// Returns the position information for a markdown node, if available.
757    #[inline(always)]
758    pub fn position(&self) -> Option<mq_markdown::Position> {
759        match self {
760            RuntimeValue::Markdown(node, _) => node.position(),
761            _ => None,
762        }
763    }
764
765    /// Sets the position information for a markdown node.
766    ///
767    /// Only affects markdown values; other value types are unaffected.
768    #[inline(always)]
769    pub fn set_position(&mut self, position: Option<mq_markdown::Position>) {
770        if let RuntimeValue::Markdown(node, _) = self {
771            markdown_mut(node).set_position(position);
772        }
773    }
774
775    /// Clears position information from a markdown node (recursively).
776    ///
777    /// Only affects markdown values; other value types are unaffected.
778    #[inline(always)]
779    pub fn strip_positions(&mut self) {
780        if let RuntimeValue::Markdown(node, _) = self {
781            markdown_mut(node).strip_positions();
782        }
783    }
784
785    /// Clears position only from the `Text` leaf written by a prior `update_markdown_value`
786    /// call, so the renderer won't re-escape it. Unlike `strip_positions`, leaves the rest of
787    /// the tree untouched.
788    #[inline(always)]
789    pub fn strip_updated_text_position(&mut self) {
790        if let RuntimeValue::Markdown(node, selector) = self {
791            let index = (*selector).map(Selector::index_value).unwrap_or(0);
792            markdown_mut(node).clear_text_position_at(index);
793        }
794    }
795
796    #[inline(always)]
797    fn string(&self) -> Cow<'_, str> {
798        match self {
799            Self::Number(n) => Cow::Owned(n.to_string()),
800            Self::Boolean(b) => Cow::Owned(b.to_string()),
801            Self::String(s) => Cow::Owned(format!(r#""{}""#, s)),
802            Self::Symbol(i) => Cow::Owned(format!(":{}", i)),
803            Self::Array(a) => Cow::Owned(format!(
804                "[{}]",
805                a.iter().map(|v| v.string()).collect::<Vec<Cow<str>>>().join(", ")
806            )),
807            Self::Markdown(m, ..) => Cow::Owned(m.to_string()),
808            Self::None => Cow::Borrowed(""),
809            Self::NativeFunction(_) => Cow::Borrowed("native_function"),
810            Self::CoroutineBuiltin(_) => Cow::Borrowed("native_function"),
811            Self::Closure(_) => Cow::Borrowed("function"),
812            Self::Bytes(b) => Cow::Owned(bytes_to_hex(b)),
813            Self::Coroutine(_) | Self::WeakCoroutine(_) => Cow::Borrowed("coroutine"),
814            #[cfg(any(feature = "file-io", feature = "http"))]
815            Self::ReaderHandle(handle) => Cow::Borrowed(handle.kind().as_str()),
816            Self::Dict(map) => {
817                let items = map
818                    .iter()
819                    .map(|(k, v)| format!("\"{}\": {}", k, v.string()))
820                    .collect::<Vec<String>>()
821                    .join(", ");
822                Cow::Owned(format!("{{{}}}", items))
823            }
824        }
825    }
826
827    /// Returns a new runtime value that is the logical negation of this value.
828    pub fn negated(&self) -> Self {
829        match self {
830            RuntimeValue::Boolean(b) => RuntimeValue::Boolean(!b),
831            RuntimeValue::Number(n) => RuntimeValue::Number((-n.value()).into()),
832            RuntimeValue::String(s) => RuntimeValue::String(Shared::new(s.chars().rev().collect())),
833            _ => self.clone(),
834        }
835    }
836
837    /// Converts the value to a JSON value; unrepresentable values become null.
838    pub fn to_json_value(self) -> serde_json::Value {
839        use base64::Engine;
840        match self {
841            RuntimeValue::None => serde_json::Value::Null,
842            RuntimeValue::Boolean(b) => serde_json::Value::Bool(b),
843            RuntimeValue::Number(n) => {
844                let v = n.value();
845                // `i64::MAX as f64` and `u64::MAX as f64` round up to 2^63 and 2^64, so `<` keeps the bounds exact.
846                if n.is_int() && v >= i64::MIN as f64 && v < i64::MAX as f64 {
847                    serde_json::Value::Number(serde_json::Number::from(n.to_int()))
848                } else if n.is_int() && v >= 0.0 && v < u64::MAX as f64 {
849                    serde_json::Value::Number(serde_json::Number::from(v as u64))
850                } else {
851                    // jq compatible: infinities clamp to the largest finite f64, NaN is null.
852                    let v = if v.is_infinite() { f64::MAX.copysign(v) } else { v };
853                    serde_json::Number::from_f64(v)
854                        .map(serde_json::Value::Number)
855                        .unwrap_or(serde_json::Value::Null)
856                }
857            }
858            RuntimeValue::String(s) => serde_json::Value::String(Shared::unwrap_or_clone(s)),
859            RuntimeValue::Symbol(i) => serde_json::Value::String(i.to_string()),
860            RuntimeValue::Array(arr) => serde_json::Value::Array(
861                Shared::unwrap_or_clone(arr)
862                    .into_iter()
863                    .map(Self::to_json_value)
864                    .collect(),
865            ),
866            RuntimeValue::Dict(map) => {
867                let obj: serde_json::Map<String, serde_json::Value> = Shared::unwrap_or_clone(map)
868                    .into_iter()
869                    .map(|(k, v)| (k.to_string(), v.to_json_value()))
870                    .collect();
871                serde_json::Value::Object(obj)
872            }
873            RuntimeValue::Bytes(b) => serde_json::Value::String(base64::engine::general_purpose::STANDARD.encode(&*b)),
874            RuntimeValue::Markdown(node, _) => serde_json::to_value(node.as_ref()).unwrap_or(serde_json::Value::Null),
875            _ => serde_json::Value::Null,
876        }
877    }
878
879    /// Converts the value to a CBOR value; unrepresentable values become null.
880    pub fn to_cbor_value(self) -> ciborium::Value {
881        match self {
882            RuntimeValue::None => ciborium::Value::Null,
883            RuntimeValue::Boolean(b) => ciborium::Value::Bool(b),
884            RuntimeValue::Number(n) => ciborium::Value::Float(n.value()),
885            RuntimeValue::String(s) => ciborium::Value::Text(Shared::unwrap_or_clone(s)),
886            RuntimeValue::Symbol(i) => ciborium::Value::Text(i.to_string()),
887            RuntimeValue::Bytes(b) => ciborium::Value::Bytes(Shared::unwrap_or_clone(b)),
888            RuntimeValue::Array(arr) => ciborium::Value::Array(
889                Shared::unwrap_or_clone(arr)
890                    .into_iter()
891                    .map(Self::to_cbor_value)
892                    .collect(),
893            ),
894            RuntimeValue::Dict(map) => ciborium::Value::Map(
895                Shared::unwrap_or_clone(map)
896                    .into_iter()
897                    .map(|(k, v)| (ciborium::Value::Text(k.to_string()), v.to_cbor_value()))
898                    .collect(),
899            ),
900            _ => ciborium::Value::Null,
901        }
902    }
903}
904
905/// Error returned by [`from_value`].
906#[derive(Debug, thiserror::Error)]
907#[error("{0}")]
908pub struct FromValueError(serde_json::Error);
909
910/// Deserializes a runtime value into `T` through its JSON form (see
911/// [`RuntimeValue::to_json_value`]).
912///
913/// # Examples
914///
915/// ```rust
916/// #[derive(serde::Deserialize)]
917/// struct Task {
918///     title: String,
919///     done: bool,
920/// }
921///
922/// let mut engine = mq_lang::DefaultEngine::default();
923/// engine.load_builtin_module();
924/// let output = engine
925///     .eval(r#"{"title": "build", "done": true}"#, mq_lang::null_input().into_iter())
926///     .unwrap();
927/// let task: Task = mq_lang::from_value(&output[0]).unwrap();
928/// assert_eq!(task.title, "build");
929/// assert!(task.done);
930/// ```
931pub fn from_value<T: serde::de::DeserializeOwned>(value: &RuntimeValue) -> Result<T, FromValueError> {
932    serde_json::from_value(value.clone().to_json_value()).map_err(FromValueError)
933}
934
935/// A collection of runtime values.
936///
937/// Provides utilities for working with multiple values, such as filtering
938/// and updating operations.
939#[derive(Debug, Clone, PartialEq)]
940pub struct RuntimeValues(Vec<RuntimeValue>);
941
942impl From<Vec<RuntimeValue>> for RuntimeValues {
943    fn from(values: Vec<RuntimeValue>) -> Self {
944        Self(values)
945    }
946}
947
948impl Index<usize> for RuntimeValues {
949    type Output = RuntimeValue;
950
951    fn index(&self, index: usize) -> &Self::Output {
952        &self.0[index]
953    }
954}
955
956impl IndexMut<usize> for RuntimeValues {
957    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
958        &mut self.0[index]
959    }
960}
961
962impl IntoIterator for RuntimeValues {
963    type IntoIter = std::vec::IntoIter<RuntimeValue>;
964    type Item = RuntimeValue;
965
966    fn into_iter(self) -> Self::IntoIter {
967        self.0.into_iter()
968    }
969}
970
971impl RuntimeValues {
972    /// Returns a compacted version of this collection, removing `None` and empty values.
973    pub fn compact(&self) -> Vec<RuntimeValue> {
974        self.0
975            .iter()
976            .filter(|v| !v.is_none() && !v.is_empty())
977            .cloned()
978            .collect::<Vec<_>>()
979    }
980
981    /// Returns a reference to the underlying vector of values.
982    pub fn values(&self) -> &Vec<RuntimeValue> {
983        &self.0
984    }
985
986    /// Converts every value with [`RuntimeValue::into_markdown_node`], dropping values whose
987    /// selector points at a child that no longer exists instead of exporting a phantom node.
988    pub fn into_markdown_nodes(self) -> Vec<Node> {
989        self.0
990            .into_iter()
991            .filter_map(RuntimeValue::into_markdown_node)
992            .collect()
993    }
994
995    /// Returns the number of values in this collection.
996    pub fn len(&self) -> usize {
997        self.0.len()
998    }
999
1000    /// Returns `true` if this collection contains no values.
1001    pub fn is_empty(&self) -> bool {
1002        self.0.len() == 0
1003    }
1004
1005    /// Updates this collection with values from another collection.
1006    ///
1007    /// Pairs corresponding elements from both collections and applies special
1008    /// update logic for markdown nodes.
1009    pub fn update_with(&self, other: Self) -> Self {
1010        self.0
1011            .clone()
1012            .into_iter()
1013            .zip(other)
1014            .map(|(current_value, mut updated_value)| {
1015                updated_value.set_position(current_value.position());
1016
1017                if let RuntimeValue::Markdown(node, _) = &current_value {
1018                    match &updated_value {
1019                        RuntimeValue::None | RuntimeValue::NativeFunction(_) | RuntimeValue::CoroutineBuiltin(_) => {
1020                            current_value.clone()
1021                        }
1022                        RuntimeValue::Closure(_) => current_value.clone(),
1023                        RuntimeValue::Coroutine(_) | RuntimeValue::WeakCoroutine(_) => current_value.clone(),
1024                        #[cfg(any(feature = "file-io", feature = "http"))]
1025                        RuntimeValue::ReaderHandle(_) => current_value.clone(),
1026                        RuntimeValue::Markdown(node, _) if node.is_empty() => current_value.clone(),
1027                        RuntimeValue::Markdown(node, _) => {
1028                            if node.is_fragment() {
1029                                if let RuntimeValue::Markdown(mut current_node, selector) = current_value {
1030                                    markdown_mut(&mut current_node).apply_fragment((**node).clone());
1031                                    RuntimeValue::Markdown(current_node, selector)
1032                                } else {
1033                                    updated_value
1034                                }
1035                            } else {
1036                                updated_value
1037                            }
1038                        }
1039                        RuntimeValue::String(s) => RuntimeValue::new_markdown(node.with_value(s)),
1040                        RuntimeValue::Symbol(i) => RuntimeValue::new_markdown(node.with_value(&i.to_string())),
1041                        RuntimeValue::Boolean(b) => RuntimeValue::new_markdown(node.with_value(b.to_string().as_str())),
1042                        RuntimeValue::Number(n) => RuntimeValue::new_markdown(node.with_value(n.to_string().as_str())),
1043                        RuntimeValue::Array(array) => RuntimeValue::Array(Shared::new(
1044                            array
1045                                .iter()
1046                                .filter_map(|o| {
1047                                    if o.is_none() {
1048                                        None
1049                                    } else {
1050                                        Some(RuntimeValue::Markdown(
1051                                            Shared::new(node.with_value(o.to_string().as_str())),
1052                                            None,
1053                                        ))
1054                                    }
1055                                })
1056                                .collect::<Vec<_>>(),
1057                        )),
1058                        RuntimeValue::Bytes(b) => RuntimeValue::new_markdown(node.with_value(bytes_to_hex(b).as_str())),
1059                        RuntimeValue::Dict(map) => {
1060                            let mut new_dict = DictMap::default();
1061                            for (k, v) in map.iter() {
1062                                if !v.is_none() && !v.is_empty() {
1063                                    new_dict.insert(
1064                                        *k,
1065                                        RuntimeValue::new_markdown(node.with_value(v.to_string().as_str())),
1066                                    );
1067                                }
1068                            }
1069                            RuntimeValue::Dict(Shared::new(new_dict))
1070                        }
1071                    }
1072                } else {
1073                    updated_value
1074                }
1075            })
1076            .collect::<Vec<_>>()
1077            .into()
1078    }
1079}
1080
1081#[cfg(test)]
1082mod tests {
1083    use super::*;
1084    use proptest::prelude::*;
1085    use rstest::rstest;
1086    use serde::Deserialize;
1087
1088    #[test]
1089    fn runtime_value_is_16_bytes() {
1090        assert!(
1091            std::mem::size_of::<RuntimeValue>() <= 16,
1092            "RuntimeValue grew to {} bytes; box the new payload instead of widening it",
1093            std::mem::size_of::<RuntimeValue>()
1094        );
1095    }
1096
1097    #[rstest]
1098    #[case("1: x", "1")]
1099    #[case("true: x", "true")]
1100    #[case("null: x", "null")]
1101    #[case("1.5: x", "1.5")]
1102    #[case("? [1, 2]\n: x", "[1, 2]")]
1103    #[case("? {a: 1, b: [x, y]}\n: x", "{a: 1, b: [x, y]}")]
1104    fn yaml_mapping_key_string(#[case] src: &str, #[case] expected: &str) {
1105        let doc = yaml_rust2::YamlLoader::load_from_str(src).unwrap().remove(0);
1106        let RuntimeValue::Dict(d) = RuntimeValue::from(doc) else {
1107            panic!("expected dict");
1108        };
1109        assert_eq!(d.keys().map(|k| k.to_string()).collect::<Vec<_>>(), vec![expected]);
1110    }
1111
1112    fn dict(entries: &[(&str, RuntimeValue)]) -> RuntimeValue {
1113        let mut map = DictMap::default();
1114        for (key, value) in entries {
1115            map.insert(Ident::new(key), value.clone());
1116        }
1117        RuntimeValue::Dict(Shared::new(map))
1118    }
1119
1120    #[rstest]
1121    #[case::empty(dict(&[]), false)]
1122    #[case::non_empty(dict(&[("a", RuntimeValue::NONE)]), true)]
1123    fn test_dict_is_truthy(#[case] value: RuntimeValue, #[case] expected: bool) {
1124        assert_eq!(value.is_truthy(), expected);
1125    }
1126
1127    #[rstest]
1128    #[case::string("a".into(), Some("a"), None, None)]
1129    #[case::number(RuntimeValue::Number(1.5.into()), None, Some(1.5), None)]
1130    #[case::boolean(RuntimeValue::TRUE, None, None, Some(true))]
1131    #[case::none(RuntimeValue::NONE, None, None, None)]
1132    fn test_scalar_accessors(
1133        #[case] value: RuntimeValue,
1134        #[case] string: Option<&str>,
1135        #[case] number: Option<f64>,
1136        #[case] boolean: Option<bool>,
1137    ) {
1138        assert_eq!(value.as_str(), string);
1139        assert_eq!(value.as_f64(), number);
1140        assert_eq!(value.as_bool(), boolean);
1141    }
1142
1143    #[rstest]
1144    #[case::array(vec![RuntimeValue::TRUE].into(), Some(vec![RuntimeValue::TRUE]))]
1145    #[case::string("a".into(), None)]
1146    fn test_as_array(#[case] value: RuntimeValue, #[case] expected: Option<Vec<RuntimeValue>>) {
1147        assert_eq!(value.as_array().map(<[RuntimeValue]>::to_vec), expected);
1148    }
1149
1150    #[rstest]
1151    #[case::present(dict(&[("title", "build".into())]), "title", Some(RuntimeValue::from("build")))]
1152    #[case::missing(dict(&[("title", "build".into())]), "title_never_interned_anywhere", None)]
1153    #[case::not_dict("title".into(), "title", None)]
1154    fn test_get(#[case] value: RuntimeValue, #[case] key: &str, #[case] expected: Option<RuntimeValue>) {
1155        assert_eq!(value.get(key).cloned(), expected);
1156        assert_eq!(value.as_dict().is_some(), matches!(value, RuntimeValue::Dict(_)));
1157    }
1158
1159    #[test]
1160    fn test_get_does_not_intern_missing_keys() {
1161        let value = dict(&[]);
1162        assert!(value.get("key_only_used_by_this_lookup").is_none());
1163        assert!(Ident::lookup("key_only_used_by_this_lookup").is_none());
1164    }
1165
1166    #[rstest]
1167    #[case::markdown(RuntimeValue::new_markdown("text".into()), Some(Node::from("text")))]
1168    #[case::string("text".into(), Some(Node::from("text")))]
1169    #[case::number(RuntimeValue::Number(2.into()), Some(Node::from("2")))]
1170    #[case::existing_selected_child(
1171        RuntimeValue::Markdown(
1172            Shared::new(Node::List(mq_markdown::List {
1173                values: vec![Node::from("item")],
1174                ..Default::default()
1175            })),
1176            Selector::index(0),
1177        ),
1178        Some(Node::from("item"))
1179    )]
1180    #[case::out_of_range_selected_child(
1181        RuntimeValue::Markdown(
1182            Shared::new(Node::List(mq_markdown::List {
1183                values: vec![Node::from("item")],
1184                ..Default::default()
1185            })),
1186            Selector::index(1),
1187        ),
1188        None
1189    )]
1190    fn test_into_markdown_node(#[case] value: RuntimeValue, #[case] expected: Option<Node>) {
1191        assert_eq!(value.into_markdown_node(), expected);
1192    }
1193
1194    #[test]
1195    fn test_into_markdown_nodes_keeps_order() {
1196        let values: RuntimeValues = vec![RuntimeValue::new_markdown("a".into()), "b".into()].into();
1197        assert_eq!(values.into_markdown_nodes(), vec![Node::from("a"), Node::from("b")]);
1198    }
1199
1200    #[derive(Debug, Deserialize, PartialEq)]
1201    struct CodeBlock {
1202        lang: Option<String>,
1203        code: String,
1204    }
1205
1206    #[derive(Debug, Deserialize, PartialEq)]
1207    struct Section {
1208        title: String,
1209        #[serde(default)]
1210        description: Option<String>,
1211        codes: Vec<CodeBlock>,
1212        level: u8,
1213    }
1214
1215    #[test]
1216    fn test_from_value_into_struct() {
1217        let value = dict(&[
1218            ("title", "Build".into()),
1219            ("level", RuntimeValue::Number(2.into())),
1220            (
1221                "codes",
1222                vec![dict(&[("lang", "sh".into()), ("code", "make".into())])].into(),
1223            ),
1224        ]);
1225
1226        assert_eq!(
1227            from_value::<Section>(&value).unwrap(),
1228            Section {
1229                title: "Build".to_string(),
1230                description: None,
1231                codes: vec![CodeBlock {
1232                    lang: Some("sh".to_string()),
1233                    code: "make".to_string(),
1234                }],
1235                level: 2,
1236            }
1237        );
1238    }
1239
1240    #[rstest]
1241    #[case::missing_field(dict(&[("title", "Build".into())]))]
1242    #[case::wrong_type(dict(&[("title", RuntimeValue::TRUE), ("codes", RuntimeValue::empty_array()), ("level", RuntimeValue::Number(1.into()))]))]
1243    #[case::fractional_level(dict(&[("title", "a".into()), ("codes", RuntimeValue::empty_array()), ("level", RuntimeValue::Number(1.5.into()))]))]
1244    fn test_from_value_rejects_mismatch(#[case] value: RuntimeValue) {
1245        assert!(from_value::<Section>(&value).is_err());
1246    }
1247
1248    proptest! {
1249        #[test]
1250        fn from_value_round_trips_scalars(s in ".*", n in any::<i32>(), b in any::<bool>()) {
1251            prop_assert_eq!(from_value::<String>(&RuntimeValue::from(s.clone())).unwrap(), s);
1252            prop_assert_eq!(from_value::<i32>(&RuntimeValue::Number((n as f64).into())).unwrap(), n);
1253            prop_assert_eq!(from_value::<bool>(&RuntimeValue::Boolean(b)).unwrap(), b);
1254        }
1255
1256        #[test]
1257        fn from_value_round_trips_string_arrays(items in prop::collection::vec(".*", 0..8)) {
1258            let value: RuntimeValue = items.iter().cloned().map(RuntimeValue::from).collect::<Vec<_>>().into();
1259            prop_assert_eq!(from_value::<Vec<String>>(&value).unwrap(), items);
1260        }
1261    }
1262}