Code cleanup.

This commit is contained in:
Stephen Chung 2020-06-25 11:07:46 +08:00
parent ab60c2e1d2
commit 58c198776f
11 changed files with 61 additions and 50 deletions

View File

@ -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`.

View File

@ -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<Dynamic>,
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
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 {
let next_chain = match rhs {
Expr::Index(_) => ChainType::Index,
Expr::Dot(_) => ChainType::Dot,
_ => unreachable!(),
}
}
_ => 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::<Map>() => {
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(

View File

@ -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),

View File

@ -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;

View File

@ -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<T> + 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::<A>(), TypeId::of::<B>(), TypeId::of::<A>()];
self.set_fn(
FUNC_INDEXER_SET,
FN_IDX_SET,
Public,
&args,
CallableFunction::from_method(Box::new(f)),

View File

@ -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

View File

@ -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);
}

View File

@ -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<Stmt> {
&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
}

View File

@ -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),

View File

@ -417,7 +417,7 @@ impl<'a> Scope<'a> {
pub fn set_value<T: Variant + Clone>(&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)
}

View File

@ -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<LexError>),
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"))]