Skip to main content

nybl/value_conversion/
error.rs

1#[cfg(all(feature = "no_std", not(feature = "std")))]
2use alloc::{format, string::String, vec::Vec};
3#[cfg(any(feature = "std", not(feature = "no_std")))]
4use std::{format, string::String, vec::Vec};
5
6use core::fmt;
7
8use crate::{NyblError, Value};
9
10/// One location component inside a nested Rust ↔ Nybl conversion.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum ValuePathSegment {
13    /// Array position, rendered as `[index]`.
14    Index(usize),
15    /// Dict key, rendered as `["key"]`.
16    Key(String),
17    /// Canonical built-in Result payload, rendered as `<Ok>` or `<Err>`.
18    ResultVariant(String),
19}
20
21/// A precise Rust ↔ Nybl conversion failure.
22///
23/// `expected` and `actual` describe the failed boundary. `path` is empty at
24/// the root and accumulates array indices, dict keys, and Result variants as a
25/// nested conversion unwinds.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct ValueConversionError {
28    expected: String,
29    actual: String,
30    path: Vec<ValuePathSegment>,
31}
32
33impl ValueConversionError {
34    /// Create a conversion error at the root value.
35    ///
36    /// Custom [`IntoValue`](crate::IntoValue) and
37    /// [`FromValue`](crate::FromValue) implementations can use this to retain
38    /// the same expected/actual diagnostic shape as the built-in conversions.
39    pub fn new(expected: impl Into<String>, actual: impl Into<String>) -> Self {
40        Self {
41            expected: expected.into(),
42            actual: actual.into(),
43            path: Vec::new(),
44        }
45    }
46
47    pub(crate) fn type_mismatch(expected: impl Into<String>, value: &Value) -> Self {
48        Self::new(expected, describe_value(value))
49    }
50
51    pub(crate) fn construction(error: NyblError) -> Self {
52        Self::new("a Nybl value within runtime limits", error.message)
53    }
54
55    pub(crate) fn at_index(mut self, index: usize) -> Self {
56        self.path.insert(0, ValuePathSegment::Index(index));
57        self
58    }
59
60    pub(crate) fn at_key(mut self, key: impl Into<String>) -> Self {
61        self.path.insert(0, ValuePathSegment::Key(key.into()));
62        self
63    }
64
65    pub(crate) fn at_result_variant(mut self, variant: impl Into<String>) -> Self {
66        self.path
67            .insert(0, ValuePathSegment::ResultVariant(variant.into()));
68        self
69    }
70
71    /// Prepend one location to the structured root-to-leaf error path.
72    ///
73    /// This is useful when a custom conversion delegates to another
74    /// conversion for one of its fields or elements.
75    pub fn at_path(mut self, segment: ValuePathSegment) -> Self {
76        self.path.insert(0, segment);
77        self
78    }
79
80    /// Human-readable expected Rust/Nybl shape.
81    pub fn expected(&self) -> &str {
82        &self.expected
83    }
84
85    /// Human-readable value or shape actually encountered.
86    pub fn actual(&self) -> &str {
87        &self.actual
88    }
89
90    /// Structured path from the root value to the failing child.
91    pub fn path(&self) -> &[ValuePathSegment] {
92        &self.path
93    }
94}
95
96impl fmt::Display for ValueConversionError {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        write!(f, "value conversion failed at $")?;
99        for segment in &self.path {
100            match segment {
101                ValuePathSegment::Index(index) => write!(f, "[{index}]")?,
102                ValuePathSegment::Key(key) => {
103                    write!(f, "[\"")?;
104                    for ch in key.chars() {
105                        for escaped in ch.escape_default() {
106                            write!(f, "{escaped}")?;
107                        }
108                    }
109                    write!(f, "\"]")?;
110                }
111                ValuePathSegment::ResultVariant(variant) => write!(f, "<{variant}>")?,
112            }
113        }
114        write!(f, ": expected {}, got {}", self.expected, self.actual)
115    }
116}
117
118impl core::error::Error for ValueConversionError {}
119
120pub(crate) fn describe_value(value: &Value) -> String {
121    match value {
122        Value::Struct(value) => format!("struct {}.{}", value.module_path(), value.type_name()),
123        Value::EnumVariant(value) => format!(
124            "enum {}.{}::{}",
125            value.module_path(),
126            value.type_name(),
127            value.variant()
128        ),
129        other => other.type_name().into(),
130    }
131}