Skip to main content

datex_core/traits/
convert_value_container.rs

1#[cfg(feature = "compiler")]
2use crate::compiler::error::SpannedCompilerError;
3#[cfg(feature = "parser")]
4use crate::parser::errors::SpannedParserError;
5use crate::{
6    core_compiler::core_compilation_context::DXBWithSharedValues,
7    prelude::*,
8    runtime::{
9        Runtime,
10        execution::{
11            ExecutionError,
12            context::{ExecutionContext, ScriptExecutionError},
13        },
14    },
15    traits::{
16        classification::Classification,
17        convert_parts::{FromParts, HasPartsKind, IntoParts, PartsKind},
18    },
19    values::value_container::{
20        ValueContainer,
21        borrowed_value_container::{
22            BorrowedValueContainer, BorrowedValueContainerMut,
23        },
24    },
25};
26
27#[derive(Debug, PartialEq, Eq)]
28pub enum DeserializationError {
29    NoValue,
30    InvalidValue,
31    ExecutionError(Box<ExecutionError>),
32    CanNotReadFile(String),
33    #[cfg(feature = "parser")]
34    ParserError(SpannedParserError),
35    #[cfg(feature = "compiler")]
36    CompilerError(Box<SpannedCompilerError>),
37    NoStaticValueFound,
38}
39
40impl From<ExecutionError> for DeserializationError {
41    fn from(err: ExecutionError) -> DeserializationError {
42        DeserializationError::ExecutionError(Box::new(err))
43    }
44}
45
46#[cfg(feature = "parser")]
47impl From<SpannedParserError> for DeserializationError {
48    fn from(err: SpannedParserError) -> DeserializationError {
49        DeserializationError::ParserError(err)
50    }
51}
52
53impl From<ScriptExecutionError> for DeserializationError {
54    fn from(err: ScriptExecutionError) -> DeserializationError {
55        match err {
56            ScriptExecutionError::ExecutionError(e) => {
57                DeserializationError::ExecutionError(e)
58            }
59            #[cfg(feature = "compiler")]
60            ScriptExecutionError::CompilerError(e) => {
61                DeserializationError::CompilerError(e)
62            }
63        }
64    }
65}
66
67/// This traits allows converting types to and from [ValueContainer]s
68/// No value conversions are performed, only downcasts to more specific types or upcasts to more general types are performed
69pub trait ConvertValueContainer {
70    /// Convert the value to a [ValueContainer]
71    fn to_value_container(self) -> ValueContainer;
72
73    /// Borrow the value as a [BorrowedValueContainer]
74    fn as_borrowed_value_container(&self) -> BorrowedValueContainer<'_>;
75
76    /// Borrow the value as a mutable [BorrowedValueContainer]
77    fn as_borrowed_value_container_mut(
78        &mut self,
79    ) -> BorrowedValueContainerMut<'_>;
80
81    /// Tries to downcast a [ValueContainer] into [Self]
82    fn try_from_value_container(
83        value_container: ValueContainer,
84    ) -> Result<Self, ValueContainer>
85    where
86        Self: Sized;
87
88    /// Tries to downcast a [ValueContainer] into a reference of [Self]
89    fn try_borrow_from_value_container(
90        value_container: &ValueContainer,
91    ) -> Result<&Self, ()>
92    where
93        Self: Sized;
94
95    /// Tries to downcast a [ValueContainer] into a mutable reference of [Self]
96    fn try_borrow_mut_from_value_container(
97        value_container: &mut ValueContainer,
98    ) -> Result<&mut Self, ()>
99    where
100        Self: Sized;
101
102    /// Deserialize a value of type T from a byte slice containing DXB data
103    fn try_from_bytes(
104        dxb: Vec<u8>,
105        runtime: &Runtime,
106    ) -> Result<Self, DeserializationError>
107    where
108        Self: Sized + FromParts,
109    {
110        let value = runtime.execute_dxb_sync(
111            DXBWithSharedValues::new(dxb, vec![]),
112            None,
113            None::<ExecutionContext>,
114        )?;
115        if let Some(value) = value {
116            let config = Self::try_convert_from_value_container(value)
117                .map_err(|_| DeserializationError::InvalidValue)?;
118            Ok(config)
119        } else {
120            Err(DeserializationError::NoValue)
121        }
122    }
123
124    #[cfg(feature = "compiler")]
125    fn try_from_script(
126        script: &str,
127        runtime: &Runtime,
128    ) -> Result<Self, DeserializationError>
129    where
130        Self: Sized + FromParts,
131    {
132        let value =
133            runtime.execute_sync(script, &[], None::<ExecutionContext>)?;
134
135        if let Some(value) = value {
136            let config = Self::try_convert_from_value_container(value)
137                .map_err(|_| DeserializationError::InvalidValue)?;
138            Ok(config)
139        } else {
140            Err(DeserializationError::NoValue)
141        }
142    }
143
144    #[cfg(all(feature = "std", feature = "compiler"))]
145    fn try_from_dx_file(
146        path: &std::path::Path,
147        runtime: &Runtime,
148    ) -> Result<Self, DeserializationError>
149    where
150        Self: Sized + FromParts,
151    {
152        let script = std::fs::read_to_string(path)
153            .map_err(|e| DeserializationError::CanNotReadFile(e.to_string()))?;
154        Self::try_from_script(&script, runtime)
155    }
156
157    /// Create a value from a DX script string
158    /// This will extract a static value from the script without executing it
159    /// and use that value for deserialization
160    /// If no static value is found, an error is returned
161    /// This is useful for deserializing simple values like integer, text, map and list
162    /// without the need to execute the script
163    /// Note: This does not support expressions or computations in the script
164    /// For example, the script `{ "key": 42 }` will work, but the script `{ "key": 40 + 2 }` will not
165    /// because the latter requires execution to evaluate the expression
166    /// and extract the value
167    #[cfg(feature = "compiler")]
168    fn try_from_static_script(
169        script: &str,
170    ) -> Result<Self, DeserializationError>
171    where
172        Self: Sized,
173    {
174        let value = crate::compiler::extract_static_value_from_script(script)?
175            .ok_or(DeserializationError::NoStaticValueFound)?;
176        Self::try_from_value_container(value)
177            .map_err(|_| DeserializationError::InvalidValue)
178    }
179
180    /// Tries to cast a [ValueContainer] into the specified type [T].
181    /// First, it attempts a direct conversion (downcast) of the [ValueContainer]
182    /// into the type [T].
183    /// If that fails, it tries to convert the [ValueContainer] into map or list parts and then into the type [T].
184    fn try_convert_from_value_container(
185        value_container: ValueContainer,
186    ) -> Result<Self, ()>
187    where
188        Self: FromParts + Sized,
189    {
190        // first try to convert (downcast) the value container directly into the type T
191        let val = Self::try_from_value_container(value_container);
192        match val {
193            Ok(value) => Ok(value),
194            // otherwise, try to convert the value container into map or list parts and then into the type T
195            Err(value_container) => {
196                let classification =
197                    value_container.unresolved_classification();
198                let tag = classification.tag_str();
199
200                match value_container.parts_kind() {
201                    PartsKind::Map => {
202                        let map_parts =
203                            Box::new(value_container).try_into_map_parts();
204                        if let Ok(map) = map_parts {
205                            Self::try_from_map_parts_with_tag(map, tag)
206                        } else {
207                            Err(())
208                        }
209                    }
210                    PartsKind::List => {
211                        let list_parts =
212                            Box::new(value_container).try_into_list_parts();
213                        if let Ok(list) = list_parts {
214                            Self::try_from_list_parts_with_tag(list, tag)
215                        } else {
216                            Err(())
217                        }
218                    }
219                    PartsKind::SingleValue => {
220                        let single_value_parts =
221                            Box::new(value_container).try_into_single_value();
222                        if let Ok(single_value) = single_value_parts {
223                            Self::try_from_single_value_with_tag(
224                                single_value,
225                                tag,
226                            )
227                        } else {
228                            Err(())
229                        }
230                    }
231                    PartsKind::None => Err(()),
232                }
233            }
234        }
235    }
236}