mech_core/
nodes.rs

1use std::cmp::Ordering;
2use crate::hash_chars; 
3use std::fmt;
4
5#[derive(Clone, Copy, Ord, PartialEq, Eq, Hash, Serialize, Deserialize)]
6pub struct SourceLocation {
7  pub row: usize,
8  pub col: usize,
9}
10
11impl PartialOrd for SourceLocation {
12  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
13    if self.row < other.row {
14      Some(Ordering::Less)
15    } else if self.row > other.row {
16      Some(Ordering::Greater)
17    } else {
18      self.col.partial_cmp(&other.col)
19    }
20  }
21}
22
23impl fmt::Debug for SourceLocation {
24  #[inline]
25  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26    write!(f, "{}:{}", self.row, self.col);
27    Ok(())
28  }
29}
30
31#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
32pub struct SourceRange {
33  pub start: SourceLocation,
34  pub end:   SourceLocation,
35}
36
37/// Coordinates in SourceRange are 1-indexed, i.e. they directly translate
38/// human's view to line and column numbers.  Having value 0 means the 
39/// range is not initialized.
40impl Default for SourceRange {
41  fn default() -> Self {
42    SourceRange {
43      start: SourceLocation { row: 0, col: 0 },
44      end:   SourceLocation { row: 0, col: 0 },
45    }
46  }
47}
48
49impl fmt::Debug for SourceRange {
50  #[inline]
51  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52    write!(f, "[{:?}, {:?})", self.start, self.end);
53    Ok(())
54  }
55}
56
57pub fn merge_src_range(r1: SourceRange, r2: SourceRange) -> SourceRange {
58  SourceRange {
59    start: r1.start.min(r2.start),
60    end:   r2.end.max(r2.end),
61  }
62}
63
64#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
65pub enum TokenKind {
66  Alpha,
67  Digit,
68  HashTag,
69  LeftBracket,
70  RightBracket,
71  LeftParenthesis,
72  RightParenthesis,
73  LeftBrace,
74  RightBrace,
75  Caret,
76  Semicolon,
77  Space,
78  Plus,
79  Dash,
80  Underscore,
81  At,
82  Asterisk,
83  Slash,
84  Apostrophe,
85  Equal,
86  LeftAngle,
87  RightAngle,
88  Exclamation,
89  Question,
90  Period,
91  Colon,
92  Comma,
93  Tilde,
94  Grave,
95  Bar,
96  Backslash,
97  Quote,
98  Ampersand,
99  Percent,
100  Newline,
101  CarriageReturn,
102  CarriageReturnNewLine,
103  Tab,
104  Emoji,
105  Text,
106  True,
107  False,
108  Number,
109  String,
110  Title,
111  Identifier,
112  BoxDrawing,
113  Dollar,
114  Empty
115}
116
117#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
118pub struct Token { 
119  pub kind: TokenKind, 
120  pub chars: Vec<char>, 
121  pub src_range: SourceRange 
122}
123
124impl fmt::Debug for Token {
125  #[inline]
126  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127    write!(f, "{:?}:{:?}:{:?}", self.kind, String::from_iter(self.chars.iter().cloned()), self.src_range);
128    Ok(())
129  }
130}
131
132impl Default for Token {
133  fn default() -> Self {
134    Token{
135      kind: TokenKind::Empty,
136      chars: vec![],
137      src_range: SourceRange::default(),
138    }
139  }
140}
141
142impl Token {
143
144  pub fn to_string(&self) -> String {
145    self.chars.iter().collect()
146  }
147
148  pub fn merge_tokens(tokens: &mut Vec<Token>) -> Option<Token> {
149    if tokens.len() == 0 {
150      None
151    } else if tokens.len() == 1 {
152      Some(tokens[0].clone())
153    } else {
154      let first = tokens[0].src_range.clone();
155      let kind = tokens[0].kind.clone();
156      let last = tokens.last().unwrap().src_range.clone();
157      let src_range = merge_src_range(first, last);
158      let chars: Vec<char> = tokens.iter_mut().fold(vec![],|mut m, ref mut t| {m.append(&mut t.chars.clone()); m});
159      let merged_token = Token{kind, chars, src_range};
160      Some(merged_token)
161    }
162  }
163}
164
165
166
167
168#[derive(Clone, Debug, Serialize, Deserialize)]
169pub struct Program {
170  pub title: Option<Title>,
171  pub body: Body,
172}
173
174impl Program {
175  pub fn tokens(&self) -> Vec<Token> {
176    /*let mut title_tokens = match self.title.tokens() {
177      Some(tkns) => tkns,
178      None => vec![],
179    };*/
180    let body_tokens = self.body.tokens();
181    body_tokens
182  }
183}
184
185#[derive(Clone, Debug, Serialize, Deserialize)]
186pub struct Title {
187  pub text: Token,
188}
189
190impl Title {
191
192  pub fn to_string(&self) -> String {
193    self.text.to_string()
194  }
195
196}
197
198#[derive(Clone, Debug, Serialize, Deserialize)]
199pub struct Body {
200  pub sections: Vec<Section>,
201}
202
203impl Body {
204  pub fn tokens(&self) -> Vec<Token> {
205    let mut out = vec![];
206    for s in &self.sections {
207      let mut tkns = s.tokens();
208      out.append(&mut tkns);
209    }
210    out
211  }
212}
213
214#[derive(Clone, Debug, Serialize, Deserialize)]
215pub struct Subtitle {
216  pub text: Token,
217  pub level: u8,
218}
219
220impl Subtitle {
221  pub fn to_string(&self) -> String {
222    self.text.to_string()
223  }
224}
225
226#[derive(Clone, Debug, Serialize, Deserialize)]
227pub struct Section {
228  pub subtitle: Option<Subtitle>,
229  pub elements: Vec<SectionElement>,
230}
231
232impl Section {
233  pub fn tokens(&self) -> Vec<Token> {
234    let mut out = vec![];
235    for s in &self.elements {
236      let mut tkns = s.tokens();
237      out.append(&mut tkns);
238    }
239    out
240  }
241}
242
243#[derive(Clone, Debug, Serialize, Deserialize)]
244pub enum SectionElement {
245  Section(Box<Section>),
246  Comment(Comment),
247  Paragraph(Paragraph),
248  MechCode(Vec<MechCode>),
249  UnorderedList(UnorderedList),
250  CodeBlock,       // todo
251  OrderedList,     // todo
252  BlockQuote,      // todo
253  ThematicBreak,   // todo
254  Image,           // todo
255}
256
257impl SectionElement {
258  pub fn tokens(&self) -> Vec<Token> {
259    match self {
260      SectionElement::MechCode(codes) => {
261        let mut tokens = vec![];
262        for code in codes {
263          tokens.append(&mut code.tokens());
264        }
265        tokens
266      },
267      _ => todo!(),
268    }
269  }
270}
271
272pub type ListItem = Paragraph;
273
274#[derive(Clone, Debug, Serialize, Deserialize)]
275pub struct UnorderedList {
276  pub items: Vec<ListItem>,
277}
278
279#[derive(Clone, Debug, Serialize, Deserialize)]
280pub enum MechCode {
281  Expression(Expression),
282  Statement(Statement),
283  FsmSpecification(FsmSpecification),
284  FsmImplementation(FsmImplementation),
285  FunctionDefine(FunctionDefine),
286  Comment(Comment),
287}
288
289impl MechCode {
290  pub fn tokens(&self) -> Vec<Token> {
291    match self {
292      MechCode::Expression(x) => x.tokens(),
293      _ => todo!(),
294      //Statement(x) => x.tokens(),
295      //FunctionDefine(x) => x.tokens(),
296      //FsmSpecification(x) => x.tokens(),
297      //FsmImplementation(x) => x.tokens(),
298    }
299  }
300}
301
302#[derive(Clone, Debug, Serialize, Deserialize)]
303pub struct FunctionDefine {
304  pub name: Identifier,
305  pub input: Vec<FunctionArgument>,
306  pub output: Vec<FunctionArgument>,
307  pub statements: Vec<Statement>,
308}
309
310#[derive(Clone, Debug, Serialize, Deserialize)]
311pub struct FunctionArgument {
312  pub name: Identifier,
313  pub kind: KindAnnotation,
314}
315
316impl FunctionArgument {
317  pub fn tokens(&self) -> Vec<Token> {
318    let mut tokens = self.name.tokens();
319    tokens.append(&mut self.kind.tokens());
320    tokens
321  }
322}
323
324#[derive(Clone, Debug, Serialize, Deserialize)]
325pub struct FsmImplementation {
326  pub name: Identifier,
327  pub input: Vec<Identifier>,
328  pub start: Pattern,
329  pub arms: Vec<FsmArm>,
330}
331
332#[derive(Clone, Debug, Serialize, Deserialize)]
333pub enum FsmArm {
334  Guard(Pattern,Vec<Guard>),
335  Transition(Pattern,Vec<Transition>),
336}
337
338#[derive(Clone, Debug, Serialize, Deserialize)]
339pub struct Guard { 
340  pub condition: Pattern,
341  pub transitions: Vec<Transition>,
342}
343
344#[derive(Clone, Debug, Serialize, Deserialize)]
345pub enum Transition {
346  Next(Pattern),
347  Output(Pattern),
348  Async(Pattern),
349  CodeBlock(Vec<MechCode>),
350  Statement(Statement),
351}
352
353#[derive(Clone, Debug, Serialize, Deserialize)]
354pub enum Pattern {
355  Wildcard,
356  Formula(Factor),
357  Expression(Expression),
358  TupleStruct(PatternTupleStruct),
359}
360
361#[derive(Clone, Debug, Serialize, Deserialize)]
362pub struct PatternTupleStruct {
363  pub name: Identifier,
364  pub patterns: Vec<Pattern>,
365}
366
367pub type PatternTuple = Vec<Pattern>;
368
369#[derive(Clone, Debug, Serialize, Deserialize)]
370pub struct FsmSpecification {
371  pub name: Identifier,
372  pub input: Vec<Var>,
373  pub output: Option<KindAnnotation>,
374  pub states: Vec<StateDefinition>,
375}
376
377#[derive(Clone, Debug, Serialize, Deserialize)]
378pub struct StateDefinition {
379  pub name: Identifier,
380  pub state_variables: Option<Vec<Var>>,
381}
382
383#[derive(Clone, Debug, Serialize, Deserialize)]
384pub enum Statement {
385  VariableDefine(VariableDefine),
386  VariableAssign(VariableAssign),
387  KindDefine(KindDefine),
388  EnumDefine(EnumDefine),
389  FsmDeclare(FsmDeclare),    
390  OpAssign(OpAssign), 
391  SplitTable,     // todo
392  FlattenTable,   // todo
393}
394
395#[derive(Clone, Debug, Serialize, Deserialize)]
396pub struct FsmPipe {
397  pub start: FsmInstance,
398  pub transitions: Vec<Transition>
399}
400
401#[derive(Clone, Debug, Serialize, Deserialize)]
402pub enum PipeElement {
403  Expression(Expression),
404  FsmInstance(FsmInstance),
405  Timer // todo
406}
407
408#[derive(Clone, Debug, Serialize, Deserialize)]
409pub struct FsmDeclare {
410  pub fsm: Fsm,
411  pub pipe: FsmPipe,
412}
413
414#[derive(Clone, Debug, Serialize, Deserialize)]
415pub struct Fsm {
416  pub name: Identifier,
417  pub args: Option<ArgumentList>,
418  pub kind: Option<KindAnnotation>
419}
420
421pub type FsmArgs = Vec<(Option<Identifier>,Expression)>;
422
423#[derive(Clone, Debug, Serialize, Deserialize)]
424pub struct FsmInstance {
425  pub name: Identifier,
426  pub args: Option<FsmArgs>,
427}
428
429#[derive(Clone, Debug, Serialize, Deserialize)]
430pub struct EnumDefine {
431  pub name: Identifier,
432  pub variants: Vec<EnumVariant>,
433}
434
435#[derive(Clone, Debug, Serialize, Deserialize)]
436pub struct EnumVariant {
437  pub name: Identifier,
438  pub value: Option<KindAnnotation>,
439}
440
441#[derive(Clone, Debug, Serialize, Deserialize)]
442pub struct KindDefine {
443  pub name: Identifier,
444  pub kind: KindAnnotation,
445}
446
447#[derive(Clone, Debug, Serialize, Deserialize)]
448pub struct Record {
449  pub bindings: Vec<Binding>,
450}
451
452#[derive(Clone, Debug, Serialize, Deserialize)]
453pub enum Structure {
454  Empty,
455  Record(Record),
456  Matrix(Matrix),
457  Table(Table),
458  Tuple(Tuple),
459  TupleStruct(TupleStruct),
460  Set(Set),
461  Map(Map),
462}
463
464impl Structure {
465  pub fn tokens(&self) -> Vec<Token> {
466    match self {
467      Structure::Matrix(mat) => mat.tokens(),
468      _ => todo!(),
469    }
470  }
471}
472
473#[derive(Clone, Debug, Serialize, Deserialize)]
474pub struct Map {
475  pub elements: Vec<Mapping>,
476}
477
478#[derive(Clone, Debug, Serialize, Deserialize)]
479pub struct Mapping {
480  pub key: Expression,
481  pub value: Expression,
482}
483
484#[derive(Clone, Debug, Serialize, Deserialize)]
485pub struct Set {
486  pub elements: Vec<Expression>,
487}
488
489#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
490pub struct Atom {
491  pub name: Identifier,
492}
493
494#[derive(Clone, Debug, Serialize, Deserialize)]
495pub struct TupleStruct {
496  pub name: Identifier,
497  pub value: Box<Expression>,
498}
499
500#[derive(Clone, Debug, Serialize, Deserialize)]
501pub struct Matrix {
502  pub rows: Vec<MatrixRow>,
503}
504
505impl Matrix {
506  pub fn tokens(&self) -> Vec<Token> {
507    let mut tkns = vec![];
508    for r in &self.rows {
509      let mut t = r.tokens();
510      tkns.append(&mut t);
511    }
512    tkns
513  }
514}
515
516pub type TableHeader = Vec<Field>;
517
518#[derive(Clone, Debug, Serialize, Deserialize)]
519pub struct Table {
520  pub header: TableHeader,
521  pub rows: Vec<TableRow>,
522}
523
524#[derive(Clone, Debug, Serialize, Deserialize)]
525pub struct Field {
526  pub name: Identifier,
527  pub kind: Option<KindAnnotation>,
528}
529
530#[derive(Clone, Debug, Serialize, Deserialize)]
531pub struct TableColumn {
532  pub element: Expression,
533}
534
535#[derive(Clone, Debug, Serialize, Deserialize)]
536pub struct MatrixColumn {
537  pub element: Expression,
538}
539
540impl MatrixColumn {
541  pub fn tokens(&self) -> Vec<Token> {
542    self.element.tokens()
543  }
544}
545
546#[derive(Clone, Debug, Serialize, Deserialize)]
547pub struct TableRow {
548  pub columns: Vec<TableColumn>,
549}
550
551#[derive(Clone, Debug, Serialize, Deserialize)]
552pub struct MatrixRow {
553  pub columns: Vec<MatrixColumn>,
554}
555
556impl MatrixRow {
557  pub fn tokens(&self) -> Vec<Token> {
558    let mut tkns = vec![];
559    for r in &self.columns {
560      let mut t = r.tokens();
561      tkns.append(&mut t);
562    }
563    tkns
564  }
565}
566
567#[derive(Clone, Debug, Serialize, Deserialize)]
568pub struct VariableDefine {
569  pub mutable: bool,
570  pub var: Var,
571  pub expression: Expression,
572}
573
574#[derive(Clone, Debug, Serialize, Deserialize)]
575pub struct Var {
576  pub name: Identifier,
577  pub kind: Option<KindAnnotation>,
578}
579
580impl Var {
581  pub fn tokens(&self) -> Vec<Token> {
582    let mut tkns = self.name.tokens();
583    if let Some(knd) = &self.kind {
584      let mut t = knd.tokens();
585      tkns.append(&mut t);
586    }
587    tkns
588  }
589}
590
591
592#[derive(Clone, Debug, Serialize, Deserialize)]
593pub struct VariableAssign {
594  pub target: SliceRef,
595  pub expression: Expression,
596}
597
598#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
599pub struct Identifier {
600  pub name: Token,
601}
602
603impl Identifier {
604  pub fn tokens(&self) -> Vec<Token> {
605    vec![self.name.clone()]
606  }
607
608  pub fn to_string(&self) -> String {
609    self.name.to_string()
610  }
611
612}
613
614
615impl Identifier {
616  pub fn hash(&self) -> u64 {
617    hash_chars(&self.name.chars)
618  }
619}
620
621#[derive(Clone, Debug, Serialize, Deserialize)]
622pub struct Emoji {
623  pub tokens: Vec<Token>,
624}
625
626#[derive(Clone, Debug, Serialize, Deserialize)]
627pub struct Word {
628  pub tokens: Vec<Token>,
629}
630
631#[derive(Clone, Debug, Serialize, Deserialize)]
632pub struct Slice {
633  pub name: Identifier,
634  pub subscript: Vec<Subscript>
635}
636
637#[derive(Clone, Debug, Serialize, Deserialize)]
638pub struct SliceRef {
639  pub name: Identifier,
640  pub subscript: Option<Vec<Subscript>>
641}
642
643#[derive(Clone, Debug, Serialize, Deserialize)]
644pub enum Subscript {
645  Dot(Identifier),          // a.b
646  Swizzle(Vec<Identifier>), // a.b,c
647  Range(RangeExpression),   // a[1 + 1]
648  Formula(Factor),          // a[1 + 1]
649  All,                      // a[:]
650  Bracket(Vec<Subscript>),  // a[1,2,3]
651  Brace(Vec<Subscript>),    // a{"foo"}
652  DotInt(RealNumber)        // a.1
653}
654
655#[derive(Clone, Debug, Serialize, Deserialize)]
656pub enum Expression {
657  Var(Var),
658  Range(Box<RangeExpression>),
659  Slice(Slice),
660  Formula(Factor),
661  Structure(Structure),
662  Literal(Literal),
663  FunctionCall(FunctionCall),
664  FsmPipe(FsmPipe),
665}
666
667impl Expression {
668  pub fn tokens(&self) -> Vec<Token> {
669    match self {
670      Expression::Var(v) => v.tokens(),
671      Expression::Literal(ltrl) => ltrl.tokens(),
672      Expression::Structure(strct) => strct.tokens(),
673      Expression::Formula(fctr) => fctr.tokens(),
674      _ => todo!(),
675    }
676  }
677}
678
679pub type ArgumentList = Vec<(Option<Identifier>,Expression)>;
680
681#[derive(Clone, Debug, Serialize, Deserialize)]
682pub struct FunctionCall {
683  pub name: Identifier,
684  pub args: ArgumentList,
685}
686
687impl FunctionCall {
688  pub fn tokens(&self) -> Vec<Token> {
689    self.name.tokens()
690  }
691}
692
693#[derive(Clone, Debug, Serialize, Deserialize)]
694pub struct Tuple {
695  pub elements: Vec<Expression>
696}
697
698#[derive(Clone, Debug, Serialize, Deserialize)]
699pub struct Binding {
700  pub name: Identifier,
701  pub kind: Option<KindAnnotation>,
702  pub value: Expression,
703}
704
705#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
706pub struct KindAnnotation {
707  pub kind: Kind
708}
709
710impl KindAnnotation {
711
712  pub fn hash(&self) -> u64 {
713    match &self.kind {
714      Kind::Scalar(id) => id.hash(),
715      _ => todo!(),
716    }
717  }
718
719  pub fn tokens(&self) -> Vec<Token> {
720    self.kind.tokens()
721  }
722}
723
724#[derive(Clone, Debug, Serialize, Deserialize,Eq, PartialEq)]
725pub enum Kind {
726  Tuple(Vec<Kind>),
727  Bracket((Vec<Kind>,Vec<Literal>)),
728  Brace((Vec<Kind>,Vec<Literal>)),
729  Map(Box<Kind>,Box<Kind>),
730  Scalar(Identifier),
731  Atom(Identifier),
732  Function(Vec<Kind>,Vec<Kind>),
733  Fsm(Vec<Kind>,Vec<Kind>),
734  Empty,
735}
736
737impl Kind {
738  pub fn tokens(&self) -> Vec<Token> {
739    match self {
740      Kind::Tuple(x) => x.iter().flat_map(|k| k.tokens()).collect(),
741      Kind::Bracket((kinds, literals)) => {
742        kinds.iter().flat_map(|k| k.tokens())
743            .chain(literals.iter().flat_map(|l| l.tokens()))
744            .collect()
745      },
746      Kind::Brace((kinds, literals)) => {
747        kinds.iter().flat_map(|k| k.tokens())
748            .chain(literals.iter().flat_map(|l| l.tokens()))
749            .collect()
750      }
751      Kind::Map(x, y) => x.tokens().into_iter().chain(y.tokens()).collect(),
752      Kind::Scalar(x) => x.tokens(),
753      Kind::Atom(x) => x.tokens(),
754      Kind::Function(args, rets) => {
755        args.iter().flat_map(|k| k.tokens())
756            .chain(rets.iter().flat_map(|k| k.tokens()))
757            .collect()
758      }
759      Kind::Fsm(args, rets) => {
760        args.iter().flat_map(|k| k.tokens())
761            .chain(rets.iter().flat_map(|k| k.tokens()))
762            .collect()
763      }
764      Kind::Empty => vec![],
765    }
766  }
767}
768
769#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
770pub enum Literal {
771  Empty(Token),
772  Boolean(Token),
773  Number(Number),
774  String(MechString),
775  Atom(Atom),
776  TypedLiteral((Box<Literal>,KindAnnotation))
777}
778
779impl Literal {
780  pub fn tokens(&self) -> Vec<Token> {
781    match self {
782      Literal::Number(x) => x.tokens(),
783      Literal::Boolean(tkn) => vec![tkn.clone()],
784      Literal::String(strng) => vec![strng.text.clone()],
785      Literal::Atom(atm) => atm.name.tokens(),
786      _ => todo!(),
787    }
788  }
789}
790
791#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
792pub struct MechString {
793  pub text: Token,
794}
795
796#[derive(Clone, Debug, Serialize, Deserialize)]
797pub enum ParagraphElement {
798  Start(Token),
799  Text(Token),
800  Bold,            // todo
801  Italic,          // todo
802  Underline,       // todo
803  Strike,          // todo
804  InlineCode,      // todo           
805  Link,            // todo
806}
807
808impl ParagraphElement {
809
810  pub fn to_string(&self) -> String {
811    match self {
812      ParagraphElement::Start(t) => t.to_string(),
813      ParagraphElement::Text(t) => t.to_string(),
814      _ => "".to_string(),
815    }
816  }
817
818}
819
820#[derive(Clone, Debug, Serialize, Deserialize)]
821pub struct Paragraph {
822  pub elements: Vec<ParagraphElement>,
823}
824
825impl Paragraph {
826  pub fn to_string(&self) -> String {
827    let mut out = "".to_string();
828    for e in &self.elements {
829      out.push_str(&e.to_string());
830    }
831    out
832  }
833}
834
835pub type Sign = bool;
836pub type Numerator = Token;
837pub type Denominator = Token;
838pub type Whole = Token;
839pub type Part = Token;
840pub type Real = Box<Number>;
841pub type Imaginary = Box<Number>;
842pub type Base = (Whole, Part);
843pub type Exponent = (Sign, Whole, Part);
844
845#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
846pub enum Number {
847  Real(RealNumber),
848  Imaginary(ComplexNumber),
849}
850
851impl Number {
852  pub fn tokens(&self) -> Vec<Token> {
853    match self {
854      Number::Real(x) => x.tokens(),
855      _ => todo!(),
856    }
857  }
858}
859
860#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
861pub enum RealNumber {
862  Negated(Box<RealNumber>),
863  Integer(Token),
864  Float((Whole,Part)),
865  Decimal(Token),
866  Hexadecimal(Token),
867  Octal(Token),
868  Binary(Token),
869  Scientific((Base,Exponent)),
870  Rational((Numerator,Denominator)),
871}
872
873impl RealNumber {
874  pub fn tokens(&self) -> Vec<Token> {
875    match self {
876      RealNumber::Integer(tkn) => vec![tkn.clone()],
877      _ => todo!(),
878    }
879  }
880}
881
882#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
883pub struct ImaginaryNumber {
884  pub number: RealNumber,
885}
886
887#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
888pub struct ComplexNumber {
889  pub real: Option<RealNumber>,
890  pub imaginary: ImaginaryNumber
891}
892
893#[derive(Clone, Debug, Serialize, Deserialize)]
894pub struct Comment {
895  pub text: Token,
896}
897
898#[derive(Clone, Debug, Serialize, Deserialize)]
899pub struct OpAssign {
900  pub target: SliceRef,
901  pub op: OpAssignOp,
902  pub expression: Expression,
903}
904
905#[derive(Clone, Debug, Serialize, Deserialize)]
906pub enum OpAssignOp {
907  Add,
908  Sub,   
909  Mul,
910  Div,
911  Exp,   
912}
913
914#[derive(Clone, Debug, Serialize, Deserialize)]
915pub enum RangeOp {
916  Inclusive,
917  Exclusive,      
918}
919
920#[derive(Clone, Debug, Serialize, Deserialize)]
921pub enum AddSubOp {
922  Add,
923  Sub
924}
925
926#[derive(Clone, Debug, Serialize, Deserialize)]
927pub enum MulDivOp {
928  Mul,
929  Div
930}
931
932#[derive(Clone, Debug, Serialize, Deserialize)]
933pub enum VecOp {
934  MatMul,
935  Solve,
936  Dot,
937  Cross,
938}
939
940#[derive(Clone, Debug, Serialize, Deserialize)]
941pub enum ExponentOp {
942  Exp
943}
944
945#[derive(Clone, Debug, Serialize, Deserialize)]
946pub enum ComparisonOp {
947  LessThan,
948  GreaterThan,
949  LessThanEqual,
950  GreaterThanEqual,
951  Equal,
952  NotEqual,
953}
954
955#[derive(Clone, Debug, Serialize, Deserialize)]
956pub enum LogicOp {
957  And,
958  Or,
959  Not,
960  Xor,
961}
962
963#[derive(Clone, Debug, Serialize, Deserialize)]
964pub enum FormulaOperator {
965  Logic(LogicOp),
966  Comparison(ComparisonOp),
967  AddSub(AddSubOp),
968  MulDiv(MulDivOp),
969  Exponent(ExponentOp),
970  Vec(VecOp),
971}
972
973#[derive(Clone, Debug, Serialize, Deserialize)]
974pub struct RangeExpression {
975  pub start: Factor,
976  pub increment: Option<(RangeOp,Factor)>,
977  pub operator: RangeOp,
978  pub terminal: Factor,
979}
980
981impl RangeExpression {
982  pub fn tokens(&self) -> Vec<Token> {
983    let mut tokens = self.start.tokens();
984    tokens.append(&mut self.terminal.tokens());
985    tokens
986  }
987}
988
989#[derive(Clone, Debug, Serialize, Deserialize)]
990pub struct Term {
991  pub lhs: Factor,
992  pub rhs: Vec<(FormulaOperator,Factor)>
993}
994
995impl Term {
996  pub fn tokens(&self) -> Vec<Token> {
997    let mut lhs_tkns = self.lhs.tokens();
998    let mut rhs_tkns = vec![];
999    for (op, r) in &self.rhs {
1000      let mut tkns = r.tokens();
1001      rhs_tkns.append(&mut tkns);
1002    }
1003    lhs_tkns.append(&mut rhs_tkns);
1004    lhs_tkns
1005  }
1006}
1007
1008#[derive(Clone, Debug, Serialize, Deserialize)]
1009pub enum Factor {
1010  Term(Box<Term>),
1011  Parenthetical(Box<Factor>),
1012  Expression(Box<Expression>),
1013  Negate(Box<Factor>),
1014  Not(Box<Factor>),
1015  Transpose(Box<Factor>),
1016}
1017
1018impl Factor {
1019  pub fn tokens(&self) -> Vec<Token> {
1020    match self {
1021      Factor::Term(x) => x.tokens(),
1022      Factor::Expression(x) => x.tokens(),
1023      Factor::Negate(x) => x.tokens(),
1024      Factor::Not(x) => x.tokens(),
1025      Factor::Transpose(x) => x.tokens(),
1026      Factor::Parenthetical(x) => x.tokens(),
1027    }
1028  }
1029}