While expression

This commit is contained in:
greg 2020-03-15 16:03:22 -07:00
parent 5da61658ec
commit 08ce718fb6
2 changed files with 24 additions and 7 deletions

View File

@ -65,7 +65,7 @@ fn bool_literal(text: &str) -> ParseResult<ExpressionKind> {
value(true, tag("true")), value(true, tag("true")),
value(false, tag("false")) value(false, tag("false"))
)); ));
map(p, ExpressionKind::BoolLiteral)(text) context("Bool literal", map(p, ExpressionKind::BoolLiteral))(text)
} }
fn number_literal(text: &str) -> ParseResult<ExpressionKind> { fn number_literal(text: &str) -> ParseResult<ExpressionKind> {
@ -121,8 +121,7 @@ fn literal(text: &str) -> ParseResult<ExpressionKind> {
} }
fn paren_expr(text: &str) -> ParseResult<ExpressionKind> { fn paren_expr(text: &str) -> ParseResult<ExpressionKind> {
use nom::character::complete::char; context("Paren expression", delimited(tag("("), ws(expression_kind), tag(")")))(text)
context("Paren expression", delimited(char('('), expression_kind, char(')')))(text)
} }
fn prefix_op(text: &str) -> ParseResult<PrefixOp> { fn prefix_op(text: &str) -> ParseResult<PrefixOp> {
@ -148,12 +147,30 @@ fn primary_expr(text: &str) -> ParseResult<ExpressionKind> {
alt(( alt((
if_expr, if_expr,
for_expr, for_expr,
while_expr,
literal, literal,
paren_expr, paren_expr,
identifier_expr, identifier_expr,
))(text) ))(text)
} }
fn while_expr(text: &str) -> ParseResult<ExpressionKind> {
let p = preceded(tag("while"), tuple((ws(while_cond), ws(block))));
let m = map(p, |(condition, body)| {
let condition = condition.map(Box::new);
ExpressionKind::WhileExpression {condition, body}
});
context("While expression", m)(text)
}
fn while_cond(text: &str) -> ParseResult<Option<Expression>> {
//TODO support is constructs?
context("While condition",
map(opt(ws(expression_kind)),
|maybe_expr_kind| maybe_expr_kind.map(|kind| Expression::new(ItemId::new(0), kind)))
)(text)
}
fn for_expr(text: &str) -> ParseResult<ExpressionKind> { fn for_expr(text: &str) -> ParseResult<ExpressionKind> {
//TODO do I need something like no struct literal here? //TODO do I need something like no struct literal here?
let en = alt(( let en = alt((

View File

@ -618,13 +618,13 @@ fn more_advanced_lambdas() {
#[test] #[test]
fn while_expr() { fn while_expr() {
parse_test_wrap_ast! { parse_test_wrap_ast! {
"while { }", "while { 3 }",
exst!(WhileExpression { condition: None, body: vec![] }) exst!(WhileExpression { condition: None, body: vec![ exst!(s "3")] })
} }
parse_test_wrap_ast! { parse_test_wrap_ast! {
"while a == b { }", "while a == b { 3 }",
exst!(WhileExpression { condition: Some(bx![ex![binexp!("==", val!("a"), val!("b"))]]), body: vec![] }) exst!(WhileExpression { condition: Some(bx![ex![binexp!("==", val!("a"), val!("b"))]]), body: vec![ exst!(s "3")] })
} }
} }