feat: 支持 to_string 与错误栈
This commit is contained in:
@@ -193,6 +193,12 @@ impl CompileCtx {
|
||||
"Boolean",
|
||||
"Function",
|
||||
"Error",
|
||||
"TypeError",
|
||||
"ReferenceError",
|
||||
"RangeError",
|
||||
"SyntaxError",
|
||||
"URIError",
|
||||
"EvalError",
|
||||
"Math",
|
||||
"JSON",
|
||||
"Promise",
|
||||
|
||||
@@ -80,6 +80,8 @@ pub struct ErrorMethods {
|
||||
pub syntax_error: *const (),
|
||||
pub uri_error: *const (),
|
||||
pub eval_error: *const (),
|
||||
pub to_string: *const (),
|
||||
pub stack: *const (),
|
||||
}
|
||||
|
||||
pub struct StringMethods {
|
||||
@@ -123,12 +125,18 @@ pub struct NumberMethods {
|
||||
pub parse_float: *const (),
|
||||
pub to_string: *const (),
|
||||
pub to_fixed: *const (),
|
||||
pub is_integer: *const (),
|
||||
pub is_safe_integer: *const (),
|
||||
pub to_exponential: *const (),
|
||||
pub to_precision: *const (),
|
||||
pub value_of: *const (),
|
||||
}
|
||||
|
||||
pub struct FunctionMethods {
|
||||
pub call: *const (),
|
||||
pub apply: *const (),
|
||||
pub bind: *const (),
|
||||
pub to_string: *const (),
|
||||
}
|
||||
|
||||
pub struct BuiltinWorld {
|
||||
@@ -650,6 +658,11 @@ impl BuiltinWorld {
|
||||
methods.eval_error,
|
||||
1,
|
||||
);
|
||||
|
||||
let proto_ptr = P::as_ptr(&self.error_proto) as *mut JsObject;
|
||||
let proto = unsafe { &mut *proto_ptr };
|
||||
let _ = self.bind_method(proto, shape_forge, string_forge, "toString", methods.to_string, 0);
|
||||
let _ = self.bind_method(proto, shape_forge, string_forge, "stack", methods.stack, 0);
|
||||
}
|
||||
|
||||
pub fn bind_string_methods(
|
||||
@@ -853,6 +866,11 @@ impl BuiltinWorld {
|
||||
methods.to_fixed,
|
||||
0,
|
||||
);
|
||||
let _ = self.bind_method(ctor, shape_forge, string_forge, "isInteger", methods.is_integer, 1);
|
||||
let _ = self.bind_method(ctor, shape_forge, string_forge, "isSafeInteger", methods.is_safe_integer, 1);
|
||||
let _ = self.bind_method(proto, shape_forge, string_forge, "toExponential", methods.to_exponential, 0);
|
||||
let _ = self.bind_method(proto, shape_forge, string_forge, "toPrecision", methods.to_precision, 0);
|
||||
let _ = self.bind_method(proto, shape_forge, string_forge, "valueOf", methods.value_of, 0);
|
||||
}
|
||||
|
||||
pub fn bind_function_methods(
|
||||
@@ -892,6 +910,7 @@ impl BuiltinWorld {
|
||||
1,
|
||||
fp,
|
||||
);
|
||||
let _ = Self::bind_method_static(proto, shape_forge, string_forge, "toString", methods.to_string, 0, fp);
|
||||
}
|
||||
|
||||
pub fn bind_method(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::bind_constructor_hash;
|
||||
use oxide_kernel::builtin::ErrorMethods;
|
||||
use oxide_kernel::kernel::OxideKernel;
|
||||
use oxide_types::object::JsObject;
|
||||
@@ -14,6 +15,8 @@ pub fn bind_error(kernel: &Arc<OxideKernel>, global: &mut JsObject) {
|
||||
syntax_error: crate::builtins::error::syntax_error_constructor as *const (),
|
||||
uri_error: crate::builtins::error::uri_error_constructor as *const (),
|
||||
eval_error: crate::builtins::error::eval_error_constructor as *const (),
|
||||
to_string: crate::builtins::error::error_to_string as *const (),
|
||||
stack: crate::builtins::error::error_stack_getter as *const (),
|
||||
};
|
||||
kernel.builtin_world().bind_error_methods(
|
||||
&error_methods,
|
||||
@@ -29,6 +32,13 @@ pub fn bind_error(kernel: &Arc<OxideKernel>, global: &mut JsObject) {
|
||||
global.ensure_hash_props().push(Box::new(err_val));
|
||||
global.bump_generation();
|
||||
|
||||
bind_constructor_hash!(kernel, global, "TypeError", kernel.builtin_world().type_error_proto.as_ptr() as *mut JsObject, crate::builtins::error::type_error_constructor, 1);
|
||||
bind_constructor_hash!(kernel, global, "ReferenceError", kernel.builtin_world().reference_error_proto.as_ptr() as *mut JsObject, crate::builtins::error::reference_error_constructor, 1);
|
||||
bind_constructor_hash!(kernel, global, "RangeError", kernel.builtin_world().range_error_proto.as_ptr() as *mut JsObject, crate::builtins::error::range_error_constructor, 1);
|
||||
bind_constructor_hash!(kernel, global, "SyntaxError", kernel.builtin_world().syntax_error_proto.as_ptr() as *mut JsObject, crate::builtins::error::syntax_error_constructor, 1);
|
||||
bind_constructor_hash!(kernel, global, "URIError", kernel.builtin_world().uri_error_proto.as_ptr() as *mut JsObject, crate::builtins::error::uri_error_constructor, 1);
|
||||
bind_constructor_hash!(kernel, global, "EvalError", kernel.builtin_world().eval_error_proto.as_ptr() as *mut JsObject, crate::builtins::error::eval_error_constructor, 1);
|
||||
|
||||
{
|
||||
let err_ctor_ptr = kernel.builtin_world().error_constructor.as_ptr() as *mut JsObject;
|
||||
let err_ctor = unsafe { &mut *err_ctor_ptr };
|
||||
|
||||
@@ -8,6 +8,7 @@ pub fn bind_function(kernel: &Arc<OxideKernel>) {
|
||||
call: crate::builtins::function::function_call as *const (),
|
||||
apply: crate::builtins::function::function_apply as *const (),
|
||||
bind: crate::builtins::function::function_bind as *const (),
|
||||
to_string: crate::builtins::function::function_to_string as *const (),
|
||||
};
|
||||
kernel.builtin_world().bind_function_methods(
|
||||
&function_methods,
|
||||
|
||||
@@ -14,6 +14,11 @@ pub fn bind_number(kernel: &Arc<OxideKernel>, global: &mut JsObject) {
|
||||
parse_float: crate::builtins::number::number_parse_float as *const (),
|
||||
to_string: crate::builtins::number::number_to_string as *const (),
|
||||
to_fixed: crate::builtins::number::number_to_fixed as *const (),
|
||||
is_integer: crate::builtins::number::number_is_integer as *const (),
|
||||
is_safe_integer: crate::builtins::number::number_is_safe_integer as *const (),
|
||||
to_exponential: crate::builtins::number::number_to_exponential as *const (),
|
||||
to_precision: crate::builtins::number::number_to_precision as *const (),
|
||||
value_of: crate::builtins::number::number_value_of as *const (),
|
||||
};
|
||||
kernel.builtin_world().bind_number_methods(
|
||||
&number_methods,
|
||||
@@ -37,6 +42,46 @@ pub fn bind_number(kernel: &Arc<OxideKernel>, global: &mut JsObject) {
|
||||
crate::builtins::number::number_constructor as *const (),
|
||||
));
|
||||
num_ctor.set_native_arg_count(1);
|
||||
|
||||
num_ctor.ensure_hash_props().push(Box::new(JsValue::float(2.220446049250313e-16)));
|
||||
let eps_si = kernel.string_forge().intern("EPSILON").0;
|
||||
let _shape1 = kernel.shape_forge().make_shape(num_ctor.shape_id(), eps_si);
|
||||
num_ctor.set_shape_id(_shape1);
|
||||
|
||||
num_ctor.ensure_hash_props().push(Box::new(JsValue::float(9007199254740991f64)));
|
||||
let max_safe_si = kernel.string_forge().intern("MAX_SAFE_INTEGER").0;
|
||||
let _shape2 = kernel.shape_forge().make_shape(num_ctor.shape_id(), max_safe_si);
|
||||
num_ctor.set_shape_id(_shape2);
|
||||
|
||||
num_ctor.ensure_hash_props().push(Box::new(JsValue::float(-9007199254740991f64)));
|
||||
let min_safe_si = kernel.string_forge().intern("MIN_SAFE_INTEGER").0;
|
||||
let _shape3 = kernel.shape_forge().make_shape(num_ctor.shape_id(), min_safe_si);
|
||||
num_ctor.set_shape_id(_shape3);
|
||||
|
||||
num_ctor.ensure_hash_props().push(Box::new(JsValue::float(1.7976931348623157e308)));
|
||||
let max_val_si = kernel.string_forge().intern("MAX_VALUE").0;
|
||||
let _shape4 = kernel.shape_forge().make_shape(num_ctor.shape_id(), max_val_si);
|
||||
num_ctor.set_shape_id(_shape4);
|
||||
|
||||
num_ctor.ensure_hash_props().push(Box::new(JsValue::float(5e-324)));
|
||||
let min_val_si = kernel.string_forge().intern("MIN_VALUE").0;
|
||||
let _shape5 = kernel.shape_forge().make_shape(num_ctor.shape_id(), min_val_si);
|
||||
num_ctor.set_shape_id(_shape5);
|
||||
|
||||
num_ctor.ensure_hash_props().push(Box::new(JsValue::float(f64::NAN)));
|
||||
let nan_si = kernel.string_forge().intern("NaN").0;
|
||||
let _shape6 = kernel.shape_forge().make_shape(num_ctor.shape_id(), nan_si);
|
||||
num_ctor.set_shape_id(_shape6);
|
||||
|
||||
num_ctor.ensure_hash_props().push(Box::new(JsValue::float(f64::NEG_INFINITY)));
|
||||
let neg_inf_si = kernel.string_forge().intern("NEGATIVE_INFINITY").0;
|
||||
let _shape7 = kernel.shape_forge().make_shape(num_ctor.shape_id(), neg_inf_si);
|
||||
num_ctor.set_shape_id(_shape7);
|
||||
|
||||
num_ctor.ensure_hash_props().push(Box::new(JsValue::float(f64::INFINITY)));
|
||||
let pos_inf_si = kernel.string_forge().intern("POSITIVE_INFINITY").0;
|
||||
let _shape8 = kernel.shape_forge().make_shape(num_ctor.shape_id(), pos_inf_si);
|
||||
num_ctor.set_shape_id(_shape8);
|
||||
}
|
||||
|
||||
let pi_fn = crate::builtins::number::number_parse_int as *const ();
|
||||
|
||||
@@ -116,3 +116,31 @@ pub fn eval_error_constructor(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||
let proto_ptr = P::as_ptr(&vm.kernel().builtin_world().eval_error_proto) as *mut JsObject;
|
||||
Ok(create_error_object(vm, proto_ptr, "EvalError", &msg))
|
||||
}
|
||||
|
||||
pub fn error_to_string(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||
let this_val = vm.reg(args[0]);
|
||||
let (name, msg) = if this_val.is_object() {
|
||||
let obj = unsafe { &*this_val.as_js_object_ptr() };
|
||||
let name_val = obj.hash_props_vec().and_then(|v| v.first()).map(|b| **b).unwrap_or(JsValue::undefined());
|
||||
let msg_val = obj.hash_props_vec().and_then(|v| v.get(1)).map(|b| **b).unwrap_or(JsValue::undefined());
|
||||
(vm.lookup_str(name_val).unwrap_or_else(|| "Error".to_string()),
|
||||
vm.lookup_str(msg_val).unwrap_or_default())
|
||||
} else {
|
||||
("Error".to_string(), String::new())
|
||||
};
|
||||
let result = if msg.is_empty() { name } else { format!("{}: {}", name, msg) };
|
||||
let si = vm.kernel().string_forge().intern(&result).0;
|
||||
Ok(JsValue::string(si, 0))
|
||||
}
|
||||
|
||||
pub fn error_stack_getter(vm: &mut Vm, _args: &[u8]) -> NativeResult {
|
||||
let mut lines = vec![];
|
||||
for frame in vm.frames.iter().rev() {
|
||||
let func_name = vm.kernel().string_forge().lookup(frame.function_name).unwrap_or_else(|| "<anonymous>".to_string());
|
||||
lines.push(format!(" at {} (native)", func_name));
|
||||
}
|
||||
lines.push(" at <anonymous> (native)".to_string());
|
||||
let result = lines.join("\n");
|
||||
let si = vm.kernel().string_forge().intern(&result).0;
|
||||
Ok(JsValue::string(si, 0))
|
||||
}
|
||||
|
||||
@@ -158,3 +158,14 @@ pub fn function_bind(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||
|
||||
Ok(JsValue::from_js_object(wrapper))
|
||||
}
|
||||
|
||||
pub fn function_to_string(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||
let name = vm.kernel().string_forge().lookup(vm.reg(args[0]).as_string_index()).unwrap_or_default();
|
||||
let result = if name.is_empty() {
|
||||
"function () { [native code] }".to_string()
|
||||
} else {
|
||||
format!("function {}() {{ [native code] }}", name)
|
||||
};
|
||||
let si = vm.kernel().string_forge().intern(&result).0;
|
||||
Ok(JsValue::string(si, 0))
|
||||
}
|
||||
|
||||
@@ -167,3 +167,50 @@ pub fn number_to_fixed(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||
let formatted = format!("{:.digits$}", n);
|
||||
Ok(vm.intern(&formatted))
|
||||
}
|
||||
|
||||
pub fn number_is_integer(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||
let val = vm.reg(if args.len() > 1 { args[1] } else { args[0] });
|
||||
let n = coercion::to_number(val, vm.kernel().string_forge().as_ref());
|
||||
Ok(JsValue::bool(n.trunc() == n && n.is_finite()))
|
||||
}
|
||||
|
||||
pub fn number_is_safe_integer(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||
let val = vm.reg(if args.len() > 1 { args[1] } else { args[0] });
|
||||
let n = coercion::to_number(val, vm.kernel().string_forge().as_ref());
|
||||
let safe = n.trunc() == n && n.is_finite() && n >= -9007199254740991i64 as f64 && n <= 9007199254740991i64 as f64;
|
||||
Ok(JsValue::bool(safe))
|
||||
}
|
||||
|
||||
pub fn number_to_exponential(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||
let n = coercion::to_number(vm.reg(args[0]), vm.kernel().string_forge().as_ref());
|
||||
let digits = if args.len() > 1 {
|
||||
coercion::to_number(vm.reg(args[1]), vm.kernel().string_forge().as_ref()) as usize
|
||||
} else { 0usize }.min(100);
|
||||
if n.is_nan() { return Ok(vm.intern("NaN")); }
|
||||
if n.is_infinite() {
|
||||
return Ok(vm.intern(if n.is_sign_positive() { "Infinity" } else { "-Infinity" }));
|
||||
}
|
||||
let formatted = format!("{:.digits$e}", n);
|
||||
Ok(vm.intern(&formatted))
|
||||
}
|
||||
|
||||
pub fn number_to_precision(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||
let n = coercion::to_number(vm.reg(args[0]), vm.kernel().string_forge().as_ref());
|
||||
let precision = if args.len() > 1 {
|
||||
coercion::to_number(vm.reg(args[1]), vm.kernel().string_forge().as_ref()) as usize
|
||||
} else { 0usize }.min(21);
|
||||
if n.is_nan() { return Ok(vm.intern("NaN")); }
|
||||
if n.is_infinite() {
|
||||
return Ok(vm.intern(if n.is_sign_positive() { "Infinity" } else { "-Infinity" }));
|
||||
}
|
||||
let formatted = format!("{:.precision$}", n);
|
||||
Ok(vm.intern(&formatted))
|
||||
}
|
||||
|
||||
pub fn number_value_of(vm: &mut Vm, args: &[u8]) -> NativeResult {
|
||||
let this_val = vm.reg(args[0]);
|
||||
if this_val.is_int() || this_val.is_double() {
|
||||
return Ok(this_val);
|
||||
}
|
||||
Ok(JsValue::float(f64::NAN))
|
||||
}
|
||||
|
||||
@@ -139,6 +139,7 @@ pub struct CallFrame {
|
||||
pub n_args: u8,
|
||||
pub function_obj_reg: u8,
|
||||
pub frame_base: u8,
|
||||
pub function_name: u32,
|
||||
}
|
||||
|
||||
pub struct ForInIter<'bump> {
|
||||
@@ -729,6 +730,7 @@ impl Vm {
|
||||
n_args: sub_n_args as u8,
|
||||
function_obj_reg: callee_reg as u8,
|
||||
frame_base: sub_builtin_count as u8,
|
||||
function_name: 0,
|
||||
});
|
||||
|
||||
// Convert sub_module constants
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use oxide_compiler::compiler::Compiler;
|
||||
use oxide_types::value::JsValue;
|
||||
use oxide_vm::builtins::error;
|
||||
use oxide_vm::vm::Vm;
|
||||
|
||||
@@ -5,6 +7,14 @@ fn make_vm() -> Vm {
|
||||
Vm::new()
|
||||
}
|
||||
|
||||
fn eval(source: &str) -> Result<JsValue, String> {
|
||||
let allocator = oxide_parser::Allocator::default();
|
||||
let program = oxide_parser::parse(&allocator, source).map_err(|e| format!("Parse: {}", e))?;
|
||||
let module = Compiler::new().compile(&program).map_err(|e| format!("Compile: {}", e))?;
|
||||
let mut vm = make_vm();
|
||||
vm.run(&module)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_constructor_creates_object() {
|
||||
let mut vm = make_vm();
|
||||
@@ -107,3 +117,21 @@ fn error_name_is_string_property() {
|
||||
let n = obj.prop_count();
|
||||
assert!(n >= 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_to_string_returns_string() {
|
||||
let result = eval("new Error('test').toString()").unwrap();
|
||||
assert!(result.is_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_error_is_defined() {
|
||||
let result = eval("typeof TypeError").unwrap();
|
||||
assert!(result.is_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_error_is_defined() {
|
||||
let result = eval("typeof ReferenceError").unwrap();
|
||||
assert!(result.is_string());
|
||||
}
|
||||
|
||||
@@ -32,3 +32,10 @@ fn function_bind_creates_wrapper() {
|
||||
let result = eval(&mut vm, "var b = Math.max.bind(null, 1); b(5)").unwrap();
|
||||
assert!((result.as_double() - 5.0).abs() < 0.0001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_to_string_includes_function() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(&mut vm, "Math.max.toString()").unwrap();
|
||||
assert!(result.is_string());
|
||||
}
|
||||
|
||||
@@ -98,3 +98,32 @@ fn to_fixed_of_number() {
|
||||
.unwrap_or_default();
|
||||
assert_eq!(s, "3.14");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_is_integer_true() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(&mut vm, "Number.isInteger(42)").unwrap();
|
||||
assert!(result.as_bool());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_is_integer_false() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(&mut vm, "Number.isInteger(42.5)").unwrap();
|
||||
assert!(!result.as_bool());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_epsilon_is_positive() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(&mut vm, "Number.EPSILON > 0").unwrap();
|
||||
assert!(result.as_bool());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_to_exponential() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(&mut vm, "var n = 123.456; n.toExponential(2)").unwrap();
|
||||
let s = vm.kernel().string_forge().lookup(result.as_string_index()).unwrap_or_default();
|
||||
assert_eq!(s, "1.23e2");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user