From 1d377936e0dc2fa998c96225adbf574f3606a768 Mon Sep 17 00:00:00 2001 From: Ryan Chandler Date: Thu, 22 Sep 2022 20:38:53 +0100 Subject: [PATCH] parser: shorthand switch --- trunk_lexer/src/lexer.rs | 1 + trunk_parser/src/parser/mod.rs | 24 +++++++++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/trunk_lexer/src/lexer.rs b/trunk_lexer/src/lexer.rs index 71ae496..372eaae 100644 --- a/trunk_lexer/src/lexer.rs +++ b/trunk_lexer/src/lexer.rs @@ -1084,6 +1084,7 @@ fn parse_int(buffer: &str, base: u32) -> Result { fn identifier_to_keyword(ident: &[u8]) -> Option { Some(match ident { + b"endswitch" => TokenKind::EndSwitch, b"endfor" => TokenKind::EndFor, b"endwhile" => TokenKind::EndWhile, b"endforeach" => TokenKind::EndForeach, diff --git a/trunk_parser/src/parser/mod.rs b/trunk_parser/src/parser/mod.rs index 39362c9..24a1c59 100644 --- a/trunk_parser/src/parser/mod.rs +++ b/trunk_parser/src/parser/mod.rs @@ -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("