Simplify code.

This commit is contained in:
Stephen Chung 2020-04-11 18:09:03 +08:00
parent 5848339d5a
commit bc0d43d68f
3 changed files with 102 additions and 116 deletions

View File

@ -172,11 +172,10 @@ impl FunctionsLib {
} }
/// Get a function definition from the `FunctionsLib`. /// Get a function definition from the `FunctionsLib`.
pub fn get_function(&self, name: &str, params: usize) -> Option<&FnDef> { pub fn get_function(&self, name: &str, params: usize) -> Option<&FnDef> {
if let Ok(n) = self.0.binary_search_by(|f| f.compare(name, params)) { self.0
Some(&self.0[n]) .binary_search_by(|f| f.compare(name, params))
} else { .ok()
None .map(|n| self.0[n].as_ref())
}
} }
/// Merge another `FunctionsLib` into this `FunctionsLib`. /// Merge another `FunctionsLib` into this `FunctionsLib`.
pub fn merge(&self, other: &Self) -> Self { pub fn merge(&self, other: &Self) -> Self {
@ -441,8 +440,7 @@ impl Engine<'_> {
const fn_lib: Option<&FunctionsLib> = None; const fn_lib: Option<&FunctionsLib> = None;
// First search in script-defined functions (can override built-in) // First search in script-defined functions (can override built-in)
if let Some(lib) = fn_lib { if let Some(fn_def) = fn_lib.and_then(|lib| lib.get_function(fn_name, args.len())) {
if let Some(fn_def) = lib.get_function(fn_name, args.len()) {
match scope { match scope {
// Extern scope passed in which is not empty // Extern scope passed in which is not empty
Some(scope) if scope.len() > 0 => { Some(scope) if scope.len() > 0 => {
@ -495,7 +493,6 @@ impl Engine<'_> {
} }
} }
} }
}
let spec = FnSpec { let spec = FnSpec {
name: fn_name.into(), name: fn_name.into(),
@ -510,25 +507,23 @@ impl Engine<'_> {
} }
// Search built-in's and external functions // Search built-in's and external functions
if let Some(functions) = &self.functions { if let Some(func) = self.functions.as_ref().and_then(|f| f.get(&spec)) {
if let Some(func) = functions.get(&spec) {
// Run external function // Run external function
let result = func(args, pos)?; let result = func(args, pos)?;
// See if the function match print/debug (which requires special processing) // See if the function match print/debug (which requires special processing)
return Ok(match fn_name { return match fn_name {
KEYWORD_PRINT if self.on_print.is_some() => { KEYWORD_PRINT if self.on_print.is_some() => Ok(self.on_print.as_ref().unwrap()(
self.on_print.as_ref().unwrap()(cast_to_string(result.as_ref(), pos)?) cast_to_string(result.as_ref(), pos)?,
.into_dynamic() )
} .into_dynamic()),
KEYWORD_DEBUG if self.on_debug.is_some() => { KEYWORD_DEBUG if self.on_debug.is_some() => Ok(self.on_debug.as_ref().unwrap()(
self.on_debug.as_ref().unwrap()(cast_to_string(result.as_ref(), pos)?) cast_to_string(result.as_ref(), pos)?,
.into_dynamic() )
} .into_dynamic()),
KEYWORD_PRINT | KEYWORD_DEBUG => ().into_dynamic(), KEYWORD_PRINT | KEYWORD_DEBUG => Ok(().into_dynamic()),
_ => result, _ => Ok(result),
}); };
}
} }
if let Some(prop) = extract_prop_from_getter(fn_name) { if let Some(prop) = extract_prop_from_getter(fn_name) {
@ -1603,8 +1598,7 @@ impl Engine<'_> {
let arr = self.eval_expr(scope, fn_lib, expr, level)?; let arr = self.eval_expr(scope, fn_lib, expr, level)?;
let tid = Any::type_id(arr.as_ref()); let tid = Any::type_id(arr.as_ref());
if let Some(type_iterators) = &self.type_iterators { if let Some(iter_fn) = self.type_iterators.as_ref().and_then(|t| t.get(&tid)) {
if let Some(iter_fn) = type_iterators.get(&tid) {
// Add the loop variable - variable name is copied // Add the loop variable - variable name is copied
// TODO - avoid copying variable name // TODO - avoid copying variable name
scope.push(name.clone(), ()); scope.push(name.clone(), ());
@ -1630,9 +1624,6 @@ impl Engine<'_> {
} else { } else {
Err(EvalAltResult::ErrorFor(expr.position())) Err(EvalAltResult::ErrorFor(expr.position()))
} }
} else {
Err(EvalAltResult::ErrorFor(expr.position()))
}
} }
// Continue statement // Continue statement
@ -1694,17 +1685,11 @@ impl Engine<'_> {
/// Map a type_name into a pretty-print name /// Map a type_name into a pretty-print name
pub(crate) fn map_type_name<'a>(&'a self, name: &'a str) -> &'a str { pub(crate) fn map_type_name<'a>(&'a self, name: &'a str) -> &'a str {
if self.type_names.is_none() {
name
} else {
self.type_names self.type_names
.as_ref() .as_ref()
.unwrap() .and_then(|list| list.get(name).map(String::as_str))
.get(name)
.map(String::as_str)
.unwrap_or(name) .unwrap_or(name)
} }
}
} }
/// Print/debug to stdout /// Print/debug to stdout

View File

@ -663,17 +663,19 @@ fn optimize<'a>(
.into_iter() .into_iter()
.enumerate() .enumerate()
.map(|(i, stmt)| { .map(|(i, stmt)| {
if let Stmt::Const(name, value, _) = &stmt { match stmt {
Stmt::Const(ref name, ref value, _) => {
// Load constants // Load constants
state.push_constant(name, value.as_ref().clone()); state.push_constant(name.as_ref(), value.as_ref().clone());
stmt // Keep it in the global scope stmt // Keep it in the global scope
} else { }
_ => {
// Keep all variable declarations at this level // Keep all variable declarations at this level
// and always keep the last return value // and always keep the last return value
let keep = matches!(stmt, Stmt::Let(_, _, _)) || i == num_statements - 1; let keep = matches!(stmt, Stmt::Let(_, _, _)) || i == num_statements - 1;
optimize_stmt(stmt, &mut state, keep) optimize_stmt(stmt, &mut state, keep)
} }
}
}) })
.collect(); .collect();

View File

@ -2192,11 +2192,10 @@ fn parse_binary_op<'a>(
let mut current_lhs = lhs; let mut current_lhs = lhs;
loop { loop {
let (current_precedence, bind_right) = if let Some((current_op, _)) = input.peek() { let (current_precedence, bind_right) = input.peek().map_or_else(
(current_op.precedence(), current_op.is_bind_right()) || (0, false),
} else { |(current_op, _)| (current_op.precedence(), current_op.is_bind_right()),
(0, false) );
};
// Bind left to the parent lhs expression if precedence is higher // Bind left to the parent lhs expression if precedence is higher
// If same precedence, then check if the operator binds right // If same precedence, then check if the operator binds right