Disallow overriding keywords.

This commit is contained in:
Stephen Chung 2021-03-01 22:44:56 +08:00
parent fc10df7d63
commit 67d277aa21
8 changed files with 434 additions and 339 deletions

View File

@ -20,6 +20,7 @@ Breaking changes
* `NativeCallContext::call_fn_dynamic_raw` no longer has the `pub_only` parameter.
* `Module::update_fn_metadata` input parameter is changed.
* Function keywords (e.g. `type_of`, `eval`, `Fn`) can no longer be overloaded. It is more trouble than worth. To disable these keywords, use `Engine::disable_symbol`.
* `is_def_var` and `is_def_fn` are now reserved keywords.
Enhancements
------------

View File

@ -187,6 +187,8 @@ pub const KEYWORD_FN_PTR_CURRY: &str = "curry";
#[cfg(not(feature = "no_closure"))]
pub const KEYWORD_IS_SHARED: &str = "is_shared";
pub const KEYWORD_IS_DEF_VAR: &str = "is_def_var";
#[cfg(not(feature = "no_function"))]
pub const KEYWORD_IS_DEF_FN: &str = "is_def_fn";
pub const KEYWORD_THIS: &str = "this";
#[cfg(not(feature = "no_object"))]
pub const FN_GET: &str = "get$";

View File

@ -644,37 +644,80 @@ impl Engine {
ensure_no_data_race(fn_name, args, is_ref)?;
}
let hash_fn =
calc_native_fn_hash(empty(), fn_name, args.iter().map(|a| a.type_id())).unwrap();
// These may be redirected from method style calls.
match fn_name {
// type_of
KEYWORD_TYPE_OF if args.len() == 1 => Ok((
// Handle type_of()
KEYWORD_TYPE_OF if args.len() == 1 => {
return Ok((
self.map_type_name(args[0].type_name()).to_string().into(),
false,
)),
));
}
// Fn/eval - reaching this point it must be a method-style call, mostly like redirected
// by a function pointer so it isn't caught at parse time.
KEYWORD_FN_PTR | KEYWORD_EVAL if args.len() == 1 => EvalAltResult::ErrorRuntime(
// Handle is_def_fn()
#[cfg(not(feature = "no_function"))]
crate::engine::KEYWORD_IS_DEF_FN
if args.len() == 2 && args[0].is::<FnPtr>() && args[1].is::<INT>() =>
{
let fn_name = args[0].as_str().unwrap();
let num_params = args[1].as_int().unwrap();
return Ok((
if num_params < 0 {
Dynamic::FALSE
} else {
let hash_script =
calc_script_fn_hash(empty(), fn_name, num_params as usize);
self.has_override(Some(mods), lib, None, hash_script).into()
},
false,
));
}
// Handle is_shared()
#[cfg(not(feature = "no_closure"))]
crate::engine::KEYWORD_IS_SHARED if args.len() == 1 => {
return Err(Box::new(EvalAltResult::ErrorRuntime(
format!(
"'{}' should not be called in method style. Try {}(...);",
"'{}' should not be called this way. Try {}(...);",
fn_name, fn_name
)
.into(),
pos,
)))
}
KEYWORD_FN_PTR | KEYWORD_EVAL | KEYWORD_IS_DEF_VAR if args.len() == 1 => {
return Err(Box::new(EvalAltResult::ErrorRuntime(
format!(
"'{}' should not be called this way. Try {}(...);",
fn_name, fn_name
)
.into(),
pos,
)))
}
KEYWORD_FN_PTR_CALL | KEYWORD_FN_PTR_CURRY if !args.is_empty() => {
return Err(Box::new(EvalAltResult::ErrorRuntime(
format!(
"'{}' should not be called this way. Try {}(...);",
fn_name, fn_name
)
.into(),
pos,
)))
}
_ => (),
}
#[cfg(not(feature = "no_function"))]
_ if hash_script.is_some() => {
let (func, source) = self
.resolve_function(mods, state, lib, fn_name, hash_script.unwrap(), args, false)
if let Some((func, source)) = hash_script.and_then(|hash| {
self.resolve_function(mods, state, lib, fn_name, hash, args, false)
.as_ref()
.map(|(f, s)| (Some(f.clone()), s.clone()))
.unwrap_or((None, None));
if let Some(func) = func {
.map(|(f, s)| (f.clone(), s.clone()))
}) {
// Script function call
assert!(func.is_script());
@ -732,9 +775,8 @@ impl Engine {
let level = _level + 1;
let result = self.call_script_fn(
scope, mods, state, lib, &mut None, func, args, pos, level,
);
let result =
self.call_script_fn(scope, mods, state, lib, &mut None, func, args, pos, level);
// Restore the original source
state.source = orig_source;
@ -745,18 +787,13 @@ impl Engine {
result?
};
Ok((result, false))
} else {
// Native function call
self.call_native_fn(
mods, state, lib, fn_name, hash_fn, args, is_ref, false, pos,
)
}
return Ok((result, false));
}
// Native function call
_ => self.call_native_fn(mods, state, lib, fn_name, hash_fn, args, is_ref, false, pos),
}
let hash_fn =
calc_native_fn_hash(empty(), fn_name, args.iter().map(|a| a.type_id())).unwrap();
self.call_native_fn(mods, state, lib, fn_name, hash_fn, args, is_ref, false, pos)
}
/// Evaluate a list of statements with no `this` pointer.
@ -845,14 +882,16 @@ impl Engine {
let obj = target.as_mut();
let mut fn_name = fn_name;
let (result, updated) = if fn_name == KEYWORD_FN_PTR_CALL && obj.is::<FnPtr>() {
let (result, updated) = match fn_name {
KEYWORD_FN_PTR_CALL if obj.is::<FnPtr>() => {
// FnPtr call
let fn_ptr = obj.read_lock::<FnPtr>().unwrap();
// Redirect function name
let fn_name = fn_ptr.fn_name();
let args_len = call_args.len() + fn_ptr.curry().len();
// Recalculate hash
let hash = hash_script.and_then(|_| calc_script_fn_hash(empty(), fn_name, args_len));
let hash =
hash_script.and_then(|_| calc_script_fn_hash(empty(), fn_name, args_len));
// Arguments are passed as-is, adding the curried arguments
let mut curry = fn_ptr.curry().iter().cloned().collect::<StaticVec<_>>();
let mut arg_values = curry
@ -865,17 +904,16 @@ impl Engine {
self.exec_fn_call(
mods, state, lib, fn_name, hash, args, false, false, pos, None, level,
)
} else if fn_name == KEYWORD_FN_PTR_CALL
&& call_args.len() > 0
&& call_args[0].is::<FnPtr>()
{
}
KEYWORD_FN_PTR_CALL if call_args.len() > 0 && call_args[0].is::<FnPtr>() => {
// FnPtr call on object
let fn_ptr = call_args.remove(0).cast::<FnPtr>();
// Redirect function name
let fn_name = fn_ptr.fn_name();
let args_len = call_args.len() + fn_ptr.curry().len();
// Recalculate hash
let hash = hash_script.and_then(|_| calc_script_fn_hash(empty(), fn_name, args_len));
let hash =
hash_script.and_then(|_| calc_script_fn_hash(empty(), fn_name, args_len));
// Replace the first argument with the object pointer, adding the curried arguments
let mut curry = fn_ptr.curry().iter().cloned().collect::<StaticVec<_>>();
let mut arg_values = once(obj)
@ -888,7 +926,8 @@ impl Engine {
self.exec_fn_call(
mods, state, lib, fn_name, hash, args, is_ref, true, pos, None, level,
)
} else if fn_name == KEYWORD_FN_PTR_CURRY && obj.is::<FnPtr>() {
}
KEYWORD_FN_PTR_CURRY if obj.is::<FnPtr>() => {
// Curry call
let fn_ptr = obj.read_lock::<FnPtr>().unwrap();
Ok((
@ -904,17 +943,15 @@ impl Engine {
.into(),
false,
))
} else if {
#[cfg(not(feature = "no_closure"))]
{
fn_name == crate::engine::KEYWORD_IS_SHARED && call_args.is_empty()
}
#[cfg(feature = "no_closure")]
false
} {
// is_shared call
Ok((target.is_shared().into(), false))
} else {
// Handle is_shared()
#[cfg(not(feature = "no_closure"))]
crate::engine::KEYWORD_IS_SHARED if call_args.is_empty() => {
return Ok((target.is_shared().into(), false));
}
_ => {
let _redirected;
let mut hash = hash_script;
@ -934,8 +971,9 @@ impl Engine {
.enumerate()
.for_each(|(i, v)| call_args.insert(i, v));
// Recalculate the hash based on the new function name and new arguments
hash = hash_script
.and_then(|_| calc_script_fn_hash(empty(), fn_name, call_args.len()));
hash = hash_script.and_then(|_| {
calc_script_fn_hash(empty(), fn_name, call_args.len())
});
}
}
};
@ -953,6 +991,7 @@ impl Engine {
self.exec_fn_call(
mods, state, lib, fn_name, hash, args, is_ref, true, pos, None, level,
)
}
}?;
// Propagate the changed value back to the source if necessary
@ -986,8 +1025,11 @@ impl Engine {
let mut curry = StaticVec::new();
let mut name = fn_name;
if name == KEYWORD_FN_PTR_CALL && args_expr.len() >= 1 {
let fn_ptr = self.eval_expr(scope, mods, state, lib, this_ptr, &args_expr[0], level)?;
match name {
// Handle call()
KEYWORD_FN_PTR_CALL if args_expr.len() >= 1 => {
let fn_ptr =
self.eval_expr(scope, mods, state, lib, this_ptr, &args_expr[0], level)?;
if !fn_ptr.is::<FnPtr>() {
return Err(self.make_type_mismatch_err::<FnPtr>(
@ -1012,7 +1054,7 @@ impl Engine {
}
// Handle Fn()
if name == KEYWORD_FN_PTR && args_expr.len() == 1 {
KEYWORD_FN_PTR if args_expr.len() == 1 => {
// Fn - only in function call style
return self
.eval_expr(scope, mods, state, lib, this_ptr, &args_expr[0], level)?
@ -1026,8 +1068,9 @@ impl Engine {
}
// Handle curry()
if name == KEYWORD_FN_PTR_CURRY && args_expr.len() > 1 {
let fn_ptr = self.eval_expr(scope, mods, state, lib, this_ptr, &args_expr[0], level)?;
KEYWORD_FN_PTR_CURRY if args_expr.len() > 1 => {
let fn_ptr =
self.eval_expr(scope, mods, state, lib, this_ptr, &args_expr[0], level)?;
if !fn_ptr.is::<FnPtr>() {
return Err(self.make_type_mismatch_err::<FnPtr>(
@ -1040,27 +1083,49 @@ impl Engine {
// Append the new curried arguments to the existing list.
args_expr
.iter()
.skip(1)
.try_for_each(|expr| -> Result<(), Box<EvalAltResult>> {
fn_curry.push(self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?);
args_expr.iter().skip(1).try_for_each(
|expr| -> Result<(), Box<EvalAltResult>> {
fn_curry
.push(self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?);
Ok(())
})?;
},
)?;
return Ok(FnPtr::new_unchecked(name, fn_curry).into());
}
// Handle is_shared()
#[cfg(not(feature = "no_closure"))]
if name == crate::engine::KEYWORD_IS_SHARED && args_expr.len() == 1 {
let value = self.eval_expr(scope, mods, state, lib, this_ptr, &args_expr[0], level)?;
crate::engine::KEYWORD_IS_SHARED if args_expr.len() == 1 => {
let value =
self.eval_expr(scope, mods, state, lib, this_ptr, &args_expr[0], level)?;
return Ok(value.is_shared().into());
}
// Handle is_def_fn()
#[cfg(not(feature = "no_function"))]
crate::engine::KEYWORD_IS_DEF_FN if args_expr.len() == 2 => {
let fn_name =
self.eval_expr(scope, mods, state, lib, this_ptr, &args_expr[0], level)?;
let fn_name = fn_name.as_str().map_err(|err| {
self.make_type_mismatch_err::<ImmutableString>(err, args_expr[0].position())
})?;
let num_params =
self.eval_expr(scope, mods, state, lib, this_ptr, &args_expr[1], level)?;
let num_params = num_params.as_int().map_err(|err| {
self.make_type_mismatch_err::<INT>(err, args_expr[0].position())
})?;
if num_params < 0 {
return Ok(Dynamic::FALSE);
} else {
let hash_script = calc_script_fn_hash(empty(), fn_name, num_params as usize);
return Ok(self.has_override(Some(mods), lib, None, hash_script).into());
}
}
// Handle is_def_var()
if name == KEYWORD_IS_DEF_VAR && args_expr.len() == 1 {
KEYWORD_IS_DEF_VAR if args_expr.len() == 1 => {
let var_name =
self.eval_expr(scope, mods, state, lib, this_ptr, &args_expr[0], level)?;
let var_name = var_name.as_str().map_err(|err| {
@ -1070,16 +1135,17 @@ impl Engine {
}
// Handle eval()
if name == KEYWORD_EVAL && args_expr.len() == 1 {
KEYWORD_EVAL if args_expr.len() == 1 => {
let script_expr = &args_expr[0];
let script_pos = script_expr.position();
// eval - only in function call style
let prev_len = scope.len();
let script = self.eval_expr(scope, mods, state, lib, this_ptr, script_expr, level)?;
let script = script
.as_str()
.map_err(|typ| self.make_type_mismatch_err::<ImmutableString>(typ, script_pos))?;
let script =
self.eval_expr(scope, mods, state, lib, this_ptr, script_expr, level)?;
let script = script.as_str().map_err(|typ| {
self.make_type_mismatch_err::<ImmutableString>(typ, script_pos)
})?;
let result = self.eval_script_expr_in_place(
scope,
mods,
@ -1110,6 +1176,9 @@ impl Engine {
});
}
_ => (),
}
// Normal function call - except for Fn, curry, call and eval (handled above)
let mut arg_values: StaticVec<_>;
let mut args: StaticVec<_>;

View File

@ -2,7 +2,7 @@
use crate::engine::{
KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_FN_PTR_CALL, KEYWORD_FN_PTR_CURRY,
KEYWORD_PRINT, KEYWORD_THIS, KEYWORD_TYPE_OF,
KEYWORD_IS_DEF_VAR, KEYWORD_PRINT, KEYWORD_THIS, KEYWORD_TYPE_OF,
};
use crate::stdlib::{
borrow::Cow,
@ -21,6 +21,9 @@ use crate::ast::FloatWrapper;
#[cfg(feature = "decimal")]
use rust_decimal::Decimal;
#[cfg(not(feature = "no_function"))]
use crate::engine::KEYWORD_IS_DEF_FN;
type LERR = LexError;
/// Separator character for numbers.
@ -579,7 +582,12 @@ impl Token {
| "async" | "await" | "yield" => Reserved(syntax.into()),
KEYWORD_PRINT | KEYWORD_DEBUG | KEYWORD_TYPE_OF | KEYWORD_EVAL | KEYWORD_FN_PTR
| KEYWORD_FN_PTR_CALL | KEYWORD_FN_PTR_CURRY | KEYWORD_THIS => Reserved(syntax.into()),
| KEYWORD_FN_PTR_CALL | KEYWORD_FN_PTR_CURRY | KEYWORD_THIS | KEYWORD_IS_DEF_VAR => {
Reserved(syntax.into())
}
#[cfg(not(feature = "no_function"))]
KEYWORD_IS_DEF_FN => Reserved(syntax.into()),
_ => return None,
})
@ -1624,7 +1632,11 @@ fn get_identifier(
pub fn is_keyword_function(name: &str) -> bool {
match name {
KEYWORD_PRINT | KEYWORD_DEBUG | KEYWORD_TYPE_OF | KEYWORD_EVAL | KEYWORD_FN_PTR
| KEYWORD_FN_PTR_CALL | KEYWORD_FN_PTR_CURRY => true,
| KEYWORD_FN_PTR_CALL | KEYWORD_FN_PTR_CURRY | KEYWORD_IS_DEF_VAR => true,
#[cfg(not(feature = "no_function"))]
KEYWORD_IS_DEF_FN => true,
_ => false,
}
}

View File

@ -102,6 +102,14 @@ fn test_closures() -> Result<(), Box<EvalAltResult>> {
"#
)?);
assert!(engine.eval::<bool>(
r#"
let a = 41;
let foo = |x| { a += x };
is_shared(a)
"#
)?);
engine.register_fn("plus_one", |x: INT| x + 1);
assert_eq!(

View File

@ -37,32 +37,6 @@ fn test_constant_scope() -> Result<(), Box<EvalAltResult>> {
Ok(())
}
#[test]
fn test_var_is_def() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert!(engine.eval::<bool>(
r#"
let x = 42;
is_def_var("x")
"#
)?);
assert!(!engine.eval::<bool>(
r#"
let x = 42;
is_def_var("y")
"#
)?);
assert!(engine.eval::<bool>(
r#"
const x = 42;
is_def_var("x")
"#
)?);
Ok(())
}
#[cfg(not(feature = "no_object"))]
#[test]
fn test_constant_mut() -> Result<(), Box<EvalAltResult>> {

View File

@ -46,6 +46,9 @@ fn test_type_of() -> Result<(), Box<EvalAltResult>> {
assert_eq!(engine.eval::<String>(r#"type_of("hello")"#)?, "string");
#[cfg(not(feature = "no_object"))]
assert_eq!(engine.eval::<String>(r#""hello".type_of()"#)?, "string");
#[cfg(not(feature = "only_i32"))]
assert_eq!(engine.eval::<String>("let x = 123; type_of(x)")?, "i64");

View File

@ -19,6 +19,32 @@ fn test_var_scope() -> Result<(), Box<EvalAltResult>> {
Ok(())
}
#[test]
fn test_var_is_def() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert!(engine.eval::<bool>(
r#"
let x = 42;
is_def_var("x")
"#
)?);
assert!(!engine.eval::<bool>(
r#"
let x = 42;
is_def_var("y")
"#
)?);
assert!(engine.eval::<bool>(
r#"
const x = 42;
is_def_var("x")
"#
)?);
Ok(())
}
#[test]
fn test_scope_eval() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();