|
| 1 | +use crate::error::{parser_error, Error}; |
| 2 | +use crate::syntax::{Expr, LiteralValue}; |
| 3 | +use crate::token::{Token, TokenType}; |
| 4 | + |
| 5 | +pub struct Parser<'t> { |
| 6 | + tokens: &'t Vec<Token>, |
| 7 | + current: usize, |
| 8 | +} |
| 9 | + |
| 10 | +/// AKA match in Chapter 6. |
| 11 | +macro_rules! matches { |
| 12 | + ( $sel:ident, $( $x:expr ),* ) => { |
| 13 | + { |
| 14 | + if $( $sel.check($x) )||* { |
| 15 | + $sel.advance(); |
| 16 | + true |
| 17 | + } else { |
| 18 | + false |
| 19 | + } |
| 20 | + } |
| 21 | + }; |
| 22 | +} |
| 23 | + |
| 24 | +impl<'t> Parser<'t> { |
| 25 | + pub fn new(tokens: &'t Vec<Token>) -> Self { |
| 26 | + Parser { tokens, current: 0 } |
| 27 | + } |
| 28 | + |
| 29 | + pub fn parse(&mut self) -> Option<Expr> { |
| 30 | + self.expression().ok() |
| 31 | + } |
| 32 | + |
| 33 | + fn expression(&mut self) -> Result<Expr, Error> { |
| 34 | + self.equality() |
| 35 | + } |
| 36 | + |
| 37 | + fn equality(&mut self) -> Result<Expr, Error> { |
| 38 | + let mut expr = self.comparison()?; |
| 39 | + |
| 40 | + while matches!(self, TokenType::BangEqual, TokenType::EqualEqual) { |
| 41 | + let operator: Token = (*self.previous()).clone(); |
| 42 | + let right: Expr = self.comparison()?; |
| 43 | + expr = Expr::Binary { |
| 44 | + left: Box::new(expr), |
| 45 | + operator, |
| 46 | + right: Box::new(right), |
| 47 | + }; |
| 48 | + } |
| 49 | + |
| 50 | + Ok(expr) |
| 51 | + } |
| 52 | + |
| 53 | + fn check(&self, token_type: TokenType) -> bool { |
| 54 | + if self.is_at_end() { |
| 55 | + return false; |
| 56 | + } |
| 57 | + |
| 58 | + token_type == self.peek().tpe |
| 59 | + } |
| 60 | + |
| 61 | + fn consume(&mut self, tpe: TokenType, message: &str) -> Result<Token, Error> { |
| 62 | + if self.check(tpe) { |
| 63 | + Ok(self.advance().clone()) |
| 64 | + } else { |
| 65 | + Err(self.error(self.peek(), message)) |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + fn advance(&mut self) -> &Token { |
| 70 | + if !self.is_at_end() { |
| 71 | + self.current += 1; |
| 72 | + } |
| 73 | + self.previous() |
| 74 | + } |
| 75 | + |
| 76 | + fn previous(&self) -> &Token { |
| 77 | + self.tokens |
| 78 | + .get(self.current - 1) |
| 79 | + .expect("Previous was empty.") |
| 80 | + } |
| 81 | + |
| 82 | + fn error(&self, token: &Token, message: &str) -> Error { |
| 83 | + parser_error(token, message); |
| 84 | + Error::Parse |
| 85 | + } |
| 86 | + |
| 87 | + fn synchronize(&mut self) { |
| 88 | + self.advance(); |
| 89 | + |
| 90 | + while !self.is_at_end() { |
| 91 | + if self.previous().tpe == TokenType::Semicolon { |
| 92 | + return; |
| 93 | + } |
| 94 | + |
| 95 | + match self.peek().tpe { |
| 96 | + TokenType::Class |
| 97 | + | TokenType::Fun |
| 98 | + | TokenType::Var |
| 99 | + | TokenType::For |
| 100 | + | TokenType::If |
| 101 | + | TokenType::While |
| 102 | + | TokenType::Print |
| 103 | + | TokenType::Return => return, |
| 104 | + _ => self.advance(), |
| 105 | + }; |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + fn peek(&self) -> &Token { |
| 110 | + self.tokens |
| 111 | + .get(self.current) |
| 112 | + .expect("Peek into end of token stream.") |
| 113 | + } |
| 114 | + |
| 115 | + fn is_at_end(&self) -> bool { |
| 116 | + self.peek().tpe == TokenType::EOF |
| 117 | + } |
| 118 | + |
| 119 | + fn comparison(&mut self) -> Result<Expr, Error> { |
| 120 | + let mut expr = self.addition()?; |
| 121 | + |
| 122 | + while matches!( |
| 123 | + self, |
| 124 | + TokenType::Greater, |
| 125 | + TokenType::GreaterEqual, |
| 126 | + TokenType::Less, |
| 127 | + TokenType::LessEqual |
| 128 | + ) { |
| 129 | + let operator: Token = self.previous().clone(); |
| 130 | + let right = self.addition()?; |
| 131 | + expr = Expr::Binary { |
| 132 | + left: Box::new(expr), |
| 133 | + operator, |
| 134 | + right: Box::new(right), |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + Ok(expr) |
| 139 | + } |
| 140 | + |
| 141 | + fn addition(&mut self) -> Result<Expr, Error> { |
| 142 | + let mut expr = self.multiplication()?; |
| 143 | + |
| 144 | + while matches!(self, TokenType::Minus, TokenType::Plus) { |
| 145 | + let operator: Token = self.previous().clone(); |
| 146 | + let right = self.multiplication()?; |
| 147 | + expr = Expr::Binary { |
| 148 | + left: Box::new(expr), |
| 149 | + operator, |
| 150 | + right: Box::new(right), |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + Ok(expr) |
| 155 | + } |
| 156 | + |
| 157 | + fn multiplication(&mut self) -> Result<Expr, Error> { |
| 158 | + let mut expr = self.unary()?; |
| 159 | + |
| 160 | + while matches!(self, TokenType::Slash, TokenType::Star) { |
| 161 | + let operator: Token = self.previous().clone(); |
| 162 | + let right = self.unary()?; |
| 163 | + expr = Expr::Binary { |
| 164 | + left: Box::new(expr), |
| 165 | + operator, |
| 166 | + right: Box::new(right), |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + Ok(expr) |
| 171 | + } |
| 172 | + |
| 173 | + fn unary(&mut self) -> Result<Expr, Error> { |
| 174 | + if matches!(self, TokenType::Bang, TokenType::Minus) { |
| 175 | + let operator: Token = self.previous().clone(); |
| 176 | + let right = self.unary()?; |
| 177 | + Ok(Expr::Unary { |
| 178 | + operator, |
| 179 | + right: Box::new(right), |
| 180 | + }) |
| 181 | + } else { |
| 182 | + self.primary() |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + fn primary(&mut self) -> Result<Expr, Error> { |
| 187 | + // We don't use matches!() here since we want to extract the literals. |
| 188 | + let expr = match &self.peek().tpe { |
| 189 | + TokenType::False => Expr::Literal { |
| 190 | + value: LiteralValue::Boolean(false), |
| 191 | + }, |
| 192 | + TokenType::True => Expr::Literal { |
| 193 | + value: LiteralValue::Boolean(true), |
| 194 | + }, |
| 195 | + TokenType::Nil => Expr::Literal { |
| 196 | + value: LiteralValue::Null, |
| 197 | + }, |
| 198 | + TokenType::String { literal } => Expr::Literal { |
| 199 | + value: LiteralValue::String(literal.clone()), |
| 200 | + }, |
| 201 | + TokenType::Number { literal } => Expr::Literal { |
| 202 | + value: LiteralValue::Number(literal.clone()), |
| 203 | + }, |
| 204 | + TokenType::LeftParen => { |
| 205 | + let expr = self.expression()?; |
| 206 | + self.consume(TokenType::RightParen, "Expected ')' after expression.")?; |
| 207 | + Expr::Grouping { |
| 208 | + expression: Box::new(expr), |
| 209 | + } |
| 210 | + } |
| 211 | + _ => return Err(self.error(self.peek(), "Expect expression.")), |
| 212 | + }; |
| 213 | + |
| 214 | + self.advance(); |
| 215 | + |
| 216 | + Ok(expr) |
| 217 | + } |
| 218 | +} |
| 219 | + |
| 220 | +#[cfg(test)] |
| 221 | +mod tests { |
| 222 | + use super::*; |
| 223 | + use crate::scanner::Scanner; |
| 224 | + use crate::syntax::AstPrinter; |
| 225 | + |
| 226 | + #[test] |
| 227 | + fn test_parser() { |
| 228 | + let mut scanner = Scanner::new("-123 * 45.67".to_string()); |
| 229 | + let tokens = scanner.scan_tokens(); |
| 230 | + |
| 231 | + let mut parser = Parser::new(tokens); |
| 232 | + let expression = parser.parse().expect("Could not parse sample code."); |
| 233 | + let printer = AstPrinter; |
| 234 | + |
| 235 | + assert_eq!(printer.print(expression), "(* (- 123) 45.67)"); |
| 236 | + } |
| 237 | +} |
0 commit comments