From 980a13ca4264ca4b6f3c68c0895f7a1efa185910 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Fri, 16 Apr 2021 12:04:33 +0800 Subject: [PATCH] Add switch case conditions. --- CHANGELOG.md | 1 + src/ast.rs | 116 +++++++++++++++------------------ src/engine.rs | 59 ++++++++--------- src/fn_call.rs | 2 +- src/optimize.rs | 167 ++++++++++++++++++++++++++++-------------------- src/parser.rs | 22 +++++-- tests/switch.rs | 39 +++++++++++ 7 files changed, 233 insertions(+), 173 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7dac623..a6b27309 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,7 @@ New features * String interpolation support is added via the `` `... ${`` ... ``} ...` `` syntax. * `FileModuleResolver` resolves relative paths under the parent path (i.e. the path holding the script that does the loading). This allows seamless cross-loading of scripts from a directory hierarchy instead of having all relative paths load from the current working directory. * Negative index to an array or string yields the appropriate element/character counting from the _end_. +* `switch` statement cases can now have an optional `if` clause. Version 0.19.15 diff --git a/src/ast.rs b/src/ast.rs index 5f5bb3a3..ba459184 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -187,10 +187,7 @@ impl AST { ) -> Self { Self { source: None, - body: StmtBlock { - statements: statements.into_iter().collect(), - pos: Position::NONE, - }, + body: StmtBlock(statements.into_iter().collect(), Position::NONE), functions: functions.into(), #[cfg(not(feature = "no_module"))] resolver: None, @@ -205,10 +202,7 @@ impl AST { ) -> Self { Self { source: Some(source.into()), - body: StmtBlock { - statements: statements.into_iter().collect(), - pos: Position::NONE, - }, + body: StmtBlock(statements.into_iter().collect(), Position::NONE), functions: functions.into(), #[cfg(not(feature = "no_module"))] resolver: None, @@ -245,7 +239,7 @@ impl AST { #[cfg(not(feature = "internals"))] #[inline(always)] pub(crate) fn statements(&self) -> &[Stmt] { - &self.body.statements + &self.body.0 } /// _(INTERNALS)_ Get the statements. /// Exported under the `internals` feature only. @@ -259,7 +253,7 @@ impl AST { #[cfg(not(feature = "no_optimize"))] #[inline(always)] pub(crate) fn statements_mut(&mut self) -> &mut StaticVec { - &mut self.body.statements + &mut self.body.0 } /// Get the internal shared [`Module`] containing all script-defined functions. #[cfg(not(feature = "internals"))] @@ -535,8 +529,7 @@ impl AST { let merged = match (body.is_empty(), other.body.is_empty()) { (false, false) => { let mut body = body.clone(); - body.statements - .extend(other.body.statements.iter().cloned()); + body.0.extend(other.body.0.iter().cloned()); body } (false, true) => body.clone(), @@ -550,9 +543,9 @@ impl AST { functions.merge_filtered(&other.functions, &filter); if let Some(source) = source { - Self::new_with_source(merged.statements, functions, source) + Self::new_with_source(merged.0, functions, source) } else { - Self::new(merged.statements, functions) + Self::new(merged.0, functions) } } /// Combine one [`AST`] with another. The second [`AST`] is consumed. @@ -612,9 +605,7 @@ impl AST { other: Self, filter: impl Fn(FnNamespace, FnAccess, bool, &str, usize) -> bool, ) -> &mut Self { - self.body - .statements - .extend(other.body.statements.into_iter()); + self.body.0.extend(other.body.0.into_iter()); if !other.functions.is_empty() { shared_make_mut(&mut self.functions).merge_filtered(&other.functions, &filter); @@ -705,7 +696,7 @@ impl AST { } } #[cfg(not(feature = "no_function"))] - for stmt in self.iter_fn_def().flat_map(|f| f.body.statements.iter()) { + for stmt in self.iter_fn_def().flat_map(|f| f.body.0.iter()) { if !stmt.walk(path, on_node) { return false; } @@ -833,30 +824,27 @@ impl<'a> From<&'a Expr> for ASTNode<'a> { /// /// This type is volatile and may change. #[derive(Clone, Hash, Default)] -pub struct StmtBlock { - pub statements: StaticVec, - pub pos: Position, -} +pub struct StmtBlock(pub StaticVec, pub Position); impl StmtBlock { /// Is this statements block empty? #[inline(always)] pub fn is_empty(&self) -> bool { - self.statements.is_empty() + self.0.is_empty() } /// Number of statements in this statements block. #[inline(always)] pub fn len(&self) -> usize { - self.statements.len() + self.0.len() } } impl fmt::Debug for StmtBlock { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Debug::fmt(&self.statements, f)?; - if !self.pos.is_none() { - write!(f, " @ {:?}", self.pos)?; + fmt::Debug::fmt(&self.0, f)?; + if !self.1.is_none() { + write!(f, " @ {:?}", self.1)?; } Ok(()) } @@ -874,10 +862,10 @@ pub enum Stmt { Noop(Position), /// `if` expr `{` stmt `}` `else` `{` stmt `}` If(Expr, Box<(StmtBlock, StmtBlock)>, Position), - /// `switch` expr `{` literal or _ `=>` stmt `,` ... `}` + /// `switch` expr `if` condition `{` literal or _ `=>` stmt `,` ... `}` Switch( Expr, - Box<(BTreeMap>, StmtBlock)>, + Box<(BTreeMap, StmtBlock)>>, StmtBlock)>, Position, ), /// `while` expr `{` stmt `}` @@ -930,18 +918,11 @@ impl From for StmtBlock { #[inline(always)] fn from(stmt: Stmt) -> Self { match stmt { - Stmt::Block(block, pos) => Self { - statements: block.into(), - pos, - }, - Stmt::Noop(pos) => Self { - statements: Default::default(), - pos, - }, + Stmt::Block(block, pos) => Self(block.into(), pos), + Stmt::Noop(pos) => Self(Default::default(), pos), _ => { let pos = stmt.position(); - let statements = vec![stmt].into(); - Self { statements, pos } + Self(vec![stmt].into(), pos) } } } @@ -1081,28 +1062,26 @@ impl Stmt { Self::Expr(expr) => expr.is_pure(), Self::If(condition, x, _) => { condition.is_pure() - && x.0.statements.iter().all(Stmt::is_pure) - && x.1.statements.iter().all(Stmt::is_pure) + && (x.0).0.iter().all(Stmt::is_pure) + && (x.1).0.iter().all(Stmt::is_pure) } Self::Switch(expr, x, _) => { expr.is_pure() - && x.0 - .values() - .flat_map(|block| block.statements.iter()) - .all(Stmt::is_pure) - && x.1.statements.iter().all(Stmt::is_pure) + && x.0.values().all(|block| { + block.0.as_ref().map(Expr::is_pure).unwrap_or(true) + && (block.1).0.iter().all(Stmt::is_pure) + }) + && (x.1).0.iter().all(Stmt::is_pure) } Self::While(condition, block, _) | Self::Do(block, condition, _, _) => { - condition.is_pure() && block.statements.iter().all(Stmt::is_pure) - } - Self::For(iterable, x, _) => { - iterable.is_pure() && x.1.statements.iter().all(Stmt::is_pure) + condition.is_pure() && block.0.iter().all(Stmt::is_pure) } + Self::For(iterable, x, _) => iterable.is_pure() && (x.1).0.iter().all(Stmt::is_pure), Self::Let(_, _, _, _) | Self::Const(_, _, _, _) | Self::Assignment(_, _) => false, Self::Block(block, _) => block.iter().all(|stmt| stmt.is_pure()), Self::Continue(_) | Self::Break(_) | Self::Return(_, _, _) => false, Self::TryCatch(x, _, _) => { - x.0.statements.iter().all(Stmt::is_pure) && x.2.statements.iter().all(Stmt::is_pure) + (x.0).0.iter().all(Stmt::is_pure) && (x.2).0.iter().all(Stmt::is_pure) } #[cfg(not(feature = "no_module"))] @@ -1168,12 +1147,12 @@ impl Stmt { if !e.walk(path, on_node) { return false; } - for s in &x.0.statements { + for s in &(x.0).0 { if !s.walk(path, on_node) { return false; } } - for s in &x.1.statements { + for s in &(x.1).0 { if !s.walk(path, on_node) { return false; } @@ -1183,12 +1162,17 @@ impl Stmt { if !e.walk(path, on_node) { return false; } - for s in x.0.values().flat_map(|block| block.statements.iter()) { - if !s.walk(path, on_node) { + for b in x.0.values() { + if !b.0.as_ref().map(|e| e.walk(path, on_node)).unwrap_or(true) { return false; } + for s in &(b.1).0 { + if !s.walk(path, on_node) { + return false; + } + } } - for s in &x.1.statements { + for s in &(x.1).0 { if !s.walk(path, on_node) { return false; } @@ -1198,7 +1182,7 @@ impl Stmt { if !e.walk(path, on_node) { return false; } - for s in &s.statements { + for s in &s.0 { if !s.walk(path, on_node) { return false; } @@ -1208,7 +1192,7 @@ impl Stmt { if !e.walk(path, on_node) { return false; } - for s in &x.1.statements { + for s in &(x.1).0 { if !s.walk(path, on_node) { return false; } @@ -1230,12 +1214,12 @@ impl Stmt { } } Self::TryCatch(x, _, _) => { - for s in &x.0.statements { + for s in &(x.0).0 { if !s.walk(path, on_node) { return false; } } - for s in &x.2.statements { + for s in &(x.2).0 { if !s.walk(path, on_node) { return false; } @@ -1681,8 +1665,8 @@ impl fmt::Debug for Expr { Self::Property(x) => write!(f, "Property({:?} @ {:?})", x.2.name, x.2.pos), Self::Stmt(x) => { f.write_str("Stmt")?; - f.debug_list().entries(x.statements.iter()).finish()?; - write!(f, " @ {:?}", x.pos) + f.debug_list().entries(x.0.iter()).finish()?; + write!(f, " @ {:?}", x.1) } Self::FnCall(x, pos) => { let mut ff = f.debug_struct("FnCall"); @@ -1796,7 +1780,7 @@ impl Expr { Self::Array(_, pos) => *pos, Self::Map(_, pos) => *pos, Self::Property(x) => (x.2).pos, - Self::Stmt(x) => x.pos, + Self::Stmt(x) => x.1, Self::Variable(_, pos, _) => *pos, Self::FnCall(_, pos) => *pos, @@ -1829,7 +1813,7 @@ impl Expr { Self::Map(_, pos) => *pos = new_pos, Self::Variable(_, pos, _) => *pos = new_pos, Self::Property(x) => (x.2).pos = new_pos, - Self::Stmt(x) => x.pos = new_pos, + Self::Stmt(x) => x.1 = new_pos, Self::FnCall(_, pos) => *pos = new_pos, Self::And(_, pos) | Self::Or(_, pos) => *pos = new_pos, Self::Unit(pos) => *pos = new_pos, @@ -1853,7 +1837,7 @@ impl Expr { x.lhs.is_pure() && x.rhs.is_pure() } - Self::Stmt(x) => x.statements.iter().all(Stmt::is_pure), + Self::Stmt(x) => x.0.iter().all(Stmt::is_pure), Self::Variable(_, _, _) => true, @@ -1959,7 +1943,7 @@ impl Expr { match self { Self::Stmt(x) => { - for s in &x.statements { + for s in &x.0 { if !s.walk(path, on_node) { return false; } diff --git a/src/engine.rs b/src/engine.rs index 3c2775d2..45001b93 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -1733,8 +1733,7 @@ impl Engine { // Statement block Expr::Stmt(x) if x.is_empty() => Ok(Dynamic::UNIT), Expr::Stmt(x) => { - let statements = &x.statements; - self.eval_stmt_block(scope, mods, state, lib, this_ptr, statements, true, level) + self.eval_stmt_block(scope, mods, state, lib, this_ptr, &x.0, true, level) } // lhs[idx_expr] @@ -2135,16 +2134,7 @@ impl Engine { // If statement Stmt::If(expr, x, _) => { - let ( - StmtBlock { - statements: if_stmt, - .. - }, - StmtBlock { - statements: else_stmt, - .. - }, - ) = x.as_ref(); + let (StmtBlock(if_stmt, _), StmtBlock(else_stmt, _)) = x.as_ref(); self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)? .as_bool() .map_err(|err| self.make_type_mismatch_err::(err, expr.position())) @@ -2180,16 +2170,33 @@ impl Engine { value.hash(hasher); let hash = hasher.finish(); - table.get(&hash).map(|t| { - let statements = &t.statements; + table.get(&hash).and_then(|t| { + if let Some(condition) = &t.0 { + match self + .eval_expr(scope, mods, state, lib, this_ptr, &condition, level) + .and_then(|v| { + v.as_bool().map_err(|err| { + self.make_type_mismatch_err::( + err, + condition.position(), + ) + }) + }) { + Ok(true) => (), + Ok(false) => return None, + Err(err) => return Some(Err(err)), + } + } - if !statements.is_empty() { + let statements = &(t.1).0; + + Some(if !statements.is_empty() { self.eval_stmt_block( scope, mods, state, lib, this_ptr, statements, true, level, ) } else { Ok(Dynamic::UNIT) - } + }) }) } else { // Non-hashable values never match any specific clause @@ -2197,7 +2204,7 @@ impl Engine { } .unwrap_or_else(|| { // Default match clause - let def_stmt = &def_stmt.statements; + let def_stmt = &def_stmt.0; if !def_stmt.is_empty() { self.eval_stmt_block( scope, mods, state, lib, this_ptr, def_stmt, true, level, @@ -2210,7 +2217,7 @@ impl Engine { // While loop Stmt::While(expr, body, _) => { - let body = &body.statements; + let body = &body.0; loop { let condition = if !expr.is_unit() { self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)? @@ -2243,7 +2250,7 @@ impl Engine { // Do loop Stmt::Do(body, expr, is_while, _) => { - let body = &body.statements; + let body = &body.0; loop { if !body.is_empty() { @@ -2277,7 +2284,7 @@ impl Engine { // For loop Stmt::For(expr, x, _) => { - let (Ident { name, .. }, StmtBlock { statements, pos }) = x.as_ref(); + let (Ident { name, .. }, StmtBlock(statements, pos)) = x.as_ref(); let iter_obj = self .eval_expr(scope, mods, state, lib, this_ptr, expr, level)? .flatten(); @@ -2360,17 +2367,7 @@ impl Engine { // Try/Catch statement Stmt::TryCatch(x, _, _) => { - let ( - StmtBlock { - statements: try_body, - .. - }, - err_var, - StmtBlock { - statements: catch_body, - .. - }, - ) = x.as_ref(); + let (StmtBlock(try_body, _), err_var, StmtBlock(catch_body, _)) = x.as_ref(); let result = self .eval_stmt_block(scope, mods, state, lib, this_ptr, try_body, true, level) diff --git a/src/fn_call.rs b/src/fn_call.rs index c0d2845e..c8c139a0 100644 --- a/src/fn_call.rs +++ b/src/fn_call.rs @@ -540,7 +540,7 @@ impl Engine { } // Evaluate the function - let body = &fn_def.body.statements; + let body = &fn_def.body.0; let result = self .eval_stmt_block(scope, mods, state, unified_lib, this_ptr, body, true, level) diff --git a/src/optimize.rs b/src/optimize.rs index 49a58a1c..38074208 100644 --- a/src/optimize.rs +++ b/src/optimize.rs @@ -416,73 +416,107 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { // if false { if_block } else { else_block } -> else_block Stmt::If(Expr::BoolConstant(false, _), x, _) => { state.set_dirty(); - let else_block = mem::take(&mut x.1.statements).into_vec(); + let else_block = mem::take(&mut (x.1).0).into_vec(); *stmt = match optimize_stmt_block(else_block, state, preserve_result, true, false) { - statements if statements.is_empty() => Stmt::Noop(x.1.pos), - statements => Stmt::Block(statements, x.1.pos), + statements if statements.is_empty() => Stmt::Noop((x.1).1), + statements => Stmt::Block(statements, (x.1).1), } } // if true { if_block } else { else_block } -> if_block Stmt::If(Expr::BoolConstant(true, _), x, _) => { state.set_dirty(); - let if_block = mem::take(&mut x.0.statements).into_vec(); + let if_block = mem::take(&mut (x.0).0).into_vec(); *stmt = match optimize_stmt_block(if_block, state, preserve_result, true, false) { - statements if statements.is_empty() => Stmt::Noop(x.0.pos), - statements => Stmt::Block(statements, x.0.pos), + statements if statements.is_empty() => Stmt::Noop((x.0).1), + statements => Stmt::Block(statements, (x.0).1), } } // if expr { if_block } else { else_block } Stmt::If(condition, x, _) => { optimize_expr(condition, state); - let if_block = mem::take(&mut x.0.statements).into_vec(); - x.0.statements = - optimize_stmt_block(if_block, state, preserve_result, true, false).into(); - let else_block = mem::take(&mut x.1.statements).into_vec(); - x.1.statements = - optimize_stmt_block(else_block, state, preserve_result, true, false).into(); + let if_block = mem::take(&mut (x.0).0).into_vec(); + (x.0).0 = optimize_stmt_block(if_block, state, preserve_result, true, false).into(); + let else_block = mem::take(&mut (x.1).0).into_vec(); + (x.1).0 = optimize_stmt_block(else_block, state, preserve_result, true, false).into(); } // switch const { ... } - Stmt::Switch(expr, x, pos) if expr.is_constant() => { - let value = expr.get_constant_value().unwrap(); + Stmt::Switch(match_expr, x, pos) if match_expr.is_constant() => { + let value = match_expr.get_constant_value().unwrap(); let hasher = &mut get_hasher(); value.hash(hasher); let hash = hasher.finish(); state.set_dirty(); - let table = &mut x.0; - let (statements, new_pos) = if let Some(block) = table.get_mut(&hash) { - let match_block = mem::take(&mut block.statements).into_vec(); - ( - optimize_stmt_block(match_block, state, true, true, false).into(), - block.pos, - ) - } else { - let def_block = mem::take(&mut x.1.statements).into_vec(); - ( - optimize_stmt_block(def_block, state, true, true, false).into(), - if x.1.pos.is_none() { *pos } else { x.1.pos }, - ) - }; + if let Some(block) = table.get_mut(&hash) { + if let Some(mut condition) = mem::take(&mut block.0) { + // switch const { case if condition => stmt, _ => def } => if condition { stmt } else { def } + optimize_expr(&mut condition, state); - *expr = Expr::Stmt(Box::new(StmtBlock { - statements, - pos: new_pos, - })); + let def_block = mem::take(&mut (x.1).0).into_vec(); + let def_stmt = optimize_stmt_block(def_block, state, true, true, false); + let def_pos = if (x.1).1.is_none() { *pos } else { (x.1).1 }; + + *stmt = Stmt::If( + condition, + Box::new(( + mem::take(&mut block.1), + Stmt::Block(def_stmt, def_pos).into(), + )), + match_expr.position(), + ); + } else { + // Promote the matched case + let StmtBlock(statements, new_pos) = mem::take(&mut block.1); + let statements = + optimize_stmt_block(statements.into_vec(), state, true, true, false); + *stmt = Stmt::Block(statements, new_pos); + } + } else { + // Promote the default case + let def_block = mem::take(&mut (x.1).0).into_vec(); + let def_stmt = optimize_stmt_block(def_block, state, true, true, false); + let def_pos = if (x.1).1.is_none() { *pos } else { (x.1).1 }; + *stmt = Stmt::Block(def_stmt, def_pos); + } } // switch - Stmt::Switch(expr, x, _) => { - optimize_expr(expr, state); + Stmt::Switch(match_expr, x, _) => { + optimize_expr(match_expr, state); x.0.values_mut().for_each(|block| { - let match_block = mem::take(&mut block.statements).into_vec(); - block.statements = - optimize_stmt_block(match_block, state, preserve_result, true, false).into() + let condition = if let Some(mut condition) = mem::take(&mut block.0) { + optimize_expr(&mut condition, state); + condition + } else { + Expr::Unit(Position::NONE) + }; + + match condition { + Expr::Unit(_) | Expr::BoolConstant(true, _) => (), + _ => { + block.0 = Some(condition); + + let match_block = mem::take(&mut (block.1).0).into_vec(); + (block.1).0 = + optimize_stmt_block(match_block, state, preserve_result, true, false) + .into(); + } + } }); - let def_block = mem::take(&mut x.1.statements).into_vec(); - x.1.statements = - optimize_stmt_block(def_block, state, preserve_result, true, false).into() + + // Remove false cases + while let Some((&key, _)) = x.0.iter().find(|(_, block)| match block.0 { + Some(Expr::BoolConstant(false, _)) => true, + _ => false, + }) { + state.set_dirty(); + x.0.remove(&key); + } + + let def_block = mem::take(&mut (x.1).0).into_vec(); + (x.1).0 = optimize_stmt_block(def_block, state, preserve_result, true, false).into() } // while false { block } -> Noop @@ -494,11 +528,11 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { Stmt::While(condition, body, _) => { optimize_expr(condition, state); - let block = mem::take(&mut body.statements).into_vec(); - body.statements = optimize_stmt_block(block, state, false, true, false).into(); + let block = mem::take(&mut body.0).into_vec(); + body.0 = optimize_stmt_block(block, state, false, true, false).into(); if body.len() == 1 { - match body.statements[0] { + match body.0[0] { // while expr { break; } -> { expr; } Stmt::Break(pos) => { // Only a single break statement - turn into running the guard expression once @@ -521,23 +555,23 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { Stmt::Do(body, Expr::BoolConstant(true, _), false, _) | Stmt::Do(body, Expr::BoolConstant(false, _), true, _) => { state.set_dirty(); - let block = mem::take(&mut body.statements).into_vec(); + let block = mem::take(&mut body.0).into_vec(); *stmt = Stmt::Block( optimize_stmt_block(block, state, false, true, false), - body.pos, + body.1, ); } // do { block } while|until expr Stmt::Do(body, condition, _, _) => { optimize_expr(condition, state); - let block = mem::take(&mut body.statements).into_vec(); - body.statements = optimize_stmt_block(block, state, false, true, false).into(); + let block = mem::take(&mut body.0).into_vec(); + body.0 = optimize_stmt_block(block, state, false, true, false).into(); } // for id in expr { block } Stmt::For(iterable, x, _) => { optimize_expr(iterable, state); - let body = mem::take(&mut x.1.statements).into_vec(); - x.1.statements = optimize_stmt_block(body, state, false, true, false).into(); + let body = mem::take(&mut (x.1).0).into_vec(); + (x.1).0 = optimize_stmt_block(body, state, false, true, false).into(); } // let id = expr; Stmt::Let(expr, _, _, _) => optimize_expr(expr, state), @@ -563,31 +597,31 @@ fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) { } } // try { pure try_block } catch ( var ) { catch_block } -> try_block - Stmt::TryCatch(x, _, _) if x.0.statements.iter().all(Stmt::is_pure) => { + Stmt::TryCatch(x, _, _) if (x.0).0.iter().all(Stmt::is_pure) => { // If try block is pure, there will never be any exceptions state.set_dirty(); - let try_block = mem::take(&mut x.0.statements).into_vec(); + let try_block = mem::take(&mut (x.0).0).into_vec(); *stmt = Stmt::Block( optimize_stmt_block(try_block, state, false, true, false), - x.0.pos, + (x.0).1, ); } // try { try_block } catch ( var ) { catch_block } Stmt::TryCatch(x, _, _) => { - let try_block = mem::take(&mut x.0.statements).into_vec(); - x.0.statements = optimize_stmt_block(try_block, state, false, true, false).into(); - let catch_block = mem::take(&mut x.2.statements).into_vec(); - x.2.statements = optimize_stmt_block(catch_block, state, false, true, false).into(); + let try_block = mem::take(&mut (x.0).0).into_vec(); + (x.0).0 = optimize_stmt_block(try_block, state, false, true, false).into(); + let catch_block = mem::take(&mut (x.2).0).into_vec(); + (x.2).0 = optimize_stmt_block(catch_block, state, false, true, false).into(); } // {} - Stmt::Expr(Expr::Stmt(x)) if x.statements.is_empty() => { + Stmt::Expr(Expr::Stmt(x)) if x.0.is_empty() => { state.set_dirty(); - *stmt = Stmt::Noop(x.pos); + *stmt = Stmt::Noop(x.1); } // {...}; Stmt::Expr(Expr::Stmt(x)) => { state.set_dirty(); - *stmt = Stmt::Block(mem::take(&mut x.statements).into_vec(), x.pos); + *stmt = Stmt::Block(mem::take(&mut x.0).into_vec(), x.1); } // expr; Stmt::Expr(expr) => optimize_expr(expr, state), @@ -610,13 +644,13 @@ fn optimize_expr(expr: &mut Expr, state: &mut State) { match expr { // {} - Expr::Stmt(x) if x.statements.is_empty() => { state.set_dirty(); *expr = Expr::Unit(x.pos) } + Expr::Stmt(x) if x.0.is_empty() => { state.set_dirty(); *expr = Expr::Unit(x.1) } // { stmt; ... } - do not count promotion as dirty because it gets turned back into an array Expr::Stmt(x) => { - x.statements = optimize_stmt_block(mem::take(&mut x.statements).into_vec(), state, true, true, false).into(); + x.0 = optimize_stmt_block(mem::take(&mut x.0).into_vec(), state, true, true, false).into(); // { Stmt(Expr) } - promote - match x.statements.as_mut() { + match x.0.as_mut() { [ Stmt::Expr(e) ] => { state.set_dirty(); *expr = mem::take(e); } _ => () } @@ -1034,19 +1068,14 @@ pub fn optimize_into_ast( .map(|fn_def| { let mut fn_def = crate::fn_native::shared_take_or_clone(fn_def); - let pos = fn_def.body.pos; - - let mut body = fn_def.body.statements.into_vec(); + let mut body = fn_def.body.0.into_vec(); // Optimize the function body let state = &mut State::new(engine, lib2, level); body = optimize_stmt_block(body, state, true, true, true); - fn_def.body = StmtBlock { - statements: body.into(), - pos, - }; + fn_def.body.0 = body.into(); fn_def }) diff --git a/src/parser.rs b/src/parser.rs index ab7902dd..0f0270fb 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -808,14 +808,14 @@ fn parse_switch( } } - let mut table = BTreeMap::>::new(); + let mut table = BTreeMap::, StmtBlock)>>::new(); let mut def_pos = Position::NONE; let mut def_stmt = None; loop { const MISSING_RBRACE: &str = "to end this switch block"; - let expr = match input.peek().unwrap() { + let (expr, condition) = match input.peek().unwrap() { (Token::RightBrace, _) => { eat_token(input, Token::RightBrace); break; @@ -829,11 +829,21 @@ fn parse_switch( (Token::Underscore, pos) if def_stmt.is_none() => { def_pos = *pos; eat_token(input, Token::Underscore); - None + (None, None) } (Token::Underscore, pos) => return Err(PERR::DuplicatedSwitchCase.into_err(*pos)), _ if def_stmt.is_some() => return Err(PERR::WrongSwitchDefaultCase.into_err(def_pos)), - _ => Some(parse_expr(input, state, lib, settings.level_up())?), + + _ => { + let case_expr = Some(parse_expr(input, state, lib, settings.level_up())?); + + let condition = if match_token(input, Token::If).0 { + Some(parse_expr(input, state, lib, settings.level_up())?) + } else { + None + }; + (case_expr, condition) + } }; let hash = if let Some(expr) = expr { @@ -871,7 +881,7 @@ fn parse_switch( let need_comma = !stmt.is_self_terminated(); def_stmt = if let Some(hash) = hash { - table.insert(hash, Box::new(stmt.into())); + table.insert(hash, Box::new((condition, stmt.into()))); None } else { Some(stmt.into()) @@ -2878,7 +2888,7 @@ fn make_curry_from_externals( let mut statements: StaticVec<_> = Default::default(); statements.extend(externals.into_iter().map(Stmt::Share)); statements.push(Stmt::Expr(expr)); - Expr::Stmt(Box::new(StmtBlock { statements, pos })) + Expr::Stmt(Box::new(StmtBlock(statements, pos))) } /// Parse an anonymous function definition. diff --git a/tests/switch.rs b/tests/switch.rs index 537dfd04..38ddebbf 100644 --- a/tests/switch.rs +++ b/tests/switch.rs @@ -67,6 +67,45 @@ fn test_switch() -> Result<(), Box> { Ok(()) } +#[test] +fn test_switch_condition() -> Result<(), Box> { + let engine = Engine::new(); + let mut scope = Scope::new(); + scope.push("x", 42 as INT); + + assert_eq!( + engine.eval_with_scope::( + &mut scope, + r" + switch x / 2 { + 21 if x > 40 => 1, + 0 if x < 100 => 2, + 1 => 3, + _ => 9 + } + " + )?, + 1 + ); + + assert_eq!( + engine.eval_with_scope::( + &mut scope, + r" + switch x / 2 { + 21 if x < 40 => 1, + 0 if x < 100 => 2, + 1 => 3, + _ => 9 + } + " + )?, + 9 + ); + + Ok(()) +} + #[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_object"))] mod test_switch_enum {