Add printing support for assignment operators

master
Nick Krichevsky 2024-05-22 18:43:56 -04:00
parent 21e1c315ad
commit 2036704732
1 changed files with 26 additions and 2 deletions

View File

@ -136,8 +136,8 @@ impl ExprVisitor<String> for ASTPrinter {
name.lexeme().to_owned()
}
fn visit_assign(&mut self, _name: &lex::Token, _value: &Expr) -> String {
todo!()
fn visit_assign(&mut self, name: &lex::Token, value: &Expr) -> String {
self.parenthesize(&format!("{}=", name.lexeme()), &[value])
}
}
@ -167,6 +167,30 @@ mod tests {
assert_eq!("(+ 123 456)", result);
}
#[test]
fn test_simple_add_assignment() {
let result = ASTPrinter.visit_expr(&Expr::Assign {
name: Token::new(
TokenKind::Identifier("a".to_string().into()),
"a".to_string(),
10,
),
value: Box::new(Expr::Binary {
left: Box::new(Expr::Literal {
value: ast::LiteralValue::Number(123_f64),
token: Token::new(TokenKind::Number(456_f64), "456".to_string(), 10),
}),
operator: Token::new(TokenKind::Plus, "+".to_string(), 1),
right: Box::new(Expr::Literal {
value: ast::LiteralValue::Number(456_f64),
token: Token::new(TokenKind::Number(456_f64), "456".to_string(), 10),
}),
}),
});
assert_eq!("(a= (+ 123 456))", result);
}
#[test]
fn test_complicated_arithmetic() {
let result = ASTPrinter.visit_expr(&Expr::Binary {