From b7b94335cc3b2d5650a385e1f4a439a7ef6d30ff Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Fri, 5 Mar 2021 21:43:28 +0200 Subject: refactor(tazjin/rlox): Refactor Compiler::consume into a macro Making this function a macro instead makes it possible to match arbitrary token kinds, even the ones that carry data, without changing the syntax too much. Change-Id: I5cda9e36d6833bd9c259f7d4d8340db6e783b4e8 Reviewed-on: https://cl.tvl.fyi/c/depot/+/2593 Reviewed-by: tazjin Tested-by: BuildkiteCI --- users/tazjin/rlox/src/bytecode/compiler.rs | 39 ++++++++++++++++-------------- 1 file changed, 21 insertions(+), 18 deletions(-) (limited to 'users') diff --git a/users/tazjin/rlox/src/bytecode/compiler.rs b/users/tazjin/rlox/src/bytecode/compiler.rs index 8e70067e3182..f2fdeb0e9feb 100644 --- a/users/tazjin/rlox/src/bytecode/compiler.rs +++ b/users/tazjin/rlox/src/bytecode/compiler.rs @@ -153,6 +153,15 @@ fn rule_for>(token: &TokenKind) -> ParseRule { } } +macro_rules! consume { + ( $self:ident, $expected:pat, $err:expr ) => { + match $self.current().kind { + $expected => $self.advance(), + _ => $self.error_at($self.current().line, $err), + } + }; +} + impl> Compiler { fn compile(&mut self) -> LoxResult<()> { self.advance(); @@ -193,9 +202,10 @@ impl> Compiler { fn print_statement(&mut self) -> LoxResult<()> { self.expression()?; - self.consume( - &TokenKind::Semicolon, - ErrorKind::ExpectedToken("Expected ';' after value"), + consume!( + self, + TokenKind::Semicolon, + ErrorKind::ExpectedToken("Expected ';' after value") ); self.emit_op(OpCode::OpPrint); Ok(()) @@ -203,9 +213,10 @@ impl> Compiler { fn expression_statement(&mut self) -> LoxResult<()> { self.expression()?; - self.consume( - &TokenKind::Semicolon, - ErrorKind::ExpectedToken("Expected ';' after expression"), + consume!( + self, + TokenKind::Semicolon, + ErrorKind::ExpectedToken("Expected ';' after expression") ); self.emit_op(OpCode::OpPop); Ok(()) @@ -222,9 +233,10 @@ impl> Compiler { fn grouping(&mut self) -> LoxResult<()> { self.expression()?; - self.consume( - &TokenKind::RightParen, - ErrorKind::ExpectedToken("Expected ')' after expression"), + consume!( + self, + TokenKind::RightParen, + ErrorKind::ExpectedToken("Expected ')' after expression") ); Ok(()) } @@ -334,15 +346,6 @@ impl> Compiler { Ok(()) } - fn consume(&mut self, expected: &TokenKind, err: ErrorKind) { - if self.current().kind == *expected { - self.advance(); - return; - } - - self.error_at(self.current().line, err); - } - fn current_chunk(&mut self) -> &mut Chunk { &mut self.chunk } -- cgit 1.4.1