sbrd_gen/
error.rs

1#![deny(missing_debug_implementations)]
2//! Module for errors used in this crate
3
4use crate::builder::ValueBound;
5use crate::eval::EvalError;
6use crate::value::{DataValue, DataValueMap};
7use crate::GeneratorType;
8use std::borrow::Borrow;
9
10/// A Error for a Schema
11#[derive(Debug)]
12pub struct SchemaError {
13    kind: SchemaErrorKind,
14    info: SchemaErrorInfo,
15}
16
17impl std::fmt::Display for SchemaError {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        match self.kind {
20            SchemaErrorKind::ParseError => write!(f, "Parse error: {}", self.info),
21            SchemaErrorKind::BuildError => write!(f, "Build error: {}", self.info),
22            SchemaErrorKind::GenerateError => write!(f, "Generate error: {}", self.info),
23            SchemaErrorKind::OutputError => write!(f, "Output error: {}", self.info),
24        }
25    }
26}
27
28impl std::error::Error for SchemaError {}
29
30impl SchemaError {
31    /// Check error's kind
32    pub fn is_kind_of(&self, kind: SchemaErrorKind) -> bool {
33        self.kind == kind
34    }
35
36    /// Get error's kind
37    pub fn get_kind(&self) -> SchemaErrorKind {
38        self.kind
39    }
40
41    /// Get error's information
42    pub fn get_error_info(&self) -> &dyn std::error::Error {
43        self.info.0.borrow()
44    }
45}
46
47/// Kinds of error for a Schema
48#[derive(Debug, Eq, PartialEq, Copy, Clone)]
49pub enum SchemaErrorKind {
50    /// Error kind for parser
51    ParseError,
52    /// Error kind for generator builder
53    BuildError,
54    /// Error kind for generating a value
55    GenerateError,
56    /// Error kind for writing to output
57    OutputError,
58}
59
60/// Error information
61#[derive(Debug)]
62struct SchemaErrorInfo(Box<dyn std::error::Error>);
63
64impl std::fmt::Display for SchemaErrorInfo {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        write!(f, "{}", self.0)
67    }
68}
69
70impl From<BuildError> for SchemaError {
71    fn from(e: BuildError) -> Self {
72        e.into_sbrd_gen_error(SchemaErrorKind::BuildError)
73    }
74}
75
76/// Trait for convert to [`SchemaError`] from other error
77///
78/// [`SchemaError`]: ./struct.SchemaError.html
79pub trait IntoSbrdError: 'static + std::error::Error + Sized {
80    /// Converter function to [`SchemaError`] from other error
81    ///
82    /// [`SchemaError`]: ./struct.SchemaError.html
83    fn into_sbrd_gen_error(self, kind: SchemaErrorKind) -> SchemaError {
84        SchemaError {
85            kind,
86            info: SchemaErrorInfo(Box::new(self)),
87        }
88    }
89}
90
91impl<E> IntoSbrdError for E where E: 'static + std::error::Error + Sized {}
92
93/// Alias of [`Result`] type
94///
95/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
96pub type SchemaResult<T> = std::result::Result<T, SchemaError>;
97
98/// Error for generator builder
99#[derive(Debug)]
100pub enum BuildError {
101    /// Specified `keys` in the Schema is not unique.
102    ///
103    /// # Arguments
104    /// * 0: Specified `keys`
105    SpecifiedKeyNotUnique(Vec<String>),
106
107    /// Specified `key` does not exist in generated values
108    ///
109    /// # Arguments
110    /// * 0: Specified `key`
111    /// * 1: Keys of generated values
112    NotExistSpecifiedKey(String, Vec<String>),
113
114    /// Specified `key` in the Schema already exist.
115    ///
116    /// # Arguments
117    /// * 0: Specified `key`
118    AlreadyExistKey(String),
119
120    /// Specified `type` in thea Schema is not valid type.
121    ///
122    /// # Arguments
123    /// * 0: Specified `type`
124    InvalidType(GeneratorType),
125
126    /// Specified value in the Schema is not valid value.
127    ///
128    /// # Arguments
129    /// * 0: Specified value's string
130    InvalidValue(String),
131
132    /// Specified value's key does not exist in the Schema.
133    ///
134    /// # Arguments
135    /// * 0: Specified value's key
136    NotExistValueOf(String),
137
138    /// Fail parse specified value in the Schema.
139    ///
140    /// # Arguments
141    /// * 0: Parse target value
142    /// * 1: Parse target type
143    /// * 2: Parse error message
144    FailParseValue(String, String, String),
145
146    /// Specified `range` in the Schema is empty range.
147    ///
148    /// # Arguments
149    /// * 0: Range bound
150    RangeEmpty(ValueBound<DataValue>),
151
152    /// Specified `children` in the Schema does not exist or does not have child.
153    EmptySelectableChildren,
154
155    /// Specified `values` in the Schema does not exist or does not have value.
156    EmptySelectValues,
157
158    /// Specified randomize values at the keys: `children`, `chars`, `values`, `filepath` is empty.
159    EmptySelectable,
160
161    /// Specified default case at the key `case` in the Schema at a child generator does not exist
162    NotExistDefaultCase,
163
164    /// Specified some of values at the key `weight` in the Schema at a child generator does not exist
165    AllWeightsZero,
166
167    /// Input/Output Error for a file.
168    ///
169    /// # Arguments
170    /// * 0: Error information
171    /// * 1: Occurred filepath
172    FileError(std::io::Error, std::path::PathBuf),
173
174    /// Error for fail build distribution with the specified parameters at the key `parameters` in the Schema
175    ///
176    /// # Arguments
177    /// * 0: Name of the distribution
178    /// * 1: Error information
179    FailBuildDistribution(String, String),
180}
181
182impl std::fmt::Display for BuildError {
183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        match self {
185            BuildError::SpecifiedKeyNotUnique(keys) => {
186                write!(f, "Not Unique Specified Keys: {:?}", keys)
187            }
188            BuildError::NotExistSpecifiedKey(key, keys) => {
189                write!(f, "Not Exist Key \"{}\" in {:?}", key, keys)
190            }
191            BuildError::AlreadyExistKey(k) => write!(f, "Already Exist Key: {}", k),
192            BuildError::InvalidType(t) => write!(f, "Invalid Type: {}", t),
193            BuildError::InvalidValue(s) => write!(f, "Invalid Value: {}", s),
194            BuildError::NotExistValueOf(s) => write!(f, "Not Exist Value for {}", s),
195            BuildError::FailParseValue(s, t, e) => {
196                write!(f, "Fail Parse {} as {} with error: {}", s, t, e)
197            }
198            BuildError::RangeEmpty(range) => write!(f, "Empty Range: {}", range),
199            BuildError::EmptySelectableChildren => write!(f, "Selectable children is empty"),
200            BuildError::EmptySelectValues => write!(f, "Selectable values is empty"),
201            BuildError::EmptySelectable => {
202                write!(f, "Selectable children or values is empty")
203            }
204            BuildError::NotExistDefaultCase => write!(f, "Not Exist default case condition"),
205            BuildError::AllWeightsZero => write!(f, "All weights are zero"),
206            BuildError::FileError(fe, path) => write!(
207                f,
208                "File Error: {} at filepath `{}`",
209                fe,
210                path.as_path().display()
211            ),
212            BuildError::FailBuildDistribution(dn, e) => {
213                write!(f, "Fail build {} distribution with error: {}", dn, e)
214            }
215        }
216    }
217}
218
219impl std::error::Error for BuildError {}
220
221/// Error for generator builder
222#[derive(Debug, PartialEq)]
223pub enum GenerateError {
224    /// Evaluate error while generating value
225    ///
226    /// # Arguments
227    /// * 0: Error information
228    /// * 1: Script
229    /// * 2: Context key-values
230    FailEval(EvalError, String, DataValueMap<String>),
231
232    /// Error for generate value while generating value
233    ///
234    /// # Arguments
235    /// * 0: Error message
236    FailGenerate(String),
237
238    /// Not found generate values at the key while generating value
239    ///
240    /// # Arguments
241    /// * 0: Key
242    /// * 1: Generated values
243    NotExistGeneratedKey(String, DataValueMap<String>),
244}
245
246impl std::fmt::Display for GenerateError {
247    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
248        match self {
249            GenerateError::FailEval(e, script, context) => {
250                write!(
251                    f,
252                    "Fail Evaluate Script \"{}\" in context {:?} with error: {}",
253                    script, context, e
254                )
255            }
256            GenerateError::FailGenerate(s) => {
257                write!(f, "Fail Generate valid data. Because {}", s)
258            }
259            GenerateError::NotExistGeneratedKey(key, values) => {
260                write!(f, "Not exist key \"{}\" in {:?}", key, values)
261            }
262        }
263    }
264}
265
266impl std::error::Error for GenerateError {}