1
0

Parse blocks

This commit is contained in:
Jeff 2024-02-28 18:16:25 -05:00
parent 65ee472a4a
commit 95d9a720a3
2 changed files with 66 additions and 3 deletions

View File

@ -44,10 +44,14 @@ pub fn lexer<'src>() -> impl Parser<
let integer = just('-') let integer = just('-')
.or_not() .or_not()
.then(text::int(10).padded()) .then(text::int(10))
.to_slice() .to_slice()
.map(|text: &str| { .map(|text: &str| {
let integer = text.parse::<i64>().unwrap(); let integer = if let Ok(integer) = text.parse::<i64>() {
integer
} else {
panic!("Failed to parse {text} as integer.");
};
Token::Integer(integer) Token::Integer(integer)
}); });

View File

@ -120,7 +120,15 @@ fn parser<'tokens, 'src: 'tokens>() -> impl Parser<
}) })
.boxed(); .boxed();
choice([assignment, expression_statement]) let block = statement
.clone()
.separated_by(just(Token::Control(";")).or_not())
.collect()
.delimited_by(just(Token::Control("{")), just(Token::Control("}")))
.map(|statements| Statement::Block(Block::new(statements)))
.boxed();
choice([assignment, expression_statement, block])
}); });
statement statement
@ -144,6 +152,57 @@ mod tests {
use super::*; use super::*;
#[test]
fn block() {
assert_eq!(
parse(&lex("{ x }").unwrap()).unwrap()[0].0,
Statement::Block(Block::new(vec![Statement::Expression(
Expression::Identifier(Identifier::new("x"))
),]))
);
assert_eq!(
parse(
&lex("
{
x;
y;
z
}
")
.unwrap()
)
.unwrap()[0]
.0,
Statement::Block(Block::new(vec![
Statement::Expression(Expression::Identifier(Identifier::new("x"))),
Statement::Expression(Expression::Identifier(Identifier::new("y"))),
Statement::Expression(Expression::Identifier(Identifier::new("z"))),
]))
);
assert_eq!(
parse(
&lex("
{
1 == 1
z
}
")
.unwrap()
)
.unwrap()[0]
.0,
Statement::Block(Block::new(vec![
Statement::Expression(Expression::Logic(Box::new(Logic::Equal(
Expression::Value(ValueNode::Integer(1)),
Expression::Value(ValueNode::Integer(1))
)))),
Statement::Expression(Expression::Identifier(Identifier::new("z"))),
]))
);
}
#[test] #[test]
fn identifier() { fn identifier() {
assert_eq!( assert_eq!(