Crafting Interpreters in Rust: Parsing Unary Negation
blog.differentpla.net·9h
🦀Rust Macros
Preview
Report Post

In the last post, we implemented unary-not. In this one, we’ll implement the other unary operator: negation.

As usual, we’ll start with a test:

#[test]
fn negation() {
let parser = lox::ExpressionParser::new();
let expr = parser.parse("-42").unwrap();
assert_eq!(expr, Expression::Nil);
}

Now – obviously – this isn’t going to pass, but it’ll prompt us through the steps to get it to compile.

First we have to update the grammar to add "-":

Unary = {
"!" <expr: Unary> => Expression::Not(Box::new(expr)),
"-" <expr: Unary> => Expression::Negate(Box::new(expr)),
Primary
};

Then we update the Expression type:

#[derive(Debug, PartialEq)]
pub enum Expression<'input> {
// ...
Negate(Box<Expression<'input>>),
}

Then we can update the test so that it passes:…

Similar Posts

Loading similar posts...