refactor: remove specification of operators for ternary operator

I don't plan on adding other ternary operators. So we just gonna assume
that we only have one ternary operator, which is ? !
This commit is contained in:
Seymur Bagirov 2025-01-06 07:07:39 +04:00
parent 50a9e062e0
commit be15364e3b
3 changed files with 2 additions and 12 deletions

View File

@ -4,9 +4,7 @@ use crate::token::{LiteralType, Token};
pub enum Expr { pub enum Expr {
Ternary { Ternary {
first: Box<Expr>, first: Box<Expr>,
first_op: Token,
second: Box<Expr>, second: Box<Expr>,
second_op: Token,
third: Box<Expr>, third: Box<Expr>,
}, },
Binary { Binary {

View File

@ -50,15 +50,12 @@ impl Parser<'_> {
let expr = self.equality()?; let expr = self.equality()?;
if self.match_token(&[Question]) { if self.match_token(&[Question]) {
let first_op = self.previous().clone();
let second = self.expression()?; let second = self.expression()?;
let second_op = self.consume(Colon, "Expected : after ternary operator ?")?; let _ = self.consume(Colon, "Expected : after ternary operator ?")?;
let third = self.ternary()?; let third = self.ternary()?;
return Ok(Expr::Ternary { return Ok(Expr::Ternary {
first: Box::new(expr), first: Box::new(expr),
first_op,
second: Box::new(second), second: Box::new(second),
second_op,
third: Box::new(third), third: Box::new(third),
}); });
} }

View File

@ -13,14 +13,9 @@ pub fn pretty_print(expr: &Expr) -> String {
Expr::Unary { op, right } => parenthesize(&op.lexeme, &[right]), Expr::Unary { op, right } => parenthesize(&op.lexeme, &[right]),
Expr::Ternary { Expr::Ternary {
first, first,
first_op,
second, second,
second_op,
third, third,
} => parenthesize( } => parenthesize("?:", &[first, second, third]),
&format!("{}{}", first_op.lexeme, second_op.lexeme),
&[first, second, third],
),
} }
} }