Skip to main content

datex_core/datex_proxy/
mod.rs

1pub mod serde_compat;
2pub mod shared;
3
4#[cfg(feature = "compiler")]
5use crate::compiler::error::SpannedCompilerError;
6#[cfg(feature = "parser")]
7use crate::parser::errors::SpannedParserError;
8use crate::{
9    core_compiler::core_compilation_context::DXBWithSharedValues,
10    prelude::*,
11    runtime::{
12        Runtime,
13        cache::shared_references_cache::SharedReferencesCache,
14        execution::{ExecutionError, context::ScriptExecutionError},
15    },
16    shared_values::errors::KeyNotFoundError,
17    types::r#type::Type,
18    values::{value::Value, value_container::ValueContainer},
19};
20
21#[cfg(feature = "decompiler")]
22use crate::decompiler::{DecompileOptions, decompile_value};
23
24#[derive(Debug, Clone)]
25pub struct TryFromDatexValueError(pub String);
26
27#[derive(Debug, Clone)]
28pub struct TryToDatexValueError(pub String);
29
30#[derive(Debug)]
31pub enum DeserializationError {
32    NoValue,
33    InvalidValue(TryFromDatexValueError),
34    ExecutionError(ExecutionError),
35    CanNotReadFile(String),
36    #[cfg(feature = "parser")]
37    ParserError(SpannedParserError),
38    #[cfg(feature = "compiler")]
39    CompilerError(SpannedCompilerError),
40    NoStaticValueFound,
41}
42
43impl From<ExecutionError> for DeserializationError {
44    fn from(err: ExecutionError) -> DeserializationError {
45        DeserializationError::ExecutionError(err)
46    }
47}
48
49#[cfg(feature = "parser")]
50impl From<SpannedParserError> for DeserializationError {
51    fn from(err: SpannedParserError) -> DeserializationError {
52        DeserializationError::ParserError(err)
53    }
54}
55
56impl From<TryFromDatexValueError> for DeserializationError {
57    fn from(err: TryFromDatexValueError) -> DeserializationError {
58        DeserializationError::InvalidValue(err)
59    }
60}
61
62impl From<ScriptExecutionError> for DeserializationError {
63    fn from(err: ScriptExecutionError) -> DeserializationError {
64        match err {
65            ScriptExecutionError::ExecutionError(e) => {
66                DeserializationError::ExecutionError(e)
67            }
68            #[cfg(feature = "compiler")]
69            ScriptExecutionError::CompilerError(e) => {
70                DeserializationError::CompilerError(e)
71            }
72        }
73    }
74}
75
76/// Base DATEX value Proxy trait - converts to and from [ValueContainer]
77/// Must implement [DatexValueContainerProxyDeserialize] and [DatexValueContainerProxySerialize]
78pub trait DatexValueContainerProxy:
79    Sized
80    + DatexValueContainerProxyDeserialize
81    + DatexValueContainerProxySerialize
82    + DatexProxyTypes
83{
84}
85
86/// Base DATEX value Proxy trait - converts to and from [Value]
87pub trait DatexValueProxy:
88    Sized + DatexValueProxyDeserialize + DatexValueProxySerialize + DatexProxyTypes
89{
90}
91
92/// Trait for providing DATEX type information for a DatexProxy type
93pub trait DatexProxyTypes {
94    fn datex_type(memory: &mut SharedReferencesCache) -> Type;
95}
96
97/// Conversion from a [ValueContainer] to a rust value
98pub trait DatexValueContainerProxyDeserialize: Sized {
99    fn try_from_value_container(
100        value: ValueContainer,
101    ) -> Result<Self, TryFromDatexValueError>;
102
103    fn try_from_map_property(
104        value: Result<ValueContainer, KeyNotFoundError>,
105    ) -> Result<Self, TryFromDatexValueError> {
106        let value =
107            value.map_err(|err| TryFromDatexValueError(err.to_string()))?;
108
109        Self::try_from_value_container(value)
110    }
111
112    /// Deserialize a value of type T from a byte slice containing DXB data
113    fn try_from_bytes(
114        dxb: Vec<u8>,
115        runtime: &Runtime,
116    ) -> Result<Self, DeserializationError> {
117        let value = runtime.execute_dxb_sync(
118            DXBWithSharedValues::new(dxb, vec![]),
119            None,
120            true,
121        )?;
122        if let Some(value) = value {
123            let config = Self::try_from_value_container(value)?;
124            Ok(config)
125        } else {
126            Err(DeserializationError::NoValue)
127        }
128    }
129
130    #[cfg(feature = "compiler")]
131    fn try_from_script(
132        script: &str,
133        runtime: &Runtime,
134    ) -> Result<Self, DeserializationError> {
135        let value = runtime.execute_sync(script, &[], None)?;
136        if let Some(value) = value {
137            let config = Self::try_from_value_container(value)?;
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        let script = std::fs::read_to_string(path)
150            .map_err(|e| DeserializationError::CanNotReadFile(e.to_string()))?;
151        Self::try_from_script(&script, runtime)
152    }
153
154    /// Create a value from a DX script string
155    /// This will extract a static value from the script without executing it
156    /// and use that value for deserialization
157    /// If no static value is found, an error is returned
158    /// This is useful for deserializing simple values like integer, text, map and list
159    /// without the need to execute the script
160    /// Note: This does not support expressions or computations in the script
161    /// For example, the script `{ "key": 42 }` will work, but the script `{ "key": 40 + 2 }` will not
162    /// because the latter requires execution to evaluate the expression
163    /// and extract the value
164    #[cfg(feature = "compiler")]
165    fn try_from_static_script(
166        script: &str,
167    ) -> Result<Self, DeserializationError> {
168        let value = crate::compiler::extract_static_value_from_script(script)?
169            .ok_or(DeserializationError::NoStaticValueFound)?;
170        Ok(Self::try_from_value_container(value)?)
171    }
172}
173
174/// Conversion from a [Value] to a rust value
175pub trait DatexValueProxyDeserialize: Sized {
176    fn try_from_value(value: Value) -> Result<Self, TryFromDatexValueError>;
177
178    fn try_from_map_property(
179        value: Result<Value, KeyNotFoundError>,
180    ) -> Result<Self, TryFromDatexValueError> {
181        let value =
182            value.map_err(|err| TryFromDatexValueError(err.to_string()))?;
183
184        Self::try_from_value(value)
185    }
186}
187
188/// Conversion from a rust value to a [ValueContainer]. Might fail if serde values are serialized.
189pub trait DatexValueContainerProxySerialize {
190    fn try_to_value_container(
191        self,
192    ) -> Result<ValueContainer, TryToDatexValueError>;
193
194    #[cfg(feature = "decompiler")]
195    fn try_to_datex_string(
196        self,
197        decompile_options: DecompileOptions,
198    ) -> Result<String, TryToDatexValueError>
199    where
200        Self: Sized,
201    {
202        Ok(decompile_value(
203            &self.try_to_value_container()?,
204            decompile_options,
205        ))
206    }
207}
208
209/// Conversion from a rust value to a [Value]. Might fail if serde values are serialized.
210pub trait DatexValueProxySerialize {
211    fn try_to_value(self) -> Result<Value, TryToDatexValueError>;
212}
213
214/// Infallible conversion from a rust value to a [ValueContainer].
215/// Only works if no serde values are serialized.
216pub trait DatexValueContainerProxyInfallibleSerialize {
217    fn to_value_container(self) -> ValueContainer;
218
219    #[cfg(feature = "decompiler")]
220    fn to_datex_string(self, decompile_options: DecompileOptions) -> String
221    where
222        Self: Sized,
223    {
224        decompile_value(&self.to_value_container(), decompile_options)
225    }
226}
227
228/// Infallible conversion from a rust value to a [Value].
229/// Only works if no serde values are serialized.
230pub trait DatexValueProxyInfallibleSerialize {
231    fn to_value(self) -> Value;
232}
233
234// Blanket DatexValueContainerProxy trait impls for types that implement DatexValueProxy traits:
235impl<T: DatexValueProxyDeserialize> DatexValueContainerProxyDeserialize for T {
236    fn try_from_value_container(
237        value: ValueContainer,
238    ) -> Result<Self, TryFromDatexValueError> {
239        match value {
240            ValueContainer::Local(val) => DatexValueProxyDeserialize::try_from_value(val),
241            _ => Err(TryFromDatexValueError("Cannot cast from ValueContainer::Shared, expected ValueContainer::Local".to_string())),
242        }
243    }
244    fn try_from_map_property(
245        value: Result<ValueContainer, KeyNotFoundError>,
246    ) -> Result<Self, TryFromDatexValueError> {
247        match value {
248            Ok(ValueContainer::Local(value)) => {
249                DatexValueProxyDeserialize::try_from_map_property(Ok(value))
250            }
251
252            Ok(_) => Err(TryFromDatexValueError("Cannot cast from ValueContainer::Shared, expected ValueContainer::Local".to_string())),
253
254            Err(err) => {
255                DatexValueProxyDeserialize::try_from_map_property(Err(err))
256            }
257        }
258    }
259}
260
261impl<T: DatexValueProxySerialize> DatexValueContainerProxySerialize for T {
262    fn try_to_value_container(
263        self,
264    ) -> Result<ValueContainer, TryToDatexValueError> {
265        DatexValueProxySerialize::try_to_value(self).map(ValueContainer::from)
266    }
267}
268
269impl<T: DatexValueProxyInfallibleSerialize>
270    DatexValueContainerProxyInfallibleSerialize for T
271{
272    fn to_value_container(self) -> ValueContainer {
273        ValueContainer::from(DatexValueProxyInfallibleSerialize::to_value(self))
274    }
275}
276
277impl<T: DatexValueProxy> DatexValueContainerProxy for T {}