diff --git a/src/main.rs b/src/main.rs index 6a56c01..aee4801 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,8 @@ fn main() { pub fn main() { if thing { print("Hello, world!") + } else if other_thing { + print("Goodbye, world!") } } "#; diff --git a/src/parser.rs b/src/parser.rs index 6f92b08..fbe43c8 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -720,14 +720,39 @@ where self.no_braces.pop(); self.expect(TokenKind::LeftBrace, &["a block"])?; - let (body, end) = self.sequence(Self::parse_statement, None, TokenKind::RightBrace)?; + let (body, mut end) = self.sequence(Self::parse_statement, None, TokenKind::RightBrace)?; + + let mut else_branch = None; + + if self.maybe_consume(&TokenKind::Else).is_some() { + let next = self.expect_token(&["an if statement", "a block"])?; + let else_ = match next.kind { + TokenKind::If => self.parse_if(next.location.start)?, + TokenKind::LeftBrace => { + let (statements, end) = + self.sequence(Self::parse_statement, None, TokenKind::RightBrace)?; + Expression::Block { + location: Span::new(next.location.start, end), + statements, + } + } + _ => { + return Err(Error::UnexpectedToken { + token: next, + expected: vec!["an if statement", "a block"], + }); + } + }; - // TODO: else + end = else_.location().end; + else_branch = Some(Box::new(else_)); + } Ok(Expression::If { location: Span { start, end }, condition: Box::new(condition), body, + else_branch, }) } diff --git a/src/parser/ast.rs b/src/parser/ast.rs index c35c148..dd1e2ce 100644 --- a/src/parser/ast.rs +++ b/src/parser/ast.rs @@ -199,6 +199,7 @@ pub enum Expression { location: Span, condition: Box, body: Vec>, + else_branch: Option>, }, Match { location: Span,