From 58c198776f6e2a7a72d1a4a3d13492a18d92ba4f Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Thu, 25 Jun 2020 11:07:46 +0800 Subject: [PATCH] Code cleanup. --- src/api.rs | 8 ++--- src/engine.rs | 58 +++++++++++++++++------------------- src/error.rs | 2 ++ src/lib.rs | 6 ++++ src/module.rs | 6 ++-- src/optimize.rs | 2 +- src/packages/string_basic.rs | 20 ++++++------- src/parser.rs | 2 ++ src/result.rs | 1 + src/scope.rs | 2 +- src/token.rs | 4 +++ 11 files changed, 61 insertions(+), 50 deletions(-) diff --git a/src/api.rs b/src/api.rs index ebfb699c..cce53dd3 100644 --- a/src/api.rs +++ b/src/api.rs @@ -2,8 +2,8 @@ use crate::any::{Dynamic, Variant}; use crate::engine::{ - get_script_function_by_signature, make_getter, make_setter, Engine, State, FUNC_INDEXER_GET, - FUNC_INDEXER_SET, + get_script_function_by_signature, make_getter, make_setter, Engine, State, FN_IDX_GET, + FN_IDX_SET, }; use crate::error::ParseError; use crate::fn_call::FuncArgs; @@ -323,7 +323,7 @@ impl Engine { U: Variant + Clone, X: Variant + Clone, { - self.register_fn(FUNC_INDEXER_GET, callback); + self.register_fn(FN_IDX_GET, callback); } /// Register an index setter for a registered type with the `Engine`. @@ -371,7 +371,7 @@ impl Engine { U: Variant + Clone, X: Variant + Clone, { - self.register_fn(FUNC_INDEXER_SET, callback); + self.register_fn(FN_IDX_SET, callback); } /// Shorthand for register both index getter and setter functions for a registered type with the `Engine`. diff --git a/src/engine.rs b/src/engine.rs index 6e993a8b..92704b24 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -71,15 +71,16 @@ pub const KEYWORD_PRINT: &str = "print"; pub const KEYWORD_DEBUG: &str = "debug"; pub const KEYWORD_TYPE_OF: &str = "type_of"; pub const KEYWORD_EVAL: &str = "eval"; -pub const FUNC_TO_STRING: &str = "to_string"; -pub const FUNC_GETTER: &str = "get$"; -pub const FUNC_SETTER: &str = "set$"; -pub const FUNC_INDEXER_GET: &str = "$index$get$"; -pub const FUNC_INDEXER_SET: &str = "$index$set$"; +pub const FN_TO_STRING: &str = "to_string"; +pub const FN_GET: &str = "get$"; +pub const FN_SET: &str = "set$"; +pub const FN_IDX_GET: &str = "$index$get$"; +pub const FN_IDX_SET: &str = "$index$set$"; /// A type specifying the method of chaining. #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] enum ChainType { + None, Index, Dot, } @@ -338,15 +339,15 @@ impl Default for Engine { /// Make getter function pub fn make_getter(id: &str) -> String { - format!("{}{}", FUNC_GETTER, id) + format!("{}{}", FN_GET, id) } /// Extract the property name from a getter function name. fn extract_prop_from_getter(fn_name: &str) -> Option<&str> { #[cfg(not(feature = "no_object"))] { - if fn_name.starts_with(FUNC_GETTER) { - Some(&fn_name[FUNC_GETTER.len()..]) + if fn_name.starts_with(FN_GET) { + Some(&fn_name[FN_GET.len()..]) } else { None } @@ -359,15 +360,15 @@ fn extract_prop_from_getter(fn_name: &str) -> Option<&str> { /// Make setter function pub fn make_setter(id: &str) -> String { - format!("{}{}", FUNC_SETTER, id) + format!("{}{}", FN_SET, id) } /// Extract the property name from a setter function name. fn extract_prop_from_setter(fn_name: &str) -> Option<&str> { #[cfg(not(feature = "no_object"))] { - if fn_name.starts_with(FUNC_SETTER) { - Some(&fn_name[FUNC_SETTER.len()..]) + if fn_name.starts_with(FN_SET) { + Some(&fn_name[FN_SET.len()..]) } else { None } @@ -802,7 +803,7 @@ impl Engine { } // index getter function not found? - if fn_name == FUNC_INDEXER_GET && args.len() == 2 { + if fn_name == FN_IDX_GET && args.len() == 2 { return Err(Box::new(EvalAltResult::ErrorFunctionNotFound( format!( "{} [{}]", @@ -814,7 +815,7 @@ impl Engine { } // index setter function not found? - if fn_name == FUNC_INDEXER_SET { + if fn_name == FN_IDX_SET { return Err(Box::new(EvalAltResult::ErrorFunctionNotFound( format!( "{} [{}]=", @@ -1022,17 +1023,18 @@ impl Engine { level: usize, mut new_val: Option, ) -> Result<(Dynamic, bool), Box> { + if chain_type == ChainType::None { + panic!(); + } + let is_ref = target.is_ref(); let is_value = target.is_value(); - #[inline(always)] - fn get_chain_type(expr: &Expr) -> ChainType { - match expr { - Expr::Index(_) => ChainType::Index, - Expr::Dot(_) => ChainType::Dot, - _ => unreachable!(), - } - } + let next_chain = match rhs { + Expr::Index(_) => ChainType::Index, + Expr::Dot(_) => ChainType::Dot, + _ => ChainType::None, + }; // Pop the last index value let mut idx_val = idx_values.pop(); @@ -1046,7 +1048,6 @@ impl Engine { // xxx[idx].expr... | xxx[idx][expr]... Expr::Dot(x) | Expr::Index(x) => { let (idx, expr, pos) = x.as_ref(); - let next_chain = get_chain_type(rhs); let idx_pos = idx.position(); let this_ptr = &mut self .get_indexed_mut(state, lib, target, idx_val, idx_pos, false)?; @@ -1064,17 +1065,16 @@ impl Engine { // Indexed value is an owned value - the only possibility is an indexer // Try to call an index setter Ok(this_ptr) if this_ptr.is_value() => { - let fn_name = FUNC_INDEXER_SET; let args = &mut [target.as_mut(), &mut idx_val2, &mut new_val.unwrap()]; self.exec_fn_call( - state, lib, fn_name, true, 0, args, is_ref, None, 0, + state, lib, FN_IDX_SET, true, 0, args, is_ref, None, 0, ) .or_else(|err| match *err { // If there is no index setter, no need to set it back because the indexer is read-only EvalAltResult::ErrorFunctionNotFound(s, _) - if s == FUNC_INDEXER_SET => + if s == FN_IDX_SET => { Ok(Default::default()) } @@ -1090,7 +1090,6 @@ impl Engine { Err(err) => match *err { // No index getter - try to call an index setter EvalAltResult::ErrorIndexingType(_, _) => { - let fn_name = FUNC_INDEXER_SET; let args = &mut [ target.as_mut(), &mut idx_val2, @@ -1098,7 +1097,7 @@ impl Engine { ]; self.exec_fn_call( - state, lib, fn_name, true, 0, args, is_ref, None, 0, + state, lib, FN_IDX_SET, true, 0, args, is_ref, None, 0, )?; } // Error @@ -1189,7 +1188,6 @@ impl Engine { // {xxx:map}.prop[expr] | {xxx:map}.prop.expr Expr::Index(x) | Expr::Dot(x) if target.is::() => { let (prop, expr, pos) = x.as_ref(); - let next_chain = get_chain_type(rhs); let mut val = if let Expr::Property(p) = prop { let ((prop, _, _), _) = p.as_ref(); @@ -1207,7 +1205,6 @@ impl Engine { // xxx.prop[expr] | xxx.prop.expr Expr::Index(x) | Expr::Dot(x) => { let (prop, expr, pos) = x.as_ref(); - let next_chain = get_chain_type(rhs); let args = &mut [target.as_mut(), &mut Default::default()]; let (mut val, updated) = if let Expr::Property(p) = prop { @@ -1454,10 +1451,9 @@ impl Engine { #[cfg(not(feature = "no_index"))] _ => { - let fn_name = FUNC_INDEXER_GET; let type_name = self.map_type_name(val.type_name()); let args = &mut [val, &mut idx]; - self.exec_fn_call(state, lib, fn_name, true, 0, args, is_ref, None, 0) + self.exec_fn_call(state, lib, FN_IDX_GET, true, 0, args, is_ref, None, 0) .map(|(v, _)| v.into()) .map_err(|_| { Box::new(EvalAltResult::ErrorIndexingType( diff --git a/src/error.rs b/src/error.rs index ce8615ed..f4792f11 100644 --- a/src/error.rs +++ b/src/error.rs @@ -7,6 +7,7 @@ use crate::stdlib::{boxed::Box, char, error::Error, fmt, string::String}; /// Error when tokenizing the script text. #[derive(Debug, Eq, PartialEq, Clone, Hash)] +#[non_exhaustive] pub enum LexError { /// An unexpected character is encountered when tokenizing the script text. UnexpectedChar(char), @@ -60,6 +61,7 @@ impl LexError { /// They still exist so that the application can turn features on and off without going through /// massive code changes to remove/add back enum variants in match statements. #[derive(Debug, Eq, PartialEq, Clone, Hash)] +#[non_exhaustive] pub enum ParseErrorType { /// Error in the script text. Wrapped value is the error message. BadInput(String), diff --git a/src/lib.rs b/src/lib.rs index cf92bfc3..04c49e42 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -130,19 +130,25 @@ pub use optimize::OptimizationLevel; // Expose internal data structures. #[cfg(feature = "internals")] +#[deprecated(note = "this type is volatile and may change")] pub use token::Token; #[cfg(feature = "internals")] +#[deprecated(note = "this type is volatile and may change")] pub use parser::Expr; #[cfg(feature = "internals")] +#[deprecated(note = "this type is volatile and may change")] pub use parser::Stmt; #[cfg(feature = "internals")] +#[deprecated(note = "this type is volatile and may change")] pub use module::ModuleRef; #[cfg(feature = "internals")] +#[deprecated(note = "this type is volatile and may change")] pub use utils::StaticVec; #[cfg(feature = "internals")] +#[deprecated(note = "this type is volatile and may change")] pub use parser::ReturnType; diff --git a/src/module.rs b/src/module.rs index 24e51f68..caf3cb39 100644 --- a/src/module.rs +++ b/src/module.rs @@ -2,7 +2,7 @@ use crate::any::{Dynamic, Variant}; use crate::calc_fn_hash; -use crate::engine::{make_getter, make_setter, Engine, FUNC_INDEXER_GET, FUNC_INDEXER_SET}; +use crate::engine::{make_getter, make_setter, Engine, FN_IDX_GET, FN_IDX_SET}; use crate::fn_native::{CallableFunction, FnCallArgs, IteratorFn, SendSync}; use crate::parser::{ FnAccess, @@ -557,7 +557,7 @@ impl Module { &mut self, func: impl Fn(&mut A, B) -> FuncReturn + SendSync + 'static, ) -> u64 { - self.set_fn_2_mut(FUNC_INDEXER_GET, func) + self.set_fn_2_mut(FN_IDX_GET, func) } /// Set a Rust function taking three parameters into the module, returning a hash key. @@ -673,7 +673,7 @@ impl Module { }; let args = [TypeId::of::(), TypeId::of::(), TypeId::of::()]; self.set_fn( - FUNC_INDEXER_SET, + FN_IDX_SET, Public, &args, CallableFunction::from_method(Box::new(f)), diff --git a/src/optimize.rs b/src/optimize.rs index 6acdcc2b..c599a44c 100644 --- a/src/optimize.rs +++ b/src/optimize.rs @@ -628,7 +628,7 @@ fn optimize( // Add constants from the scope into the state scope - .iter() + .to_iter() .filter(|ScopeEntry { typ, expr, .. }| { // Get all the constants with definite constant expressions *typ == ScopeEntryType::Constant diff --git a/src/packages/string_basic.rs b/src/packages/string_basic.rs index 338cf5ec..195ee33a 100644 --- a/src/packages/string_basic.rs +++ b/src/packages/string_basic.rs @@ -1,5 +1,5 @@ use crate::def_package; -use crate::engine::{FUNC_TO_STRING, KEYWORD_DEBUG, KEYWORD_PRINT}; +use crate::engine::{FN_TO_STRING, KEYWORD_DEBUG, KEYWORD_PRINT}; use crate::module::FuncReturn; use crate::parser::{ImmutableString, INT}; @@ -35,14 +35,14 @@ macro_rules! reg_op { def_package!(crate:BasicStringPackage:"Basic string utilities, including printing.", lib, { reg_op!(lib, KEYWORD_PRINT, to_string, INT, bool, char); - reg_op!(lib, FUNC_TO_STRING, to_string, INT, bool, char); + reg_op!(lib, FN_TO_STRING, to_string, INT, bool, char); lib.set_fn_0(KEYWORD_PRINT, || Ok("".to_string())); lib.set_fn_1(KEYWORD_PRINT, |_: ()| Ok("".to_string())); - lib.set_fn_1(FUNC_TO_STRING, |_: ()| Ok("".to_string())); + lib.set_fn_1(FN_TO_STRING, |_: ()| Ok("".to_string())); lib.set_fn_1(KEYWORD_PRINT, |s: ImmutableString| Ok(s)); - lib.set_fn_1(FUNC_TO_STRING, |s: ImmutableString| Ok(s)); + lib.set_fn_1(FN_TO_STRING, |s: ImmutableString| Ok(s)); reg_op!(lib, KEYWORD_DEBUG, to_debug, INT, bool, (), char, ImmutableString); @@ -50,16 +50,16 @@ def_package!(crate:BasicStringPackage:"Basic string utilities, including printin #[cfg(not(feature = "only_i64"))] { reg_op!(lib, KEYWORD_PRINT, to_string, i8, u8, i16, u16, i32, u32); - reg_op!(lib, FUNC_TO_STRING, to_string, i8, u8, i16, u16, i32, u32); + reg_op!(lib, FN_TO_STRING, to_string, i8, u8, i16, u16, i32, u32); reg_op!(lib, KEYWORD_DEBUG, to_debug, i8, u8, i16, u16, i32, u32); reg_op!(lib, KEYWORD_PRINT, to_string, i64, u64); - reg_op!(lib, FUNC_TO_STRING, to_string, i64, u64); + reg_op!(lib, FN_TO_STRING, to_string, i64, u64); reg_op!(lib, KEYWORD_DEBUG, to_debug, i64, u64); #[cfg(not(target_arch = "wasm32"))] { reg_op!(lib, KEYWORD_PRINT, to_string, i128, u128); - reg_op!(lib, FUNC_TO_STRING, to_string, i128, u128); + reg_op!(lib, FN_TO_STRING, to_string, i128, u128); reg_op!(lib, KEYWORD_DEBUG, to_debug, i128, u128); } } @@ -67,21 +67,21 @@ def_package!(crate:BasicStringPackage:"Basic string utilities, including printin #[cfg(not(feature = "no_float"))] { reg_op!(lib, KEYWORD_PRINT, to_string, f32, f64); - reg_op!(lib, FUNC_TO_STRING, to_string, f32, f64); + reg_op!(lib, FN_TO_STRING, to_string, f32, f64); reg_op!(lib, KEYWORD_DEBUG, to_debug, f32, f64); } #[cfg(not(feature = "no_index"))] { reg_op!(lib, KEYWORD_PRINT, to_debug, Array); - reg_op!(lib, FUNC_TO_STRING, to_debug, Array); + reg_op!(lib, FN_TO_STRING, to_debug, Array); reg_op!(lib, KEYWORD_DEBUG, to_debug, Array); } #[cfg(not(feature = "no_object"))] { lib.set_fn_1_mut(KEYWORD_PRINT, format_map); - lib.set_fn_1_mut(FUNC_TO_STRING, format_map); + lib.set_fn_1_mut(FN_TO_STRING, format_map); lib.set_fn_1_mut(KEYWORD_DEBUG, format_map); } diff --git a/src/parser.rs b/src/parser.rs index 9deda674..9d2d7e8d 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -72,6 +72,7 @@ impl AST { /// Get the statements. #[cfg(feature = "internals")] + #[deprecated(note = "this method is volatile and may change")] pub fn statements(&self) -> &Vec { &self.0 } @@ -89,6 +90,7 @@ impl AST { /// Get the internal `Module` containing all script-defined functions. #[cfg(feature = "internals")] + #[deprecated(note = "this method is volatile and may change")] pub fn lib(&self) -> &Module { &self.1 } diff --git a/src/result.rs b/src/result.rs index 760a9a5e..5fb89758 100644 --- a/src/result.rs +++ b/src/result.rs @@ -22,6 +22,7 @@ use crate::stdlib::path::PathBuf; /// /// Currently, `EvalAltResult` is neither `Send` nor `Sync`. Turn on the `sync` feature to make it `Send + Sync`. #[derive(Debug)] +#[non_exhaustive] pub enum EvalAltResult { /// Syntax error. ErrorParsing(ParseErrorType, Position), diff --git a/src/scope.rs b/src/scope.rs index 1c8a43bd..39827ef5 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -417,7 +417,7 @@ impl<'a> Scope<'a> { pub fn set_value(&mut self, name: &'a str, value: T) { match self.get_index(name) { None => self.push(name, value), - Some((_, EntryType::Constant)) => unreachable!("variable {} is constant", name), + Some((_, EntryType::Constant)) => panic!("variable {} is constant", name), Some((index, EntryType::Normal)) => { self.0.get_mut(index).unwrap().value = Dynamic::from(value) } diff --git a/src/token.rs b/src/token.rs index 5c3d8969..76019d3c 100644 --- a/src/token.rs +++ b/src/token.rs @@ -202,9 +202,11 @@ pub enum Token { PowerOfAssign, #[cfg(not(feature = "no_function"))] Private, + #[cfg(not(feature = "no_module"))] Import, #[cfg(not(feature = "no_module"))] Export, + #[cfg(not(feature = "no_module"))] As, LexError(Box), EOF, @@ -776,9 +778,11 @@ impl<'a> TokenIterator<'a> { "in" => Token::In, #[cfg(not(feature = "no_function"))] "private" => Token::Private, + #[cfg(not(feature = "no_module"))] "import" => Token::Import, #[cfg(not(feature = "no_module"))] "export" => Token::Export, + #[cfg(not(feature = "no_module"))] "as" => Token::As, #[cfg(not(feature = "no_function"))]