From e37fc83ce9705eb8af2c7b7bfb927b38cf382726 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edvard=20Th=C3=B6rnros?= Date: Tue, 9 Feb 2021 17:29:59 +0100 Subject: simplify the parse_branch --- src/compiler.rs | 72 ++++++++++++++++++++++++++++++++------------------------- 1 file changed, 40 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/compiler.rs b/src/compiler.rs index 2ca6159..3a64ac6 100644 --- a/src/compiler.rs +++ b/src/compiler.rs @@ -41,32 +41,39 @@ macro_rules! expect { macro_rules! parse_branch { ($compiler:expr, $block:expr, [ $( $call:expr ),* ]) => { - let block_length = $block.ops.len(); - let token_length = $compiler.curr; - let num_errors = $compiler.errors.len(); - let mut stored_errors = Vec::new(); - let mut success = false; - // We risk getting a lot of errors if we are in an invalid state - // when we start the parse. - while !$compiler.panic { - $( - $call; - if !$compiler.panic { - success = true; - break; + { + let block_length = $block.ops.len(); + let token_length = $compiler.curr; + let num_errors = $compiler.errors.len(); + let mut stored_errors = Vec::new(); + + // Closures for early return on success. + let success = (|| { + // We risk getting a lot of errors if we are in an invalid state + // when we start the parse. + if $compiler.panic { + return false; } - $compiler.panic = false; - $compiler.curr = token_length; - let thrown_errors = $compiler.errors.len() - num_errors - 1; - stored_errors.extend($compiler.errors.split_off(thrown_errors)); - $block.ops.truncate(block_length); - )* - break; + $( + $call; + if !$compiler.panic { + return true; + } + $compiler.panic = false; + $compiler.curr = token_length; + let thrown_errors = $compiler.errors.len() - num_errors - 1; + stored_errors.extend($compiler.errors.split_off(thrown_errors)); + $block.ops.truncate(block_length); + )* + false + })(); + + if !success { + $compiler.errors.extend(stored_errors); + } + success } - if !success { - $compiler.errors.extend(stored_errors); - } }; ($compiler:expr, $block:expr, $call:expr) => { @@ -75,23 +82,24 @@ macro_rules! parse_branch { let token_length = $compiler.curr; let num_errors = $compiler.errors.len(); let mut stored_errors = Vec::new(); - let mut success = false; - // We risk getting a lot of errors if we are in an invalid state - // when we start the parse. - while !$compiler.panic { + // Closures for early return on success. + (|| { + // We risk getting a lot of errors if we are in an invalid state + // when we start the parse. + if $compiler.panic { + return false; + } $call; if !$compiler.panic { - success = true; - break; + return true; } $compiler.panic = false; $compiler.curr = token_length; let thrown_errors = $compiler.errors.len() - num_errors - 1; stored_errors.extend($compiler.errors.split_off(thrown_errors)); $block.ops.truncate(block_length); - break; - } - success + false + })() } }; } -- cgit v1.2.1