Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parser: Prefix Negation and Minus #25

Merged
merged 1 commit into from
Dec 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/lexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ lazy_static! {
terminal!(m, Colon, ":");
terminal!(m, Comma, ",");
terminal!(m, Dot, ".");
terminal!(m, ExclamationMark, "!");
terminal!(m, SmallRightArrow, "->");
terminal!(m, BigRightArrow, "=>");
terminal!(m, Backslash, "\\");
Expand Down
4 changes: 4 additions & 0 deletions src/lexer/token_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,8 @@ pub enum TokenKind {
StructKeyword {
position: Position,
},
#[terminal]
ExclamationMark {
position: Position,
},
}
168 changes: 135 additions & 33 deletions src/parser/ast/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod if_expression;
mod lambda;
mod num;
mod postfix;
mod prefix;
mod struct_initialisation;

pub use self::array::*;
Expand All @@ -16,6 +17,7 @@ pub use self::if_expression::*;
pub use self::lambda::*;
pub use self::num::*;
pub use self::postfix::*;
pub use self::prefix::*;
pub use self::struct_initialisation::*;

use crate::lexer::Tokens;
Expand Down Expand Up @@ -49,6 +51,7 @@ pub enum Expression {
Multiplication(Box<Expression>, Box<Expression>),
Parens(Box<Expression>),
Postfix(Postfix),
Prefix(Prefix),
Comparison {
lhs: Box<Expression>,
rhs: Box<Expression>,
Expand All @@ -60,40 +63,67 @@ pub enum Expression {

impl FromTokens<TokenKind> for Expression {
fn parse(tokens: &mut Tokens<TokenKind>) -> Result<AstNode, ParseError> {
let mut expr = if let Some(TokenKind::LParen { .. }) = tokens.peek() {
let matcher = Comb::LPAREN >> Comb::EXPR >> Comb::RPAREN;
let result = matcher.parse(tokens)?;
let expr = match result.first() {
Some(AstNode::Expression(rhs)) => rhs.clone(),
None | Some(_) => unreachable!(),
};
Expression::Parens(Box::new(expr))
} else {
let matcher = Comb::FUNCTION
| Comb::IF
| Comb::NUM
| Comb::STRUCT_INITILISATION
| Comb::ID
| Comb::LAMBDA
| Comb::BLOCK
| Comb::ARRAY;
let result = matcher.parse(tokens)?;
match result.first() {
Some(AstNode::Id(id)) => Expression::Id(id.clone()),
Some(AstNode::Num(num)) => Expression::Num(num.clone()),
Some(AstNode::Function(func)) => {
return Ok(Expression::Function(func.clone()).into())
}
Some(AstNode::Lambda(lambda)) => {
return Ok(Expression::Lambda(lambda.clone()).into())
}
Some(AstNode::If(if_expression)) => Expression::If(if_expression.clone()),
Some(AstNode::Block(block)) => Expression::Block(block.clone()),
Some(AstNode::Array(array)) => Expression::Array(array.clone()),
Some(AstNode::StructInitialisation(initialisation)) => {
Expression::StructInitialisation(initialisation.clone())
let mut expr = match tokens.peek() {
Some(TokenKind::LParen { .. }) => {
let matcher = Comb::LPAREN >> Comb::EXPR >> Comb::RPAREN;
let result = matcher.parse(tokens)?;
let expr = match result.first() {
Some(AstNode::Expression(rhs)) => rhs.clone(),
None | Some(_) => unreachable!(),
};
Expression::Parens(Box::new(expr))
}
Some(TokenKind::Minus { .. }) => {
let matcher = Comb::MINUS >> Comb::EXPR;
let result = matcher.parse(tokens)?;

let Some(AstNode::Expression(expr)) = result.first() else {
unreachable!();
};

Expression::Prefix(Prefix::Minus {
expr: Box::new(expr.clone()),
})
}
Some(TokenKind::ExclamationMark { .. }) => {
let matcher = Comb::EXCLAMATION_MARK >> Comb::EXPR;
let result = matcher.parse(tokens)?;

let Some(AstNode::Expression(expr)) = result.first() else {
unreachable!();
};

Expression::Prefix(Prefix::Negation {
expr: Box::new(expr.clone()),
})
}
_ => {
let matcher = Comb::FUNCTION
| Comb::IF
| Comb::NUM
| Comb::STRUCT_INITILISATION
| Comb::ID
| Comb::LAMBDA
| Comb::BLOCK
| Comb::ARRAY;
let result = matcher.parse(tokens)?;
match result.first() {
Some(AstNode::Id(id)) => Expression::Id(id.clone()),
Some(AstNode::Num(num)) => Expression::Num(num.clone()),
Some(AstNode::Function(func)) => {
return Ok(Expression::Function(func.clone()).into())
}
Some(AstNode::Lambda(lambda)) => {
return Ok(Expression::Lambda(lambda.clone()).into())
}
Some(AstNode::If(if_expression)) => Expression::If(if_expression.clone()),
Some(AstNode::Block(block)) => Expression::Block(block.clone()),
Some(AstNode::Array(array)) => Expression::Array(array.clone()),
Some(AstNode::StructInitialisation(initialisation)) => {
Expression::StructInitialisation(initialisation.clone())
}
None | Some(_) => unreachable!(),
}
None | Some(_) => unreachable!(),
}
};

Expand Down Expand Up @@ -588,4 +618,76 @@ mod tests {
result
);
}

#[test]
fn test_simple_minus() {
let mut tokens = Lexer::new("-42").lex().expect("something is wrong").into();

let result = Expression::parse(&mut tokens);

assert_eq!(
Ok(Expression::Prefix(Prefix::Minus {
expr: Box::new(Expression::Num(Num(42)))
})
.into()),
result
);
}

#[test]
fn test_complex_minus() {
let mut tokens = Lexer::new("-someFunction()")
.lex()
.expect("something is wrong")
.into();

let result = Expression::parse(&mut tokens);

assert_eq!(
Ok(Expression::Prefix(Prefix::Minus {
expr: Box::new(Expression::Postfix(Postfix::Call {
expr: Box::new(Expression::Id(Id("someFunction".into()))),
args: vec![]
}))
})
.into()),
result
);
}

#[test]
fn test_simple_negation() {
let mut tokens = Lexer::new("!42").lex().expect("something is wrong").into();

let result = Expression::parse(&mut tokens);

assert_eq!(
Ok(Expression::Prefix(Prefix::Negation {
expr: Box::new(Expression::Num(Num(42)))
})
.into()),
result
);
}

#[test]
fn test_complex_negation() {
let mut tokens = Lexer::new("!someFunction()")
.lex()
.expect("something is wrong")
.into();

let result = Expression::parse(&mut tokens);

assert_eq!(
Ok(Expression::Prefix(Prefix::Negation {
expr: Box::new(Expression::Postfix(Postfix::Call {
expr: Box::new(Expression::Id(Id("someFunction".into()))),
args: vec![]
}))
})
.into()),
result
);
}
}
7 changes: 7 additions & 0 deletions src/parser/ast/expression/prefix.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use super::Expression;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Prefix {
Negation { expr: Box<Expression> },
Minus { expr: Box<Expression> },
}
4 changes: 4 additions & 0 deletions src/parser/combinators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@ impl<'a> Comb<'a, TokenKind, Terminal, AstNode> {

terminal_comb!(RETURN_KEYWORD, ReturnKeyword);

terminal_comb!(MINUS, Minus);

terminal_comb!(EXCLAMATION_MARK, ExclamationMark);

terminal_comb!(COLON, Colon);

terminal_comb!(COMMA, Comma);
Expand Down
Loading