nybl/value_conversion/
error.rs1#[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#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum ValuePathSegment {
13 Index(usize),
15 Key(String),
17 ResultVariant(String),
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct ValueConversionError {
28 expected: String,
29 actual: String,
30 path: Vec<ValuePathSegment>,
31}
32
33impl ValueConversionError {
34 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 pub fn at_path(mut self, segment: ValuePathSegment) -> Self {
76 self.path.insert(0, segment);
77 self
78 }
79
80 pub fn expected(&self) -> &str {
82 &self.expected
83 }
84
85 pub fn actual(&self) -> &str {
87 &self.actual
88 }
89
90 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}