mirror of
https://github.com/danog/parser.git
synced 2024-11-30 04:29:13 +01:00
Merge pull request #2 from Dohxis/parser/if-else-statements
This commit is contained in:
commit
074a84c42c
7
phpast/samples/if.php
Normal file
7
phpast/samples/if.php
Normal file
@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
if($foo) {
|
||||
return $foo;
|
||||
} else {
|
||||
return $foo;
|
||||
}
|
@ -176,6 +176,7 @@ pub enum Statement {
|
||||
If {
|
||||
condition: Expression,
|
||||
then: Block,
|
||||
r#else: Option<Block>
|
||||
},
|
||||
Return {
|
||||
value: Option<Expression>,
|
||||
|
@ -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 => {
|
||||
@ -1194,6 +1209,7 @@ mod tests {
|
||||
then: vec![
|
||||
Statement::Return { value: Some(Expression::Variable("n".into())) }
|
||||
],
|
||||
r#else: None
|
||||
},
|
||||
Statement::Return {
|
||||
value: Some(Expression::Infix(
|
||||
@ -1226,16 +1242,28 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn one_liner_if_statement() {
|
||||
assert_ast("\
|
||||
<?php
|
||||
|
||||
if($name)
|
||||
return $name;", &[
|
||||
assert_ast("<?php if($foo) 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: None
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn if_else_statement() {
|
||||
assert_ast("<?php if($foo) { return $foo; } else { return $foo; }", &[
|
||||
Statement::If {
|
||||
condition: Expression::Variable("foo".into()),
|
||||
then: vec![
|
||||
Statement::Return { value: Some(Expression::Variable("foo".into())) }
|
||||
],
|
||||
r#else: Some(vec![
|
||||
Statement::Return { value: Some(Expression::Variable("foo".into())) }
|
||||
])
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user