mech_core/
value.rs

1use crate::matrix::Matrix;
2use crate::*;
3use crate::nodes::Matrix as Mat;
4use crate::{MechError, MechErrorKind, hash_str, nodes::Kind as NodeKind, nodes::*, humanize};
5use std::collections::HashMap;
6
7use na::{Vector3, DVector, Vector2, Vector4, RowDVector, Matrix1, Matrix3, Matrix4, RowVector3, RowVector4, RowVector2, DMatrix, Rotation3, Matrix2x3, Matrix3x2, Matrix6, Matrix2};
8use std::hash::{Hash, Hasher};
9use indexmap::set::IndexSet;
10use indexmap::map::*;
11use tabled::{
12  builder::Builder,
13  settings::{object::Rows,Panel, Span, Alignment, Modify, Style},
14  Tabled,
15};
16use paste::paste;
17use serde::ser::{Serialize, Serializer, SerializeStruct};
18use serde::de::{self, Deserialize, SeqAccess, Deserializer, MapAccess, Visitor};
19use std::fmt;
20use std::cell::RefCell;
21use std::rc::Rc;
22
23macro_rules! impl_as_type {
24  ($target_type:ty) => {
25    paste!{
26      pub fn [<as_ $target_type>](&self) -> Option<Ref<$target_type>> {
27        match self {
28          Value::U8(v) => Some(new_ref(*v.borrow() as $target_type)),
29          Value::U16(v) => Some(new_ref(*v.borrow() as $target_type)),
30          Value::U32(v) => Some(new_ref(*v.borrow() as $target_type)),
31          Value::U64(v) => Some(new_ref(*v.borrow() as $target_type)),
32          Value::U128(v) => Some(new_ref(*v.borrow() as $target_type)),
33          Value::I8(v) => Some(new_ref(*v.borrow() as $target_type)),
34          Value::I16(v) => Some(new_ref(*v.borrow() as $target_type)),
35          Value::I32(v) => Some(new_ref(*v.borrow() as $target_type)),
36          Value::I64(v) => Some(new_ref(*v.borrow() as $target_type)),
37          Value::I128(v) => Some(new_ref(*v.borrow() as $target_type)),
38          Value::F32(v) => Some(new_ref((*v.borrow()).0 as $target_type)),
39          Value::F64(v) => Some(new_ref((*v.borrow()).0 as $target_type)),
40          Value::MutableReference(val) => val.borrow().[<as_ $target_type>](),
41          _ => None,
42        }
43      }
44    }
45  };
46}
47
48// Value ----------------------------------------------------------------------
49
50#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
51pub enum ValueKind {
52  U8, U16, U32, U64, U128, I8, I16, I32, I64, I128, F32, F64, 
53  String, Bool, Matrix(Box<ValueKind>,Vec<usize>), Enum(u64), Set(Box<ValueKind>, usize), 
54  Map(Box<ValueKind>,Box<ValueKind>), Record(Vec<ValueKind>), Table(Vec<ValueKind>, usize), Tuple(Vec<ValueKind>), Id, Index, Reference(Box<ValueKind>), Atom(u64), Empty, Any
55}
56
57impl ValueKind {
58
59  pub fn deref_kind(&self) -> Option<ValueKind> {
60    match self {
61      ValueKind::Reference(x) => Some(*x.clone()),
62      _ => None,
63    }
64  }
65
66}
67
68impl std::fmt::Display for ValueKind {
69  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
70    match self {
71      ValueKind::U8 => write!(f, "u8"),
72      ValueKind::U16 => write!(f, "u16"),
73      ValueKind::U32 => write!(f, "u32"),
74      ValueKind::U64 => write!(f, "u64"),
75      ValueKind::U128 => write!(f, "u128"),
76      ValueKind::I8 => write!(f, "i8"),
77      ValueKind::I16 => write!(f, "i16"),
78      ValueKind::I32 => write!(f, "i32"),
79      ValueKind::I64 => write!(f, "i64"),
80      ValueKind::I128 => write!(f, "i128"),
81      ValueKind::F32 => write!(f, "f32"),
82      ValueKind::F64 => write!(f, "f64"),
83      ValueKind::String => write!(f, "string"),
84      ValueKind::Bool => write!(f, "bool"),
85      ValueKind::Matrix(x,s) => write!(f, "[{:?}]:{:?},{:?}",x,s[0],s[1]),
86      ValueKind::Enum(x) => write!(f, "{:?}",x),
87      ValueKind::Set(x,el) => write!(f, "{{{:?}}}:{}", x, el),
88      ValueKind::Map(x,y) => write!(f, "{{{:?}:{:?}}}",x,y),
89      ValueKind::Record(x) => write!(f, "{{{}}}",x.iter().map(|x| format!("{:?}",x)).collect::<Vec<String>>().join(",")),
90      ValueKind::Table(x,y) => write!(f, "{{{}}}:{}",x.iter().map(|x| format!("{:?}",x)).collect::<Vec<String>>().join(","),y),
91      ValueKind::Tuple(x) => write!(f, "({})",x.iter().map(|x| format!("{:?}",x)).collect::<Vec<String>>().join(",")),
92      ValueKind::Id => write!(f, "id"),
93      ValueKind::Index => write!(f, "ix"),
94      ValueKind::Reference(x) => write!(f, "{:?}",x),
95      ValueKind::Atom(x) => write!(f, "`{:?}",x),
96      ValueKind::Empty => write!(f, "_"),
97      ValueKind::Any => write!(f, "_"),
98    }
99  }
100}
101
102
103impl fmt::Debug for ValueKind {
104  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105    match self {
106      ValueKind::U8 => write!(f, "u8"),
107      ValueKind::U16 => write!(f, "u16"),
108      ValueKind::U32 => write!(f, "u32"),
109      ValueKind::U64 => write!(f, "u64"),
110      ValueKind::U128 => write!(f, "u128"),
111      ValueKind::I8 => write!(f, "i8"),
112      ValueKind::I16 => write!(f, "i16"),
113      ValueKind::I32 => write!(f, "i32"),
114      ValueKind::I64 => write!(f, "i64"),
115      ValueKind::I128 => write!(f, "i128"),
116      ValueKind::F32 => write!(f, "f32"),
117      ValueKind::F64 => write!(f, "f64"),
118      ValueKind::String => write!(f, "string"),
119      ValueKind::Bool => write!(f, "bool"),
120      ValueKind::Matrix(x,s) => {
121        let s = if s.len() == 2 { s.clone() } else if s.len() == 1 { vec![s[0], 1] } else { vec![0, 0] };
122        write!(f, "[{:?}]:{:?},{:?}",x,s[0],s[1]).clone()
123      }
124      ValueKind::Enum(x) => write!(f, "{:?}",x),
125      ValueKind::Set(x,el) => write!(f, "{{{:?}}}:{}", x, el),
126      ValueKind::Map(x,y) => write!(f, "{{{:?}:{:?}}}",x,y),
127      ValueKind::Record(x) => write!(f, "{{{}}}",x.iter().map(|x| format!("{:?}",x)).collect::<Vec<String>>().join(",")),
128      ValueKind::Table(x,y) => write!(f, "{{{}}}:{}",x.iter().map(|x| format!("{:?}",x)).collect::<Vec<String>>().join(","),y),
129      ValueKind::Tuple(x) => write!(f, "({})",x.iter().map(|x| format!("{:?}",x)).collect::<Vec<String>>().join(",")),
130      ValueKind::Id => write!(f, "id"),
131      ValueKind::Index => write!(f, "ix"),
132      ValueKind::Reference(x) => write!(f, "&{:?}",x),
133      ValueKind::Atom(x) => write!(f, "`{:?}",x),
134      ValueKind::Empty => write!(f, "_"),
135      ValueKind::Any => write!(f, "_"),
136    }
137  }
138}
139
140impl ValueKind {
141  pub fn is_compatible(k1: ValueKind, k2: ValueKind) -> bool {
142    match k1 {
143      ValueKind::Reference(x) => {
144        ValueKind::is_compatible(*x,k2)
145      }
146      ValueKind::Matrix(x,_) => {
147        *x == k2
148      }
149      x => x == k2,
150    }
151  }
152}
153
154#[derive(Clone, Debug, PartialEq, Eq)]
155pub enum Value {
156  U8(Ref<u8>),
157  U16(Ref<u16>),
158  U32(Ref<u32>),
159  U64(Ref<u64>),
160  U128(Ref<u128>),
161  I8(Ref<i8>),
162  I16(Ref<i16>),
163  I32(Ref<i32>),
164  I64(Ref<i64>),
165  I128(Ref<i128>),
166  F32(Ref<F32>),
167  F64(Ref<F64>),
168  String(Ref<String>),
169  Bool(Ref<bool>),
170  Atom(u64),
171  MatrixIndex(Matrix<usize>),
172  MatrixBool(Matrix<bool>),
173  MatrixU8(Matrix<u8>),
174  MatrixU16(Matrix<u16>),
175  MatrixU32(Matrix<u32>),
176  MatrixU64(Matrix<u64>),
177  MatrixU128(Matrix<u128>),
178  MatrixI8(Matrix<i8>),
179  MatrixI16(Matrix<i16>),
180  MatrixI32(Matrix<i32>),
181  MatrixI64(Matrix<i64>),
182  MatrixI128(Matrix<i128>),
183  MatrixF32(Matrix<F32>),
184  MatrixF64(Matrix<F64>),
185  MatrixString(Matrix<String>),
186  MatrixValue(Matrix<Value>),
187  Set(MechSet),
188  Map(MechMap),
189  Record(MechRecord),
190  Table(MechTable),
191  Tuple(MechTuple),
192  Enum(Box<MechEnum>),
193  Id(u64),
194  Index(Ref<usize>),
195  MutableReference(MutableReference),
196  Kind(ValueKind),
197  IndexAll,
198  Empty
199}
200
201impl fmt::Display for Value {
202  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
203    self.pretty_print().fmt(f)
204  }
205}
206
207impl Hash for Value {
208  fn hash<H: Hasher>(&self, state: &mut H) {
209    match self {
210      Value::Id(x)   => x.hash(state),
211      Value::Kind(x) => x.hash(state),
212      Value::U8(x)   => x.borrow().hash(state),
213      Value::U16(x)  => x.borrow().hash(state),
214      Value::U32(x)  => x.borrow().hash(state),
215      Value::U64(x)  => x.borrow().hash(state),
216      Value::U128(x) => x.borrow().hash(state),
217      Value::I8(x)   => x.borrow().hash(state),
218      Value::I16(x)  => x.borrow().hash(state),
219      Value::I32(x)  => x.borrow().hash(state),
220      Value::I64(x)  => x.borrow().hash(state),
221      Value::I128(x) => x.borrow().hash(state),
222      Value::F32(x)  => x.borrow().hash(state),
223      Value::F64(x)  => x.borrow().hash(state),
224      Value::Index(x)=> x.borrow().hash(state),
225      Value::Bool(x) => x.borrow().hash(state),
226      Value::Atom(x) => x.hash(state),
227      Value::Set(x)  => x.hash(state),
228      Value::Map(x)  => x.hash(state),
229      Value::Table(x) => x.hash(state),
230      Value::Tuple(x) => x.hash(state),
231      Value::Record(x) => x.hash(state),
232      Value::Enum(x) => x.hash(state),
233      Value::String(x) => x.borrow().hash(state),
234      Value::MatrixBool(x) => x.hash(state),
235      Value::MatrixIndex(x) => x.hash(state),
236      Value::MatrixU8(x)   => x.hash(state),
237      Value::MatrixU16(x)  => x.hash(state),
238      Value::MatrixU32(x)  => x.hash(state),
239      Value::MatrixU64(x)  => x.hash(state),
240      Value::MatrixU128(x) => x.hash(state),
241      Value::MatrixI8(x)   => x.hash(state),
242      Value::MatrixI16(x)  => x.hash(state),
243      Value::MatrixI32(x)  => x.hash(state),
244      Value::MatrixI64(x)  => x.hash(state),
245      Value::MatrixI128(x) => x.hash(state),
246      Value::MatrixF32(x)  => x.hash(state),
247      Value::MatrixF64(x)  => x.hash(state),
248      Value::MatrixString(x) => x.hash(state),
249      Value::MatrixValue(x)  => x.hash(state),
250      Value::MutableReference(x) => x.borrow().hash(state),
251      Value::Empty => Value::Empty.hash(state),
252      Value::IndexAll => Value::IndexAll.hash(state),
253    }
254  }
255}
256
257impl Value {
258
259  pub fn size_of(&self) -> usize {
260    match self {
261      Value::U8(x) => 1,
262      Value::U16(x) => 2,
263      Value::U32(x) => 4,
264      Value::U64(x) => 8,
265      Value::U128(x) => 16,
266      Value::I8(x) => 1,
267      Value::I16(x) => 2,
268      Value::I32(x) => 4,
269      Value::I64(x) => 8,
270      Value::I128(x) => 16,
271      Value::F32(x) => 4,
272      Value::F64(x) => 8,
273      Value::Bool(x) => 1,
274      Value::MatrixIndex(x) =>x.size_of(),
275      Value::MatrixBool(x) =>x.size_of(),
276      Value::MatrixU8(x)   => x.size_of(),
277      Value::MatrixU16(x)  => x.size_of(),
278      Value::MatrixU32(x)  => x.size_of(),
279      Value::MatrixU64(x)  => x.size_of(),
280      Value::MatrixU128(x) => x.size_of(),
281      Value::MatrixI8(x)   => x.size_of(),
282      Value::MatrixI16(x)  => x.size_of(),
283      Value::MatrixI32(x)  => x.size_of(),
284      Value::MatrixI64(x)  => x.size_of(),
285      Value::MatrixI128(x) => x.size_of(),
286      Value::MatrixF32(x)  => x.size_of(),
287      Value::MatrixF64(x)  => x.size_of(),
288      Value::MatrixValue(x)  => x.size_of(),
289      Value::MatrixString(x) => x.size_of(),
290      Value::String(x) => x.borrow().len(),
291      Value::Atom(x) => 8,
292      Value::Set(x) => x.size_of(),
293      Value::Map(x) => x.size_of(),
294      Value::Table(x) => x.size_of(),
295      Value::Record(x) => x.size_of(),
296      Value::Tuple(x) => x.size_of(),
297      Value::Enum(x) => x.size_of(),
298      Value::MutableReference(x) => x.borrow().size_of(),
299      Value::Id(_) => 8,
300      Value::Index(x) => 8,
301      Value::Kind(_) => 0, // Kind is not a value, so it has no size
302      Value::Empty => 0,
303      Value::IndexAll => 0, // IndexAll is a special value, so it has no size
304    }
305  }
306
307  pub fn to_html(&self) -> String {
308    match self {
309      Value::U8(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
310      Value::U16(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
311      Value::U32(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
312      Value::U64(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
313      Value::I8(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
314      Value::I128(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
315      Value::I16(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
316      Value::I32(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
317      Value::I64(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
318      Value::I128(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
319      Value::F32(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
320      Value::F64(n) => format!("<span class='mech-number'>{}</span>", n.borrow()),
321      Value::String(s) => format!("<span class='mech-string'>\"{}\"</span>", s.borrow()),
322      Value::Bool(b) => format!("<span class='mech-bool'>{}</span>", b.borrow()),
323      Value::MatrixU8(m) => m.to_html(),
324      Value::MatrixU16(m) => m.to_html(),
325      Value::MatrixU32(m) => m.to_html(),
326      Value::MatrixU64(m) => m.to_html(),
327      Value::MatrixU128(m) => m.to_html(),
328      Value::MatrixI8(m) => m.to_html(),
329      Value::MatrixI16(m) => m.to_html(),
330      Value::MatrixI32(m) => m.to_html(),
331      Value::MatrixI64(m) => m.to_html(),
332      Value::MatrixI128(m) => m.to_html(),
333      Value::MatrixF64(m) => m.to_html(),
334      Value::MatrixF32(m) => m.to_html(),
335      Value::MatrixIndex(m) => m.to_html(),
336      Value::MatrixBool(m) => m.to_html(),
337      Value::MatrixString(m) => m.to_html(),
338      Value::MatrixValue(m) => m.to_html(),
339      Value::MutableReference(m) => {
340        let inner = m.borrow();
341        format!("<span class='mech-reference'>{}</span>", inner.to_html())
342      },
343      _ => todo!(),
344    }
345  }
346
347  pub fn pretty_print(&self) -> String {
348    let mut builder = Builder::default();
349    match self {
350      Value::U8(x)   => {builder.push_record(vec![format!("{}",x.borrow())]);},
351      Value::U16(x)  => {builder.push_record(vec![format!("{}",x.borrow())]);},
352      Value::U32(x)  => {builder.push_record(vec![format!("{}",x.borrow())]);},
353      Value::U64(x)  => {builder.push_record(vec![format!("{}",x.borrow())]);},
354      Value::U128(x) => {builder.push_record(vec![format!("{}",x.borrow())]);},
355      Value::I8(x)   => {builder.push_record(vec![format!("{}",x.borrow())]);},
356      Value::I16(x)  => {builder.push_record(vec![format!("{}",x.borrow())]);},
357      Value::I32(x)  => {builder.push_record(vec![format!("{}",x.borrow())]);},
358      Value::I64(x)  => {builder.push_record(vec![format!("{}",x.borrow())]);},
359      Value::I128(x) => {builder.push_record(vec![format!("{}",x.borrow())]);},
360      Value::F32(x)  => {builder.push_record(vec![format!("{}",x.borrow().0)]);},
361      Value::F64(x)  => {builder.push_record(vec![format!("{}",x.borrow().0)]);},
362      Value::Bool(x) => {builder.push_record(vec![format!("{}",x.borrow())]);},
363      Value::Index(x)  => {builder.push_record(vec![format!("{}",x.borrow())]);},
364      Value::Atom(x) => {builder.push_record(vec![format!("{}",x)]);},
365      Value::Set(x)  => {return x.pretty_print();}
366      Value::Map(x)  => {return x.pretty_print();}
367      Value::String(x) => {return format!("\"{}\"",x.borrow().clone());},
368      Value::Table(x)  => {return x.pretty_print();},
369      Value::Tuple(x)  => {return x.pretty_print();},
370      Value::Record(x) => {return x.pretty_print();},
371      Value::Enum(x) => {return x.pretty_print();},
372      Value::MatrixIndex(x) => {return x.pretty_print();}
373      Value::MatrixBool(x) => {return x.pretty_print();}
374      Value::MatrixU8(x)   => {return x.pretty_print();},
375      Value::MatrixU16(x)  => {return x.pretty_print();},
376      Value::MatrixU32(x)  => {return x.pretty_print();},
377      Value::MatrixU64(x)  => {return x.pretty_print();},
378      Value::MatrixU128(x) => {return x.pretty_print();},
379      Value::MatrixI8(x)   => {return x.pretty_print();},
380      Value::MatrixI16(x)  => {return x.pretty_print();},
381      Value::MatrixI32(x)  => {return x.pretty_print();},
382      Value::MatrixI64(x)  => {return x.pretty_print();},
383      Value::MatrixI128(x) => {return x.pretty_print();},
384      Value::MatrixF32(x)  => {return x.pretty_print();},
385      Value::MatrixF64(x)  => {return x.pretty_print();},
386      Value::MatrixValue(x)  => {return x.pretty_print();},
387      Value::MatrixString(x)  => {return x.pretty_print();},
388      Value::MutableReference(x) => {return x.borrow().pretty_print();},
389      Value::Empty => builder.push_record(vec!["_"]),
390      Value::IndexAll => builder.push_record(vec![":"]),
391      Value::Id(x) => builder.push_record(vec![format!("{:?}",humanize(x))]),
392      Value::Kind(x) => builder.push_record(vec![format!("{:?}",x)]),
393    };
394    let value_style = Style::empty()
395      .top(' ')
396      .left(' ')
397      .right(' ')
398      .bottom(' ')
399      .vertical(' ')
400      .intersection_bottom(' ')
401      .corner_top_left(' ')
402      .corner_top_right(' ')
403      .corner_bottom_left(' ')
404      .corner_bottom_right(' ');
405    let mut table = builder.build();
406    table.with(value_style);
407    format!("{table}")
408  }
409
410  pub fn shape(&self) -> Vec<usize> {
411    match self {
412      Value::U8(x) => vec![1,1],
413      Value::U16(x) => vec![1,1],
414      Value::U32(x) => vec![1,1],
415      Value::U64(x) => vec![1,1],
416      Value::U128(x) => vec![1,1],
417      Value::I8(x) => vec![1,1],
418      Value::I16(x) => vec![1,1],
419      Value::I32(x) => vec![1,1],
420      Value::I64(x) => vec![1,1],
421      Value::I128(x) => vec![1,1],
422      Value::F32(x) => vec![1,1],
423      Value::F64(x) => vec![1,1],
424      Value::Index(x) => vec![1,1],
425      Value::String(x) => vec![1,1],
426      Value::Bool(x) => vec![1,1],
427      Value::Atom(x) => vec![1,1],
428      Value::MatrixIndex(x) => x.shape(),
429      Value::MatrixBool(x) => x.shape(),
430      Value::MatrixU8(x) => x.shape(),
431      Value::MatrixU16(x) => x.shape(),
432      Value::MatrixU32(x) => x.shape(),
433      Value::MatrixU64(x) => x.shape(),
434      Value::MatrixU128(x) => x.shape(),
435      Value::MatrixI8(x) => x.shape(),
436      Value::MatrixI16(x) => x.shape(),
437      Value::MatrixI32(x) => x.shape(),
438      Value::MatrixI64(x) => x.shape(),
439      Value::MatrixI128(x) => x.shape(),
440      Value::MatrixF32(x) => x.shape(),
441      Value::MatrixF64(x) => x.shape(),
442      Value::MatrixString(x) => x.shape(),
443      Value::MatrixValue(x) => x.shape(),
444      Value::Enum(x) => vec![1,1],
445      Value::Table(x) => x.shape(),
446      Value::Set(x) => vec![1,x.set.len()],
447      Value::Map(x) => vec![1,x.map.len()],
448      Value::Record(x) => x.shape(),
449      Value::Tuple(x) => vec![1,x.size()],
450      Value::MutableReference(x) => x.borrow().shape(),
451      Value::Empty => vec![0,0],
452      Value::IndexAll => vec![0,0],
453      Value::Kind(_) => vec![0,0],
454      Value::Id(x) => vec![0,0],
455    }
456  }
457
458  pub fn kind(&self) -> ValueKind {
459    match self {
460      Value::U8(_) => ValueKind::U8,
461      Value::U16(_) => ValueKind::U16,
462      Value::U32(_) => ValueKind::U32,
463      Value::U64(_) => ValueKind::U64,
464      Value::U128(_) => ValueKind::U128,
465      Value::I8(_) => ValueKind::I8,
466      Value::I16(_) => ValueKind::I16,
467      Value::I32(_) => ValueKind::I32,
468      Value::I64(_) => ValueKind::I64,
469      Value::I128(_) => ValueKind::I128,
470      Value::F32(_) => ValueKind::F32,
471      Value::F64(_) => ValueKind::F64,
472      Value::String(_) => ValueKind::String,
473      Value::Bool(_) => ValueKind::Bool,
474      Value::Atom(x) => ValueKind::Atom(*x),
475      Value::MatrixIndex(x) => ValueKind::Matrix(Box::new(ValueKind::Index),x.shape()),
476      Value::MatrixBool(x) => ValueKind::Matrix(Box::new(ValueKind::Bool),x.shape()),
477      Value::MatrixU8(x) => ValueKind::Matrix(Box::new(ValueKind::U8),x.shape()),
478      Value::MatrixU16(x) => ValueKind::Matrix(Box::new(ValueKind::U16),x.shape()),
479      Value::MatrixU32(x) => ValueKind::Matrix(Box::new(ValueKind::U32),x.shape()),
480      Value::MatrixU64(x) => ValueKind::Matrix(Box::new(ValueKind::U64),x.shape()),
481      Value::MatrixU128(x) => ValueKind::Matrix(Box::new(ValueKind::U128),x.shape()),
482      Value::MatrixI8(x) => ValueKind::Matrix(Box::new(ValueKind::I8),x.shape()),
483      Value::MatrixI16(x) => ValueKind::Matrix(Box::new(ValueKind::I16),x.shape()),
484      Value::MatrixI32(x) => ValueKind::Matrix(Box::new(ValueKind::I32),x.shape()),
485      Value::MatrixI64(x) => ValueKind::Matrix(Box::new(ValueKind::I64),x.shape()),
486      Value::MatrixI128(x) => ValueKind::Matrix(Box::new(ValueKind::U128,),x.shape()),
487      Value::MatrixF32(x) => ValueKind::Matrix(Box::new(ValueKind::F32),x.shape()),
488      Value::MatrixF64(x) => ValueKind::Matrix(Box::new(ValueKind::F64),x.shape()),
489      Value::MatrixString(x) => ValueKind::Matrix(Box::new(ValueKind::String),x.shape()),
490      Value::MatrixValue(x) => ValueKind::Matrix(Box::new(ValueKind::Any),x.shape()),
491      Value::Table(x) => x.kind(),
492      Value::Set(x) => x.kind(),
493      Value::Map(x) => x.kind(),
494      Value::Record(x) => x.kind(),
495      Value::Tuple(x) => x.kind(),
496      Value::Enum(x) => x.kind(),
497      Value::MutableReference(x) => ValueKind::Reference(Box::new(x.borrow().kind())),
498      Value::Empty => ValueKind::Empty,
499      Value::IndexAll => ValueKind::Empty,
500      Value::Id(x) => ValueKind::Id,
501      Value::Index(x) => ValueKind::Index,
502      Value::Kind(x) => x.clone(),
503    }
504  }
505
506  pub fn is_matrix(&self) -> bool {
507    match self {
508      Value::MatrixIndex(_) | Value::MatrixBool(_) | Value::MatrixU8(_) | 
509      Value::MatrixU16(_) | Value::MatrixU32(_) | Value::MatrixU64(_) | 
510      Value::MatrixU128(_) | Value::MatrixI8(_) | Value::MatrixI16(_) | 
511      Value::MatrixI32(_) | Value::MatrixI64(_) | Value::MatrixI128(_) | 
512      Value::MatrixF32(_) | Value::MatrixF64(_) | Value::MatrixString(_) |
513      Value::MatrixValue(_) => true,
514      _ => false,
515    }
516  }
517
518  pub fn is_scalar(&self) -> bool {
519    match self {
520      Value::U8(_) | Value::U16(_) | Value::U32(_) | 
521      Value::U64(_) | Value::U128(_) | Value::I8(_) | 
522      Value::I16(_) | Value::I32(_) | Value::I64(_) | 
523      Value::I128(_) | Value::F32(_) | Value::F64(_) | 
524      Value::Bool(_) | Value::String(_) | 
525      Value::Atom(_) | Value::Index(_) => true,
526      _ => false,
527    }
528  }
529
530  pub fn as_bool(&self) -> Option<Ref<bool>> {if let Value::Bool(v) = self { Some(v.clone()) } else if let Value::MutableReference(val) = self { val.borrow().as_bool() } else { None }}
531  
532  impl_as_type!(i8);
533  impl_as_type!(i16);
534  impl_as_type!(i32);
535  impl_as_type!(i64);
536  impl_as_type!(i128);
537  impl_as_type!(u8);
538  impl_as_type!(u16);
539  impl_as_type!(u32);
540  impl_as_type!(u64);
541  impl_as_type!(u128);
542
543  pub fn as_string(&self) -> Option<Ref<String>> {
544    match self {
545      Value::String(v) => Some(v.clone()),
546      Value::U8(v) => Some(new_ref(v.borrow().to_string())),
547      Value::U16(v) => Some(new_ref(v.borrow().to_string())),
548      Value::U32(v) => Some(new_ref(v.borrow().to_string())),
549      Value::U64(v) => Some(new_ref(v.borrow().to_string())),
550      Value::U128(v) => Some(new_ref(v.borrow().to_string())),
551      Value::I8(v) => Some(new_ref(v.borrow().to_string())),
552      Value::I16(v) => Some(new_ref(v.borrow().to_string())),
553      Value::I32(v) => Some(new_ref(v.borrow().to_string())),
554      Value::I64(v) => Some(new_ref(v.borrow().to_string())),
555      Value::I128(v) => Some(new_ref(v.borrow().to_string())),
556      Value::F32(v) => Some(new_ref(format!("{}", v.borrow().0))),
557      Value::F64(v) => Some(new_ref(format!("{}", v.borrow().0))),
558      Value::Bool(v) => Some(new_ref(format!("{}", v.borrow()))),
559      Value::MutableReference(val) => val.borrow().as_string(),
560      _ => None,
561    }
562  }
563
564  pub fn as_f32(&self) -> Option<Ref<F32>> {
565    match self {
566      Value::U8(v) => Some(new_ref(F32::new(*v.borrow() as f32))),
567      Value::U16(v) => Some(new_ref(F32::new(*v.borrow() as f32))),
568      Value::U32(v) => Some(new_ref(F32::new(*v.borrow() as f32))),
569      Value::U64(v) => Some(new_ref(F32::new(*v.borrow() as f32))),
570      Value::U128(v) => Some(new_ref(F32::new(*v.borrow() as f32))),
571      Value::I8(v) => Some(new_ref(F32::new(*v.borrow() as f32))),
572      Value::I16(v) => Some(new_ref(F32::new(*v.borrow() as f32))),
573      Value::I32(v) => Some(new_ref(F32::new(*v.borrow() as f32))),
574      Value::I64(v) => Some(new_ref(F32::new(*v.borrow() as f32))),
575      Value::I128(v) => Some(new_ref(F32::new(*v.borrow() as f32))),
576      Value::F32(v) => Some(new_ref(F32::new((*v.borrow()).0 as f32))),
577      Value::F64(v) => Some(new_ref(F32::new((*v.borrow()).0 as f32))),
578      Value::MutableReference(val) => val.borrow().as_f32(),
579      _ => None,
580    }
581  }
582
583  pub fn as_f64(&self) -> Option<Ref<F64>> {
584    match self {
585      Value::U8(v) => Some(new_ref(F64::new(*v.borrow() as f64))),
586      Value::U16(v) => Some(new_ref(F64::new(*v.borrow() as f64))),
587      Value::U32(v) => Some(new_ref(F64::new(*v.borrow() as f64))),
588      Value::U64(v) => Some(new_ref(F64::new(*v.borrow() as f64))),
589      Value::U128(v) => Some(new_ref(F64::new(*v.borrow() as f64))),
590      Value::I8(v) => Some(new_ref(F64::new(*v.borrow() as f64))),
591      Value::I16(v) => Some(new_ref(F64::new(*v.borrow() as f64))),
592      Value::I32(v) => Some(new_ref(F64::new(*v.borrow() as f64))),
593      Value::I64(v) => Some(new_ref(F64::new(*v.borrow() as f64))),
594      Value::I128(v) => Some(new_ref(F64::new(*v.borrow() as f64))),
595      Value::F64(v) => Some(new_ref(F64::new((*v.borrow()).0 as f64))),
596      Value::F64(v) => Some(new_ref(F64::new((*v.borrow()).0 as f64))),
597      Value::MutableReference(val) => val.borrow().as_f64(),
598      _ => None,
599    }
600  }
601
602  pub fn as_vecbool(&self)   -> Option<Vec<bool>>  {if let Value::MatrixBool(v)  = self { Some(v.as_vec()) } else if let Value::Bool(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_vecbool()  } else { None }}
603  pub fn as_vecf64(&self)   -> Option<Vec<F64>>  {if let Value::MatrixF64(v)  = self { Some(v.as_vec()) } else if let Value::F64(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_vecf64()  } else { None }}
604  pub fn as_vecf32(&self)   -> Option<Vec<F32>>  {if let Value::MatrixF32(v)  = self { Some(v.as_vec()) } else if let Value::F32(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_vecf32()  } else { None }}
605
606  pub fn as_vecu8(&self)   -> Option<Vec<u8>>  {if let Value::MatrixU8(v)  = self { Some(v.as_vec()) } else if let Value::U8(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_vecu8()  } else { None }}
607  pub fn as_vecu16(&self)   -> Option<Vec<u16>>  {if let Value::MatrixU16(v)  = self { Some(v.as_vec()) } else if let Value::U16(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_vecu16()  } else { None }}
608  pub fn as_vecu32(&self)   -> Option<Vec<u32>>  {if let Value::MatrixU32(v)  = self { Some(v.as_vec()) } else if let Value::U32(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_vecu32()  } else { None }}
609  pub fn as_vecu64(&self)   -> Option<Vec<u64>>  {if let Value::MatrixU64(v)  = self { Some(v.as_vec()) } else if let Value::U64(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_vecu64()  } else { None }}
610  pub fn as_vecu128(&self)   -> Option<Vec<u128>>  {if let Value::MatrixU128(v)  = self { Some(v.as_vec()) } else if let Value::U128(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_vecu128()  } else { None }}
611
612  pub fn as_veci8(&self)   -> Option<Vec<i8>>  {if let Value::MatrixI8(v)  = self { Some(v.as_vec()) } else if let Value::I8(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_veci8()  } else { None }}
613  pub fn as_veci16(&self)   -> Option<Vec<i16>>  {if let Value::MatrixI16(v)  = self { Some(v.as_vec()) } else if let Value::I16(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_veci16()  } else { None }}
614  pub fn as_veci32(&self)   -> Option<Vec<i32>>  {if let Value::MatrixI32(v)  = self { Some(v.as_vec()) } else if let Value::I32(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_veci32()  } else { None }}
615  pub fn as_veci64(&self)   -> Option<Vec<i64>>  {if let Value::MatrixI64(v)  = self { Some(v.as_vec()) } else if let Value::I64(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_veci64()  } else { None }}
616  pub fn as_veci128(&self)   -> Option<Vec<i128>>  {if let Value::MatrixI128(v)  = self { Some(v.as_vec()) } else if let Value::I128(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_veci128()  } else { None }}
617
618  pub fn as_vecstring(&self)   -> Option<Vec<String>>  {if let Value::MatrixString(v)  = self { Some(v.as_vec()) } else if let Value::String(v) = self { Some(vec![v.borrow().clone()]) } else if let Value::MutableReference(val) = self { val.borrow().as_vecstring()  } else { None }}
619
620
621  pub fn as_vecusize(&self) -> Option<Vec<usize>> {
622    match self {
623      Value::MatrixIndex(v) => Some(v.as_vec()),
624      Value::MatrixI64(v) => Some(v.as_vec().iter().map(|x| *x as usize).collect::<Vec<usize>>()),
625      Value::MatrixF64(v) => Some(v.as_vec().iter().map(|x| (*x).0 as usize).collect::<Vec<usize>>()),
626      Value::MutableReference(x) => x.borrow().as_vecusize(),
627      Value::MatrixBool(_) => None,
628      Value::Bool(_) => None,
629      _ => todo!(),
630    }
631  }
632
633  pub fn as_index(&self) -> MResult<Value> {
634    match self.as_usize() {      
635      Some(ix) => Ok(Value::Index(new_ref(ix))),
636      None => match self.as_vecusize() {
637        Some(x) => {
638          let shape = self.shape();
639          let out = Value::MatrixIndex(usize::to_matrix(x, shape[0] * shape[1],1 ));
640          Ok(out)
641        },
642        None => match self.as_vecbool() {
643          Some(x) => {
644            let shape = self.shape();
645            let out = match (shape[0], shape[1]) {
646              (1,1) => Value::Bool(new_ref(x[0])),
647              (1,n) => Value::MatrixBool(Matrix::DVector(new_ref(DVector::from_vec(x)))),
648              (m,1) => Value::MatrixBool(Matrix::DVector(new_ref(DVector::from_vec(x)))),
649              (m,n) => Value::MatrixBool(Matrix::DVector(new_ref(DVector::from_vec(x)))),
650            };
651            Ok(out)
652          }
653          None => match self.as_bool() {
654            Some(x) => Ok(Value::Bool(x)),
655            None => Err(MechError{file: file!().to_string(), tokens: vec![], msg: "".to_string(), id: line!(), kind: MechErrorKind::UnhandledIndexKind}),
656          }
657        }
658      }
659    }
660  }
661
662  pub fn as_usize(&self) -> Option<usize> {
663    match self {      
664      Value::Index(v) => Some(*v.borrow()),
665      Value::U8(v) => Some(*v.borrow() as usize),
666      Value::U16(v) => Some(*v.borrow() as usize),
667      Value::U32(v) => Some(*v.borrow() as usize),
668      Value::U64(v) => Some(*v.borrow() as usize),
669      Value::U128(v) => Some(*v.borrow() as usize),
670      Value::I8(v) => Some(*v.borrow() as usize),
671      Value::I16(v) => Some(*v.borrow() as usize),
672      Value::I32(v) => Some(*v.borrow() as usize),
673      Value::I64(v) => Some(*v.borrow() as usize),
674      Value::I128(v) => Some(*v.borrow() as usize),
675      Value::F32(v) => Some((*v.borrow()).0 as usize),
676      Value::F64(v) => Some((*v.borrow()).0 as usize),
677      Value::Id(v) => Some(*v as usize),
678      Value::MutableReference(v) => v.borrow().as_usize(),
679      _ => None,
680    }
681  }
682
683}
684
685pub trait ToIndex {
686  fn to_index(&self) -> Value;
687}
688
689impl ToIndex for Ref<Vec<i64>> { fn to_index(&self) -> Value { (*self.borrow()).iter().map(|x| *x as usize).collect::<Vec<usize>>().to_value() } }
690
691pub trait ToValue {
692  fn to_value(&self) -> Value;
693}
694
695impl ToValue for Vec<usize> {
696  fn to_value(&self) -> Value {
697    match self.len() {
698      1 => Value::Index(new_ref(self[0].clone())),
699      //2 => Value::MatrixIndex(Matrix::RowVector2(new_ref(RowVector2::from_vec(self.clone())))),
700      //3 => Value::MatrixIndex(Matrix::RowVector3(new_ref(RowVector3::from_vec(self.clone())))),
701      //4 => Value::MatrixIndex(Matrix::RowVector4(new_ref(RowVector4::from_vec(self.clone())))),
702      n => Value::MatrixIndex(Matrix::DVector(new_ref(DVector::from_vec(self.clone())))),
703    }
704  }
705}
706
707impl ToValue for Ref<usize> { fn to_value(&self) -> Value { Value::Index(self.clone()) } }
708impl ToValue for Ref<u8>    { fn to_value(&self) -> Value { Value::U8(self.clone())    } }
709impl ToValue for Ref<u16>   { fn to_value(&self) -> Value { Value::U16(self.clone())   } }
710impl ToValue for Ref<u32>   { fn to_value(&self) -> Value { Value::U32(self.clone())   } }
711impl ToValue for Ref<u64>   { fn to_value(&self) -> Value { Value::U64(self.clone())   } }
712impl ToValue for Ref<u128>  { fn to_value(&self) -> Value { Value::U128(self.clone())  } }
713impl ToValue for Ref<i8>    { fn to_value(&self) -> Value { Value::I8(self.clone())    } }
714impl ToValue for Ref<i16>   { fn to_value(&self) -> Value { Value::I16(self.clone())   } }
715impl ToValue for Ref<i32>   { fn to_value(&self) -> Value { Value::I32(self.clone())   } }
716impl ToValue for Ref<i64>   { fn to_value(&self) -> Value { Value::I64(self.clone())   } }
717impl ToValue for Ref<i128>  { fn to_value(&self) -> Value { Value::I128(self.clone())  } }
718impl ToValue for Ref<F32>   { fn to_value(&self) -> Value { Value::F32(self.clone())   } }
719impl ToValue for Ref<F64>   { fn to_value(&self) -> Value { Value::F64(self.clone())   } }
720impl ToValue for Ref<bool>  { fn to_value(&self) -> Value { Value::Bool(self.clone())  } }
721impl ToValue for Ref<String>  { fn to_value(&self) -> Value { Value::String(self.clone())  } }
722
723macro_rules! to_value_matrix {
724  ($($nd_matrix_kind:ident, $matrix_kind:ident, $base_type:ty),+ $(,)?) => {
725    $(
726      impl ToValue for Ref<$nd_matrix_kind<$base_type>> {
727        fn to_value(&self) -> Value {
728          Value::$matrix_kind(Matrix::<$base_type>::$nd_matrix_kind(self.clone()))
729        }
730      }
731    )+
732  };}
733
734macro_rules! impl_to_value_matrix {
735  ($matrix_kind:ident) => {
736    to_value_matrix!(
737      $matrix_kind, MatrixIndex,  usize,
738      $matrix_kind, MatrixBool,   bool,
739      $matrix_kind, MatrixI8,     i8,
740      $matrix_kind, MatrixI16,    i16,
741      $matrix_kind, MatrixI32,    i32,
742      $matrix_kind, MatrixI64,    i64,
743      $matrix_kind, MatrixI128,   i128,
744      $matrix_kind, MatrixU8,     u8,
745      $matrix_kind, MatrixU16,    u16,
746      $matrix_kind, MatrixU32,    u32,
747      $matrix_kind, MatrixU64,    u64,
748      $matrix_kind, MatrixU128,   u128,
749      $matrix_kind, MatrixF32,    F32,
750      $matrix_kind, MatrixF64,    F64,
751      $matrix_kind, MatrixString, String,
752    );
753  }
754}
755
756impl_to_value_matrix!(Matrix2x3);
757impl_to_value_matrix!(Matrix3x2);
758impl_to_value_matrix!(Matrix1);
759impl_to_value_matrix!(Matrix2);
760impl_to_value_matrix!(Matrix3);
761impl_to_value_matrix!(Matrix4);
762impl_to_value_matrix!(Vector2);
763impl_to_value_matrix!(Vector3);
764impl_to_value_matrix!(Vector4);
765impl_to_value_matrix!(RowVector2);
766impl_to_value_matrix!(RowVector3);
767impl_to_value_matrix!(RowVector4);
768impl_to_value_matrix!(RowDVector);
769impl_to_value_matrix!(DVector);
770impl_to_value_matrix!(DMatrix);
771
772// Set --------------------------------------------------------------------------
773
774#[derive(Clone, Debug, PartialEq, Eq)]
775pub struct MechSet {
776  pub kind: ValueKind,
777  pub num_elements: usize,
778  pub set: IndexSet<Value>,
779}
780
781impl MechSet {
782
783  pub fn kind(&self) -> ValueKind {
784    ValueKind::Set(Box::new(self.kind.clone()), self.num_elements)
785  }
786
787  pub fn size_of(&self) -> usize {
788    self.set.iter().map(|x| x.size_of()).sum()
789  }
790
791  pub fn from_vec(vec: Vec<Value>) -> MechSet {
792    let mut set = IndexSet::new();
793    for v in vec {
794      set.insert(v);
795    }
796    let kind = if set.len() > 0 { set.iter().next().unwrap().kind() } else { ValueKind::Empty };
797    MechSet{
798      kind,
799      num_elements: set.len(),
800      set}
801  }
802
803  pub fn pretty_print(&self) -> String {
804    let mut builder = Builder::default();
805    let mut element_strings = vec![];
806    for x in self.set.iter() {
807      element_strings.push(x.pretty_print());
808    }
809    builder.push_record(element_strings);
810
811    let style = Style::empty()
812      .top(' ')
813      .left('║')
814      .right('║')
815      .bottom(' ')
816      .vertical(' ')
817      .intersection_bottom(' ')
818      .corner_top_left('╔')
819      .corner_top_right('╗')
820      .corner_bottom_left('╚')
821      .corner_bottom_right('╝');
822    let mut table = builder.build();
823    table.with(style);
824    format!("{table}")
825  }
826
827}
828
829impl Hash for MechSet {
830  fn hash<H: Hasher>(&self, state: &mut H) {
831    for x in self.set.iter() {
832      x.hash(state)
833    }
834  }
835}
836
837// Map ------------------------------------------------------------------
838
839#[derive(Clone, Debug, PartialEq, Eq)]
840pub struct MechMap {
841  pub key_kind: ValueKind,
842  pub value_kind: ValueKind,
843  pub num_elements: usize,
844  pub map: IndexMap<Value,Value>,
845}
846
847impl MechMap {
848
849  pub fn kind(&self) -> ValueKind {
850    ValueKind::Map(Box::new(self.key_kind.clone()), Box::new(self.value_kind.clone()))
851  }
852
853  pub fn size_of(&self) -> usize {
854    self.map.iter().map(|(k,v)| k.size_of() + v.size_of()).sum()
855  }
856
857  pub fn pretty_print(&self) -> String {
858    let mut builder = Builder::default();
859    let mut element_strings = vec![];
860    let mut key_strings = vec![];
861    for (k,v) in self.map.iter() {
862      element_strings.push(v.pretty_print());
863      key_strings.push(k.pretty_print());
864    }    
865    builder.push_record(key_strings);
866    builder.push_record(element_strings);
867    let mut table = builder.build();
868    table.with(Style::modern_rounded());
869    format!("{table}")
870  }
871
872  pub fn from_vec(vec: Vec<(Value,Value)>) -> MechMap {
873    let mut map = IndexMap::new();
874    for (k,v) in vec {
875      map.insert(k,v);
876    }
877    MechMap{
878      key_kind: map.keys().next().unwrap().kind(),
879      value_kind: map.values().next().unwrap().kind(),
880      num_elements: map.len(),
881      map}
882  }
883}
884
885impl Hash for MechMap {
886  fn hash<H: Hasher>(&self, state: &mut H) {
887    for x in self.map.iter() {
888      x.hash(state)
889    }
890  }
891}
892
893// Table ------------------------------------------------------------------
894
895#[derive(Clone, Debug, PartialEq, Eq)]
896pub struct MechTable {
897  rows: usize,
898  cols: usize,
899  data: IndexMap<Value,(ValueKind,Matrix<Value>)>,
900  col_names: HashMap<Value,String>,
901}
902
903impl MechTable {
904
905  pub fn new(rows: usize, cols: usize, data: IndexMap<Value,(ValueKind,Matrix<Value>)>, col_names: HashMap<Value,String>) -> MechTable {
906    MechTable{rows, cols, data, col_names}
907  }
908
909  pub fn kind(&self) -> ValueKind {
910    ValueKind::Table(
911      self.data.iter().map(|(_,v)| v.0.clone()).collect(),
912      self.rows)
913  }
914
915  pub fn size_of(&self) -> usize {
916    self.data.iter().map(|(_,(_,v))| v.size_of()).sum()
917  }
918
919  pub fn rows(&self) -> usize {
920    self.rows
921  }
922
923  pub fn cols(&self) -> usize {
924    self.cols
925  }
926
927  pub fn get(&self, key: &Value) -> Option<&(ValueKind,Matrix<Value>)> {
928    self.data.get(key)
929  }
930
931  pub fn pretty_print(&self) -> String {
932    let mut builder = Builder::default();
933    for (k,(knd,val)) in &self.data {
934      let name = self.col_names.get(k).unwrap();
935      let val_string: String = val.as_vec().iter()
936        .map(|x| x.pretty_print())
937        .collect::<Vec<String>>()
938        .join("\n");
939      let mut col_string = vec![format!("{}<{}>", name.to_string(), knd), val_string];
940      builder.push_column(col_string);
941    }
942    let mut table = builder.build();
943    table.with(Style::modern_rounded());
944    format!("{table}")
945  }
946
947  pub fn shape(&self) -> Vec<usize> {
948    vec![self.rows,self.cols]
949  }
950}
951
952impl Hash for MechTable {
953  fn hash<H: Hasher>(&self, state: &mut H) {
954    for (k,(knd,val)) in self.data.iter() {
955      k.hash(state);
956      knd.hash(state);
957      val.hash(state);
958    }
959  }
960}
961
962// Record ------------------------------------------------------------------
963
964#[derive(Clone, Debug, PartialEq, Eq)]
965pub struct MechRecord {
966  pub cols: usize,
967  pub kinds: Vec<ValueKind>,
968  pub data: IndexMap<u64,Value>,
969  pub field_names: HashMap<u64,String>,
970}
971
972impl MechRecord {
973
974  pub fn get(&self, key: &u64) -> Option<&Value> {
975    self.data.get(key)
976  }
977
978  pub fn from_vec(vec: Vec<((u64,String),Value)>) -> MechRecord {
979    let mut data = IndexMap::new();
980    let mut field_names = HashMap::new();
981    for ((k,s),v) in vec {
982      field_names.insert(k,s);
983      data.insert(k,v);
984    }
985    let kinds = data.iter().map(|(_,v)| v.kind()).collect();
986    MechRecord{cols: data.len(), kinds, data, field_names}
987  }
988
989  pub fn insert_field(&mut self, key: u64, value: Value) {
990    self.cols += 1;
991    self.kinds.push(value.kind());
992    self.data.insert(key, value);
993  }
994
995  pub fn kind(&self) -> ValueKind {
996    ValueKind::Record(self.kinds.clone())
997  }
998
999  pub fn size_of(&self) -> usize {
1000    self.data.iter().map(|(_,v)| v.size_of()).sum()
1001  }
1002
1003  pub fn pretty_print(&self) -> String {
1004    let mut builder = Builder::default();
1005    let mut key_strings = vec![];
1006    let mut element_strings = vec![];
1007    for (k,v) in &self.data {
1008      let field_name = self.field_names.get(k).unwrap();
1009      key_strings.push(format!("{}<{}>",field_name, v.kind()));
1010      element_strings.push(v.pretty_print());
1011    }
1012    builder.push_record(key_strings);
1013    builder.push_record(element_strings);
1014    let mut table = builder.build();
1015    table.with(Style::modern_rounded());
1016    format!("{table}")
1017  }
1018
1019  pub fn shape(&self) -> Vec<usize> {
1020    vec![1,self.cols]
1021  }
1022}
1023
1024impl Hash for MechRecord {
1025  fn hash<H: Hasher>(&self, state: &mut H) {
1026    for (k,v) in self.data.iter() {
1027      k.hash(state);
1028      v.hash(state);
1029    }
1030  }
1031}
1032
1033// Tuple ----------------------------------------------------------------------
1034
1035#[derive(Clone, Debug, PartialEq, Eq)]
1036pub struct MechTuple {
1037  pub elements: Vec<Box<Value>>
1038}
1039
1040impl MechTuple {
1041
1042  pub fn pretty_print(&self) -> String {
1043    let mut builder = Builder::default();
1044    let string_elements: Vec<String> = self.elements.iter().map(|e| e.pretty_print()).collect::<Vec<String>>();
1045    builder.push_record(string_elements);
1046    let mut table = builder.build();
1047    let style = Style::empty()
1048      .top(' ')
1049      .left('│')
1050      .right('│')
1051      .bottom(' ')
1052      .vertical(' ')
1053      .intersection_bottom('ʼ')
1054      .corner_top_left('╭')
1055      .corner_top_right('╮')
1056      .corner_bottom_left('╰')
1057      .corner_bottom_right('╯');
1058    table.with(style);
1059    format!("{table}")
1060  }
1061
1062  pub fn from_vec(elements: Vec<Value>) -> Self {
1063    MechTuple{elements: elements.iter().map(|m| Box::new(m.clone())).collect::<Vec<Box<Value>>>()}
1064  }
1065
1066  pub fn size(&self) -> usize {
1067    self.elements.len()
1068  }
1069
1070  pub fn kind(&self) -> ValueKind {
1071    ValueKind::Tuple(self.elements.iter().map(|x| x.kind()).collect())
1072  }
1073
1074  pub fn size_of(&self) -> usize {
1075    self.elements.iter().map(|x| x.size_of()).sum()
1076  }
1077
1078}
1079
1080impl Hash for MechTuple {
1081  fn hash<H: Hasher>(&self, state: &mut H) {
1082    for x in self.elements.iter() {
1083        x.hash(state)
1084    }
1085  }
1086}
1087
1088// Enum -----------------------------------------------------------------------
1089
1090#[derive(Clone, Debug, PartialEq, Eq)]
1091pub struct MechEnum {
1092  pub id: u64,
1093  pub variants: Vec<(u64, Option<Value>)>,
1094}
1095
1096impl MechEnum {
1097
1098  pub fn kind(&self) -> ValueKind {
1099    ValueKind::Enum(self.id)
1100  }
1101
1102  pub fn size_of(&self) -> usize {
1103    self.variants.iter().map(|(_,v)| v.as_ref().map_or(0, |x| x.size_of())).sum()
1104  }
1105
1106  pub fn pretty_print(&self) -> String {
1107    let mut builder = Builder::default();
1108    let string_elements: Vec<String> = vec![format!("{}{:?}",self.id,self.variants)];
1109    builder.push_record(string_elements);
1110    let mut table = builder.build();
1111    table.with(Style::modern_rounded());
1112    format!("{table}")
1113  }
1114
1115}
1116
1117impl Hash for MechEnum {
1118  fn hash<H: Hasher>(&self, state: &mut H) {
1119    self.id.hash(state);
1120    self.variants.hash(state);
1121  }
1122}