parser: shorthand switch

This commit is contained in:
Ryan Chandler 2022-09-22 20:38:53 +01:00
parent af915e4575
commit 1d377936e0
No known key found for this signature in database
GPG Key ID: F113BCADDB3B0CCA
2 changed files with 22 additions and 3 deletions

View File

@ -1084,6 +1084,7 @@ fn parse_int(buffer: &str, base: u32) -> Result<TokenKind, LexerError> {
fn identifier_to_keyword(ident: &[u8]) -> Option<TokenKind> {
Some(match ident {
b"endswitch" => TokenKind::EndSwitch,
b"endfor" => TokenKind::EndFor,
b"endwhile" => TokenKind::EndWhile,
b"endforeach" => TokenKind::EndForeach,

View File

@ -770,11 +770,17 @@ impl Parser {
self.rparen()?;
self.lbrace()?;
let end_token = if self.current.kind == TokenKind::Colon {
self.colon()?;
TokenKind::EndSwitch
} else {
self.lbrace()?;
TokenKind::RightBrace
};
let mut cases = Vec::new();
loop {
if self.current.kind == TokenKind::RightBrace {
if self.current.kind == end_token {
break;
}
@ -828,7 +834,12 @@ impl Parser {
}
}
self.rbrace()?;
if end_token == TokenKind::EndSwitch {
expect!(self, TokenKind::EndSwitch, "expected endswitch");
self.semi()?;
} else {
self.rbrace()?;
}
Statement::Switch { condition, cases }
}
@ -5200,6 +5211,13 @@ mod tests {
]);
}
#[test]
fn shorthand_switch() {
assert_ast("<?php switch ($a): endswitch;", &[
Statement::Switch { condition: Expression::Variable { name: "a".into() }, cases: vec![] }
]);
}
fn assert_ast(source: &str, expected: &[Statement]) {
let mut lexer = Lexer::new(None);
let tokens = lexer.tokenize(source).unwrap();