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...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help