Skip to main content

math_parser_rs/dsl/
types.rs

1use std::fmt;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum TokenType {
5    /// A function or variable
6    Identifier,
7    /// A basic f64 number
8    Number,
9    /// Operator represents a specific calculation object eg `+`, `-`, `*` or `/`
10    Operator,
11    /// For multiple function arguments
12    Comma,
13    /// Open parantheseese
14    ParaOpen,
15    /// Closing parantheseese
16    ParaClose,
17    /// Not yet added functionality
18    Unimplemented,
19}
20
21impl fmt::Display for TokenType {
22    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
23        write!(f, "{self:?}")
24    }
25}
26
27#[derive(Debug, PartialEq)]
28pub struct Token {
29    pub token_type: TokenType,
30    pub text: String,
31    pub position: usize,
32}
33
34impl fmt::Display for Token {
35    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36        write!(
37            f,
38            "{{type: {}, text: '{}', pos: {}}}",
39            self.token_type, self.text, self.position
40        )
41    }
42}
43
44impl Token {
45    pub fn new(token_type: TokenType, text: String, position: usize) -> Self {
46        Token {
47            token_type,
48            text,
49            position,
50        }
51    }
52}
53
54#[derive(Debug)]
55pub struct LexResult {
56    pub rhs: Vec<Token>,
57}
58
59impl fmt::Display for LexResult {
60    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61        writeln!(f, "LexResult [")?;
62        for token in &self.rhs {
63            writeln!(f, "  {token},")?;
64        }
65        write!(f, "]")
66    }
67}