garnish_lang_simple_data/data/
mod.rs

1use std::collections::HashMap;
2use std::fmt::Debug;
3use std::hash::Hash;
4#[cfg(feature = "serde")]
5use serde::{Deserialize, Serialize};
6
7use garnish_lang_traits::GarnishDataType;
8pub use number::*;
9pub use parsing::*;
10pub use iterators::*;
11pub use stack_frame::*;
12
13use crate::{DataError, NoCustom, symbol_value};
14
15mod display;
16mod number;
17mod parsing;
18mod iterators;
19mod stack_frame;
20
21pub use display::*;
22
23pub type CustomDataDisplayHandler<T> = fn(&SimpleDataList<T>, &T) -> String;
24
25pub const UNIT_INDEX: usize = 0;
26
27/// List of [`SimpleData`] with maps to convert symbolic values to original string.
28#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
29#[derive(Debug, Clone, Eq, PartialEq)]
30pub struct SimpleDataList<T = NoCustom>
31where
32    T: Clone + PartialEq + Eq + PartialOrd + Debug + Hash,
33{
34    list: Vec<SimpleData<T>>,
35    symbol_to_name: HashMap<u64, String>,
36    expression_to_symbol: HashMap<usize, u64>,
37    external_to_symbol: HashMap<usize, u64>
38}
39
40impl<T> Default for SimpleDataList<T>
41where
42    T: Clone + PartialEq + Eq + PartialOrd + Debug + Hash,
43{
44    fn default() -> Self {
45        SimpleDataList::new()
46            .append(SimpleData::Unit)
47            .append(SimpleData::False)
48            .append(SimpleData::True)
49    }
50}
51
52impl<T> SimpleDataList<T>
53where
54    T: Clone + PartialEq + Eq + PartialOrd + Debug + Hash,
55{
56    pub fn new() -> Self {
57        SimpleDataList {
58            list: vec![],
59            symbol_to_name: HashMap::new(),
60            expression_to_symbol: HashMap::new(),
61            external_to_symbol: HashMap::new(),
62        }
63    }
64
65    pub fn append(mut self, item: SimpleData<T>) -> Self {
66        self.list.push(item);
67        self
68    }
69
70    pub fn append_symbol<S: Into<String>>(mut self, s: S) -> Self {
71        let s: String = s.into();
72        let sym = symbol_value(&s);
73        self.list.push(SimpleData::Symbol(sym));
74        self.symbol_to_name.insert(sym, s);
75        self
76    }
77
78    pub fn push(&mut self, item: SimpleData<T>) {
79        self.list.push(item);
80    }
81
82    pub fn get(&self, index: usize) -> Option<&SimpleData<T>> {
83        self.list.get(index)
84    }
85
86    pub fn get_mut(&mut self, index: usize) -> Option<&mut SimpleData<T>> {
87        self.list.get_mut(index)
88    }
89
90    pub fn len(&self) -> usize {
91        self.list.len()
92    }
93
94    pub fn symbol_to_name(&self) -> &HashMap<u64, String> {
95        &self.symbol_to_name
96    }
97
98    pub fn insert_symbol<S: Into<String>>(&mut self, sym: u64, name: S) {
99        self.symbol_to_name.insert(sym, name.into());
100    }
101
102    pub fn get_symbol(&self, sym: u64) -> Option<&String> {
103        self.symbol_to_name.get(&sym)
104    }
105
106    pub fn insert_expression(&mut self, expression: usize, sym: u64) {
107        self.expression_to_symbol.insert(expression, sym);
108    }
109
110    pub fn insert_external(&mut self, external: usize, sym: u64) {
111        self.external_to_symbol.insert(external, sym);
112    }
113}
114
115/// Alias for simple error type
116pub type DataCastResult<T> = Result<T, DataError>;
117
118/// Alias for [`SimpleData`] with [`NoCustom`] type parameter.
119pub type SimpleDataNC = SimpleData<NoCustom>;
120
121/// Data object to give [`GarnishDataType`] typed values. Can be passed a type parameter to extend supported data.
122#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
123#[derive(Clone, PartialEq, Eq, PartialOrd, Debug, Hash)]
124pub enum SimpleData<T = NoCustom>
125where
126    T: Clone + PartialEq + Eq + PartialOrd + Debug + Hash,
127{
128    Unit,
129    True,
130    False,
131    Type(GarnishDataType),
132    Number(SimpleNumber),
133    Char(char),
134    Byte(u8),
135    Symbol(u64),
136    SymbolList(Vec<u64>),
137    Expression(usize),
138    External(usize),
139    CharList(String),
140    ByteList(Vec<u8>),
141    Pair(usize, usize),
142    Range(usize, usize),
143    Slice(usize, usize),
144    Partial(usize, usize),
145    List(Vec<usize>, Vec<usize>),
146    Concatenation(usize, usize),
147    StackFrame(SimpleStackFrame),
148    Custom(T),
149}
150
151impl<T> SimpleData<T>
152where
153    T: Clone + PartialEq + Eq + PartialOrd + Debug + Hash,
154{
155    pub fn get_data_type(&self) -> GarnishDataType {
156        match self {
157            SimpleData::Unit => GarnishDataType::Unit,
158            SimpleData::True => GarnishDataType::True,
159            SimpleData::False => GarnishDataType::False,
160            SimpleData::Type(_) => GarnishDataType::Type,
161            SimpleData::Number(_) => GarnishDataType::Number,
162            SimpleData::Char(_) => GarnishDataType::Char,
163            SimpleData::Byte(_) => GarnishDataType::Byte,
164            SimpleData::Symbol(_) => GarnishDataType::Symbol,
165            SimpleData::SymbolList(_) => GarnishDataType::SymbolList,
166            SimpleData::Expression(_) => GarnishDataType::Expression,
167            SimpleData::External(_) => GarnishDataType::External,
168            SimpleData::CharList(_) => GarnishDataType::CharList,
169            SimpleData::ByteList(_) => GarnishDataType::ByteList,
170            SimpleData::Pair(_, _) => GarnishDataType::Pair,
171            SimpleData::Concatenation(_, _) => GarnishDataType::Concatenation,
172            SimpleData::Range(_, _) => GarnishDataType::Range,
173            SimpleData::Slice(_, _) => GarnishDataType::Slice,
174            SimpleData::Partial(_, _) => GarnishDataType::Partial,
175            SimpleData::List(_, _) => GarnishDataType::List,
176            SimpleData::StackFrame(_)
177            | SimpleData::Custom(_) => GarnishDataType::Custom,
178        }
179    }
180
181    pub fn is_unit(&self) -> bool {
182        match self {
183            SimpleData::Unit => true,
184            _ => false,
185        }
186    }
187
188    pub fn is_true(&self) -> bool {
189        match self {
190            SimpleData::True => true,
191            _ => false,
192        }
193    }
194
195    pub fn is_false(&self) -> bool {
196        match self {
197            SimpleData::False => true,
198            _ => false,
199        }
200    }
201
202    pub fn as_stack_frame(&self) -> DataCastResult<SimpleStackFrame> {
203        match self {
204            SimpleData::StackFrame(v) => Ok(*v),
205            _ => Err(DataError::from(format!("{:?} is not a StackFrame", self))),
206        }
207    }
208
209    pub fn as_custom(&self) -> DataCastResult<T> {
210        match self {
211            SimpleData::Custom(v) => Ok(v.clone()),
212            _ => Err(DataError::from(format!("{:?} is not a Custom", self))),
213        }
214    }
215
216    pub fn as_type(&self) -> DataCastResult<GarnishDataType> {
217        match self {
218            SimpleData::Type(v) => Ok(*v),
219            _ => Err(DataError::from(format!("{:?} is not a Number", self))),
220        }
221    }
222
223    pub fn as_number(&self) -> DataCastResult<SimpleNumber> {
224        match self {
225            SimpleData::Number(v) => Ok(*v),
226            _ => Err(DataError::from(format!("{:?} is not a Number", self))),
227        }
228    }
229
230    pub fn as_char(&self) -> DataCastResult<char> {
231        match self {
232            SimpleData::Char(v) => Ok(*v),
233            _ => Err(DataError::from(format!("{:?} is not a Char", self))),
234        }
235    }
236
237    pub fn as_byte(&self) -> DataCastResult<u8> {
238        match self {
239            SimpleData::Byte(v) => Ok(*v),
240            _ => Err(DataError::from(format!("{:?} is not a Byte", self))),
241        }
242    }
243
244    pub fn as_symbol(&self) -> DataCastResult<u64> {
245        match self {
246            SimpleData::Symbol(v) => Ok(*v),
247            _ => Err(DataError::from(format!("{:?} is not a Symbol", self))),
248        }
249    }
250    
251    pub fn as_symbol_list(&self) -> DataCastResult<Vec<u64>> {
252        match self { 
253            SimpleData::SymbolList(v) => Ok(v.clone()),
254            _ => Err(DataError::from(format!("{:?} is not a SymbolList", self))),
255        }
256    }
257
258    pub fn as_expression(&self) -> DataCastResult<usize> {
259        match self {
260            SimpleData::Expression(v) => Ok(*v),
261            _ => Err(DataError::from(format!("{:?} is not an Expression", self))),
262        }
263    }
264
265    pub fn as_external(&self) -> DataCastResult<usize> {
266        match self {
267            SimpleData::External(v) => Ok(*v),
268            _ => Err(DataError::from(format!("{:?} is not an External", self))),
269        }
270    }
271
272    pub fn as_char_list(&self) -> DataCastResult<String> {
273        match self {
274            SimpleData::CharList(v) => Ok(v.clone()),
275            _ => Err(DataError::from(format!("{:?} is not a CharList", self))),
276        }
277    }
278
279    pub fn as_byte_list(&self) -> DataCastResult<Vec<u8>> {
280        match self {
281            SimpleData::ByteList(v) => Ok(v.clone()),
282            _ => Err(DataError::from(format!("{:?} is not a ByteList", self))),
283        }
284    }
285
286    pub fn as_pair(&self) -> DataCastResult<(usize, usize)> {
287        match self {
288            SimpleData::Pair(l, r) => Ok((*l, *r)),
289            _ => Err(DataError::from(format!("{:?} is not a Pair", self))),
290        }
291    }
292
293    pub fn as_partial(&self) -> DataCastResult<(usize, usize)> {
294        match self {
295            SimpleData::Partial(l, r) => Ok((*l, *r)),
296            _ => Err(DataError::from(format!("{:?} is not a Partial", self))),
297        }
298    }
299
300    pub fn as_concatenation(&self) -> DataCastResult<(usize, usize)> {
301        match self {
302            SimpleData::Concatenation(l, r) => Ok((*l, *r)),
303            _ => Err(DataError::from(format!("{:?} is not a Concatenation", self))),
304        }
305    }
306
307    pub fn as_range(&self) -> DataCastResult<(usize, usize)> {
308        match self {
309            SimpleData::Range(s, e) => Ok((*s, *e)),
310            _ => Err(DataError::from(format!("{:?} is not a Range", self))),
311        }
312    }
313
314    pub fn as_slice(&self) -> DataCastResult<(usize, usize)> {
315        match self {
316            SimpleData::Slice(v, r) => Ok((*v, *r)),
317            _ => Err(DataError::from(format!("{:?} is not a Slice", self))),
318        }
319    }
320
321    pub fn as_list(&self) -> DataCastResult<(Vec<usize>, Vec<usize>)> {
322        match self {
323            SimpleData::List(v, a) => Ok((v.clone(), a.clone())),
324            _ => Err(DataError::from(format!("{:?} is not a List", self))),
325        }
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use crate::data::{SimpleDataNC, SimpleNumber};
332    use crate::{GarnishDataType, NoCustom};
333    use crate::data::stack_frame::SimpleStackFrame;
334
335    #[test]
336    fn get_data_type() {
337        assert_eq!(SimpleDataNC::Unit.get_data_type(), GarnishDataType::Unit);
338        assert_eq!(SimpleDataNC::True.get_data_type(), GarnishDataType::True);
339        assert_eq!(SimpleDataNC::False.get_data_type(), GarnishDataType::False);
340        assert_eq!(SimpleDataNC::Number(SimpleNumber::Integer(0)).get_data_type(), GarnishDataType::Number);
341        assert_eq!(SimpleDataNC::Char('a').get_data_type(), GarnishDataType::Char);
342        assert_eq!(SimpleDataNC::Byte(0).get_data_type(), GarnishDataType::Byte);
343        assert_eq!(SimpleDataNC::Symbol(0).get_data_type(), GarnishDataType::Symbol);
344        assert_eq!(SimpleDataNC::SymbolList(vec![1, 2, 3]).get_data_type(), GarnishDataType::SymbolList);
345        assert_eq!(SimpleDataNC::Expression(0).get_data_type(), GarnishDataType::Expression);
346        assert_eq!(SimpleDataNC::External(0).get_data_type(), GarnishDataType::External);
347        assert_eq!(SimpleDataNC::CharList(String::new()).get_data_type(), GarnishDataType::CharList);
348        assert_eq!(SimpleDataNC::ByteList(vec![]).get_data_type(), GarnishDataType::ByteList);
349        assert_eq!(SimpleDataNC::Pair(0, 0).get_data_type(), GarnishDataType::Pair);
350        assert_eq!(SimpleDataNC::Concatenation(0, 0).get_data_type(), GarnishDataType::Concatenation);
351        assert_eq!(SimpleDataNC::Range(0, 0).get_data_type(), GarnishDataType::Range);
352        assert_eq!(SimpleDataNC::Slice(0, 0).get_data_type(), GarnishDataType::Slice);
353        assert_eq!(SimpleDataNC::List(vec![], vec![]).get_data_type(), GarnishDataType::List);
354        assert_eq!(SimpleDataNC::StackFrame(SimpleStackFrame::new(0)).get_data_type(), GarnishDataType::Custom);
355        assert_eq!(SimpleDataNC::Custom(NoCustom {}).get_data_type(), GarnishDataType::Custom);
356    }
357
358    #[test]
359    fn is_unit() {
360        assert!(SimpleDataNC::Unit.is_unit());
361    }
362
363    #[test]
364    fn is_unit_not_unit() {
365        assert!(!SimpleDataNC::True.is_unit());
366    }
367
368    #[test]
369    fn is_true() {
370        assert!(SimpleDataNC::True.is_true());
371    }
372
373    #[test]
374    fn is_true_not_true() {
375        assert!(!SimpleDataNC::Unit.is_true());
376    }
377
378    #[test]
379    fn is_false() {
380        assert!(SimpleDataNC::False.is_false());
381    }
382
383    #[test]
384    fn is_false_not_false() {
385        assert!(!SimpleDataNC::Unit.is_false());
386    }
387
388    #[test]
389    fn is_custom() {
390        assert_eq!(SimpleDataNC::StackFrame(SimpleStackFrame::new(0))
391                       .as_stack_frame().unwrap(), SimpleStackFrame::new(0));
392    }
393
394    #[test]
395    fn is_stack_frame() {
396        assert_eq!(SimpleDataNC::Custom(NoCustom {}).as_custom().unwrap(), NoCustom {});
397    }
398
399    #[test]
400    fn is_custom_not_custom() {
401        assert!(SimpleDataNC::Unit.as_custom().is_err());
402    }
403
404    #[test]
405    fn is_type() {
406        assert_eq!(SimpleDataNC::Type(GarnishDataType::Unit).as_type().unwrap(), GarnishDataType::Unit);
407    }
408
409    #[test]
410    fn as_type_not_type() {
411        assert!(SimpleDataNC::Unit.as_type().is_err());
412    }
413
414    #[test]
415    fn as_number() {
416        assert_eq!(
417            SimpleDataNC::Number(SimpleNumber::Integer(10)).as_number().unwrap(),
418            SimpleNumber::Integer(10)
419        );
420    }
421
422    #[test]
423    fn as_number_not_number() {
424        assert!(SimpleDataNC::Unit.as_number().is_err());
425    }
426
427    #[test]
428    fn as_char() {
429        assert_eq!(SimpleDataNC::Char('a').as_char().unwrap(), 'a');
430    }
431
432    #[test]
433    fn as_char_not_char() {
434        assert!(SimpleDataNC::Unit.as_char().is_err());
435    }
436
437    #[test]
438    fn as_byte() {
439        assert_eq!(SimpleDataNC::Byte(10).as_byte().unwrap(), 10.into());
440    }
441
442    #[test]
443    fn as_byte_not_byte() {
444        assert!(SimpleDataNC::Unit.as_byte().is_err());
445    }
446
447    #[test]
448    fn as_symbol() {
449        assert_eq!(SimpleDataNC::Symbol(10).as_symbol().unwrap(), 10);
450    }
451
452    #[test]
453    fn as_symbol_not_symbol() {
454        assert!(SimpleDataNC::Unit.as_symbol().is_err());
455    }
456
457    #[test]
458    fn as_symbol_list() {
459        assert_eq!(SimpleDataNC::SymbolList(vec![10, 20]).as_symbol_list().unwrap(), vec![10, 20]);
460    }
461
462    #[test]
463    fn as_symbol_list_not_symbol_list() {
464        assert!(SimpleDataNC::Unit.as_symbol_list().is_err());
465    }
466
467    #[test]
468    fn as_expression() {
469        assert_eq!(SimpleDataNC::Expression(10).as_expression().unwrap(), 10);
470    }
471
472    #[test]
473    fn as_expression_not_expression() {
474        assert!(SimpleDataNC::Unit.as_expression().is_err());
475    }
476
477    #[test]
478    fn as_external() {
479        assert_eq!(SimpleDataNC::External(10).as_external().unwrap(), 10);
480    }
481
482    #[test]
483    fn as_external_not_external() {
484        assert!(SimpleDataNC::Unit.as_external().is_err());
485    }
486
487    #[test]
488    fn as_char_list() {
489        assert_eq!(SimpleDataNC::CharList(String::new()).as_char_list().unwrap(), "");
490    }
491
492    #[test]
493    fn as_char_list_not_char_list() {
494        assert!(SimpleDataNC::Unit.as_char_list().is_err());
495    }
496
497    #[test]
498    fn as_byte_list() {
499        assert_eq!(SimpleDataNC::ByteList(vec![10]).as_byte_list().unwrap(), vec![10]);
500    }
501
502    #[test]
503    fn as_byte_list_not_byte_list() {
504        assert!(SimpleDataNC::Unit.as_byte_list().is_err());
505    }
506
507    #[test]
508    fn as_pair() {
509        assert_eq!(SimpleDataNC::Pair(10, 20).as_pair().unwrap(), (10, 20));
510    }
511
512    #[test]
513    fn as_pair_not_pair() {
514        assert!(SimpleDataNC::Unit.as_pair().is_err());
515    }
516
517    #[test]
518    fn as_partial() {
519        assert_eq!(SimpleDataNC::Partial(10, 20).as_partial().unwrap(), (10, 20));
520    }
521
522    #[test]
523    fn as_partial_not_partial() {
524        assert!(SimpleDataNC::Unit.as_partial().is_err());
525    }
526
527    #[test]
528    fn as_concatenation() {
529        assert_eq!(SimpleDataNC::Concatenation(10, 20).as_concatenation().unwrap(), (10, 20));
530    }
531
532    #[test]
533    fn as_concatenation_not_concatenation() {
534        assert!(SimpleDataNC::Unit.as_concatenation().is_err());
535    }
536
537    #[test]
538    fn as_range() {
539        assert_eq!(SimpleDataNC::Range(10, 20).as_range().unwrap(), (10, 20));
540    }
541
542    #[test]
543    fn as_range_not_range() {
544        assert!(SimpleDataNC::Unit.as_range().is_err());
545    }
546
547    #[test]
548    fn as_slice() {
549        assert_eq!(SimpleDataNC::Slice(10, 20).as_slice().unwrap(), (10, 20));
550    }
551
552    #[test]
553    fn as_slice_not_slice() {
554        assert!(SimpleDataNC::Unit.as_slice().is_err());
555    }
556
557    #[test]
558    fn as_list() {
559        assert_eq!(
560            SimpleDataNC::List(vec![10, 20], vec![20, 10]).as_list().unwrap(),
561            (vec![10, 20], vec![20, 10])
562        );
563    }
564
565    #[test]
566    fn as_list_not_list() {
567        assert!(SimpleDataNC::Unit.as_list().is_err());
568    }
569}