Skip to main content

vtl_rs/
parser.rs

1use crate::types::{ASTNode, Token};
2
3pub struct Parser {
4    pub tokens: Vec<Token>,
5    pub current: usize,
6}
7
8impl Parser {
9    pub fn new(tokens: Vec<Token>) -> Self {
10        Parser { tokens, current: 0 }
11    }
12
13    // Peek at the current token
14    pub fn peek(&self) -> Result<&Token, String> {
15        self.tokens
16            .get(self.current)
17            .ok_or_else(|| "Unexpected end of input (#1 peek)".to_string())
18    }
19
20    // Consume and return the current token
21    pub fn consume(&mut self) -> Result<&Token, String> {
22        if self.current < self.tokens.len() {
23            self.current += 1;
24            Ok(&self.tokens[self.current - 1])
25        } else {
26            Err("Unexpected end of input (#2 consume)".to_string())
27        }
28    }
29
30    // Parse a number token
31    pub fn parse_number(&mut self) -> Result<ASTNode, String> {
32        if let Token::Number(value) = self.consume()? {
33            Ok(ASTNode::Number(*value))
34        } else {
35            Err("Expected a number (#3 parse_number)".to_string())
36        }
37    }
38
39    // Parse a variable token
40    pub fn parse_variable(&mut self) -> Result<ASTNode, String> {
41        if let Token::Variable(var) = self.consume()? {
42            Ok(ASTNode::Variable(*var))
43        } else {
44            Err("Expected a variable (#4 parse_variable".to_string())
45        }
46    }
47
48    // Parse an expression (handles '+' and '-' operators)
49    pub fn parse_expression(&mut self) -> Result<ASTNode, String> {
50        let mut node = self.parse_term()?;
51
52        while matches!(self.peek(), Ok(Token::Plus) | Ok(Token::Minus)) {
53            let operator = self.consume()?.clone();
54            let right = self.parse_term()?;
55            node = ASTNode::BinaryOp {
56                left: Box::new(node),
57                operator,
58                right: Box::new(right),
59            };
60        }
61
62        Ok(node)
63    }
64
65    // Parse a term (handles '*' and '/' operators)
66    pub fn parse_term(&mut self) -> Result<ASTNode, String> {
67        let mut node = self.parse_factor()?;
68
69        while matches!(
70            self.peek(),
71            Ok(Token::Multiply) | Ok(Token::Divide) | Ok(Token::Remainder)
72        ) {
73            let operator = self.consume()?.clone();
74            let right = self.parse_factor()?;
75            node = ASTNode::BinaryOp {
76                left: Box::new(node),
77                operator,
78                right: Box::new(right),
79            };
80        }
81
82        Ok(node)
83    }
84
85    pub fn parse_string_literal(&mut self) -> Result<ASTNode, String> {
86        if let Ok(Token::StringLiteral(value)) = self.peek().cloned() {
87            self.consume()?; // Consume the string literal token
88            return Ok(ASTNode::String(value.clone()));
89        }
90
91        Err("Expected a string literal".to_string())
92    }
93
94    // Parse a factor (number, variable, or unary operator)
95    pub fn parse_factor(&mut self) -> Result<ASTNode, String> {
96        match self.peek()? {
97            // Handle numbers
98            Token::Number(_) => self.parse_number(),
99
100            // Handle variables
101            Token::Variable(_) => self.parse_variable(),
102
103            // Handle string literals
104            Token::StringLiteral(_) => self.parse_string_literal(),
105
106            // Handle unary minus
107            Token::Minus => {
108                self.consume()?; // Consume the '-' token
109                let expr = self.parse_factor()?; // Parse the expression after '-'
110                Ok(ASTNode::UnaryOp {
111                    operator: Token::Minus,
112                    expr: Box::new(expr),
113                })
114            }
115
116            // Handle remainder (unary operator in this context)
117            Token::Remainder => {
118                self.consume()?; // Consume the '%' token
119                Ok(ASTNode::Variable('%'))
120            }
121
122            // Unexpected token handling
123            _ => Err(format!(
124                "Unexpected token (#5 parse_factor): {:?}",
125                self.peek()?
126            )),
127        }
128    }
129
130    // Main entry point for parsing, including assignments
131    pub fn parse(&mut self) -> Result<ASTNode, String> {
132        // First, check if it's a variable assignment
133        if let Ok(Token::Variable(var)) = self.peek() {
134            let var = *var; // Copy the variable first to avoid holding the immutable borrow
135
136            self.consume()?; // Consume the variable token
137
138            // Check for the '=' sign
139            if let Ok(Token::Assign) = self.peek() {
140                self.consume()?; // Consume the '=' sign
141                let expr = self.parse_expression()?; // Parse the expression on the right-hand side
142
143                return Ok(ASTNode::Assignment {
144                    variable: var, // Use the copied variable
145                    expr: Box::new(expr),
146                });
147            }
148        }
149
150        // If not an assignment, just parse a normal expression
151        self.parse_expression()
152    }
153}