Skip to content
This repository was archived by the owner on Jul 24, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions phpast/samples/if.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

if($foo) {
return $foo;
} else {
return $foo;
}
1 change: 1 addition & 0 deletions trunk_parser/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ pub enum Statement {
If {
condition: Expression,
then: Block,
r#else: Option<Block>
},
Return {
value: Option<Expression>,
Expand Down
42 changes: 35 additions & 7 deletions trunk_parser/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,22 @@ impl Parser {
expect!(self, TokenKind::RightBrace, "expected }");
}

Statement::If { condition, then }
if self.current.kind != TokenKind::Else {
return Ok(Statement::If { condition, then, r#else: None });
}

expect!(self, TokenKind::Else, "expected else");

expect!(self, TokenKind::LeftBrace, "expected {");

let mut r#else = Block::new();
while ! self.is_eof() && self.current.kind != TokenKind::RightBrace {
r#else.push(self.statement()?);
}

expect!(self, TokenKind::RightBrace, "expected }");

Statement::If { condition, then, r#else: Some(r#else) }
},
TokenKind::Class => self.class()?,
TokenKind::Echo => {
Expand Down Expand Up @@ -1117,6 +1132,7 @@ mod tests {
then: vec![
Statement::Return { value: Some(Expression::Variable("n".into())) }
],
r#else: None
},
Statement::Return {
value: Some(Expression::Infix(
Expand Down Expand Up @@ -1149,16 +1165,28 @@ mod tests {

#[test]
fn one_liner_if_statement() {
assert_ast("\
<?php
assert_ast("<?php if($foo) return $foo;", &[
Statement::If {
condition: Expression::Variable("foo".into()),
then: vec![
Statement::Return { value: Some(Expression::Variable("foo".into())) }
],
r#else: None
},
]);
}

if($name)
return $name;", &[
#[test]
fn if_else_statement() {
assert_ast("<?php if($foo) { return $foo; } else { return $foo; }", &[
Statement::If {
condition: Expression::Variable("name".into()),
condition: Expression::Variable("foo".into()),
then: vec![
Statement::Return { value: Some(Expression::Variable("name".into())) }
Statement::Return { value: Some(Expression::Variable("foo".into())) }
],
r#else: Some(vec![
Statement::Return { value: Some(Expression::Variable("foo".into())) }
])
},
]);
}
Expand Down