summaryrefslogtreecommitdiff
path: root/core/runtime.rs
diff options
context:
space:
mode:
authorMatt Mastracci <matthew@mastracci.com>2023-04-04 06:46:31 -0600
committerGitHub <noreply@github.com>2023-04-04 06:46:31 -0600
commita1764f7690cfdc3e42724fcad29ef954b7e576a4 (patch)
tree1b621ebd7a6ef50687eeb2061740895096136e8a /core/runtime.rs
parent2dc20168371e827b86e2ce0d1d7787139fba68f3 (diff)
refactor(core): Improve ergonomics of managing ASCII strings (#18498)
This is a follow-on to the earlier work in reducing string copies, mainly focused on ensuring that ASCII strings are easy to provide to the JS runtime. While we are replacing a 16-byte reference in a number of places with a 24-byte structure (measured via `std::mem::size_of`), the reduction in copies wins out over the additional size of the arguments passed into functions. Benchmarking shows approximately the same if not slightly less wallclock time/instructions retired, but I believe this continues to open up further refactoring opportunities.
Diffstat (limited to 'core/runtime.rs')
-rw-r--r--core/runtime.rs327
1 files changed, 190 insertions, 137 deletions
diff --git a/core/runtime.rs b/core/runtime.rs
index d68cb3616..89487bc6c 100644
--- a/core/runtime.rs
+++ b/core/runtime.rs
@@ -747,7 +747,6 @@ impl JsRuntime {
{
if let Some(js_files) = ext.get_js_sources() {
for file_source in js_files {
- // TODO(@AaronO): use JsRuntime::execute_static() here to move src off heap
realm.execute_script(
self.v8_isolate(),
file_source.specifier,
@@ -914,16 +913,42 @@ impl JsRuntime {
/// The same `name` value can be used for multiple executions.
///
/// `Error` can usually be downcast to `JsError`.
- pub fn execute_script<S: Into<ModuleCode>>(
+ pub fn execute_script(
&mut self,
name: &'static str,
- source_code: S,
+ source_code: ModuleCode,
) -> Result<v8::Global<v8::Value>, Error> {
self
.global_realm()
.execute_script(self.v8_isolate(), name, source_code)
}
+ /// Executes traditional JavaScript code (traditional = not ES modules).
+ ///
+ /// The execution takes place on the current global context, so it is possible
+ /// to maintain local JS state and invoke this method multiple times.
+ ///
+ /// `name` can be a filepath or any other string, but it is required to be 7-bit ASCII, eg.
+ ///
+ /// - "/some/file/path.js"
+ /// - "<anon>"
+ /// - "[native code]"
+ ///
+ /// The same `name` value can be used for multiple executions.
+ ///
+ /// `Error` can usually be downcast to `JsError`.
+ pub fn execute_script_static(
+ &mut self,
+ name: &'static str,
+ source_code: &'static str,
+ ) -> Result<v8::Global<v8::Value>, Error> {
+ self.global_realm().execute_script(
+ self.v8_isolate(),
+ name,
+ ModuleCode::from_static(source_code),
+ )
+ }
+
/// Takes a snapshot. The isolate should have been created with will_snapshot
/// set to true.
///
@@ -1895,7 +1920,7 @@ impl JsRuntime {
let register_result = load.register_and_recurse(
&mut self.handle_scope(),
&request,
- &info,
+ info,
);
match register_result {
@@ -2071,11 +2096,12 @@ impl JsRuntime {
) -> Result<ModuleId, Error> {
let module_map_rc = Self::module_map(self.v8_isolate());
if let Some(code) = code {
+ let specifier = specifier.as_str().to_owned().into();
let scope = &mut self.handle_scope();
// true for main module
module_map_rc
.borrow_mut()
- .new_es_module(scope, true, specifier, &code, false)
+ .new_es_module(scope, true, specifier, code, false)
.map_err(|e| match e {
ModuleError::Exception(exception) => {
let exception = v8::Local::new(scope, exception);
@@ -2086,12 +2112,12 @@ impl JsRuntime {
}
let mut load =
- ModuleMap::load_main(module_map_rc.clone(), specifier.as_str()).await?;
+ ModuleMap::load_main(module_map_rc.clone(), &specifier).await?;
while let Some(load_result) = load.next().await {
let (request, info) = load_result?;
let scope = &mut self.handle_scope();
- load.register_and_recurse(scope, &request, &info).map_err(
+ load.register_and_recurse(scope, &request, info).map_err(
|e| match e {
ModuleError::Exception(exception) => {
let exception = v8::Local::new(scope, exception);
@@ -2125,11 +2151,12 @@ impl JsRuntime {
) -> Result<ModuleId, Error> {
let module_map_rc = Self::module_map(self.v8_isolate());
if let Some(code) = code {
+ let specifier = specifier.as_str().to_owned().into();
let scope = &mut self.handle_scope();
// false for side module (not main module)
module_map_rc
.borrow_mut()
- .new_es_module(scope, false, specifier, &code, false)
+ .new_es_module(scope, false, specifier, code, false)
.map_err(|e| match e {
ModuleError::Exception(exception) => {
let exception = v8::Local::new(scope, exception);
@@ -2140,12 +2167,12 @@ impl JsRuntime {
}
let mut load =
- ModuleMap::load_side(module_map_rc.clone(), specifier.as_str()).await?;
+ ModuleMap::load_side(module_map_rc.clone(), &specifier).await?;
while let Some(load_result) = load.next().await {
let (request, info) = load_result?;
let scope = &mut self.handle_scope();
- load.register_and_recurse(scope, &request, &info).map_err(
+ load.register_and_recurse(scope, &request, info).map_err(
|e| match e {
ModuleError::Exception(exception) => {
let exception = v8::Local::new(scope, exception);
@@ -2439,7 +2466,7 @@ impl JsRuntime {
/// .expect("Handle the error properly");
/// let source_code = "var a = 0; a + 1";
/// let result = new_realm
-/// .execute_script(runtime.v8_isolate(), "<anon>", source_code)
+/// .execute_script_static(runtime.v8_isolate(), "<anon>", source_code)
/// .expect("Handle the error properly");
/// # drop(result);
/// ```
@@ -2525,17 +2552,30 @@ impl JsRealm {
/// The same `name` value can be used for multiple executions.
///
/// `Error` can usually be downcast to `JsError`.
- pub fn execute_script<S: Into<ModuleCode>>(
+ pub fn execute_script_static(
&self,
isolate: &mut v8::Isolate,
name: &'static str,
- source_code: S,
+ source_code: &'static str,
) -> Result<v8::Global<v8::Value>, Error> {
- // Manual monomorphization (TODO: replace w/momo)
- self.execute_script_inner(isolate, name, source_code.into())
+ self.execute_script(isolate, name, ModuleCode::from_static(source_code))
}
- fn execute_script_inner(
+ /// Executes traditional JavaScript code (traditional = not ES modules) in the
+ /// realm's context.
+ ///
+ /// For info on the [`v8::Isolate`] parameter, check [`JsRealm#panics`].
+ ///
+ /// The `name` parameter can be a filepath or any other string. E.g.:
+ ///
+ /// - "/some/file/path.js"
+ /// - "<anon>"
+ /// - "[native code]"
+ ///
+ /// The same `name` value can be used for multiple executions.
+ ///
+ /// `Error` can usually be downcast to `JsError`.
+ pub fn execute_script(
&self,
isolate: &mut v8::Isolate,
name: &'static str,
@@ -2687,8 +2727,10 @@ pub fn queue_async_op(
#[cfg(test)]
pub mod tests {
use super::*;
+ use crate::ascii_str;
use crate::error::custom_error;
use crate::error::AnyError;
+ use crate::include_ascii_string;
use crate::modules::AssertedModuleType;
use crate::modules::ModuleInfo;
use crate::modules::ModuleSource;
@@ -2787,7 +2829,7 @@ pub mod tests {
});
runtime
- .execute_script(
+ .execute_script_static(
"setup.js",
r#"
function assert(cond) {
@@ -2806,7 +2848,7 @@ pub mod tests {
fn test_ref_unref_ops() {
let (mut runtime, _dispatch_count) = setup(Mode::AsyncDeferred);
runtime
- .execute_script(
+ .execute_script_static(
"filename.js",
r#"
@@ -2824,7 +2866,7 @@ pub mod tests {
assert_eq!(realm.state(isolate).borrow().unrefed_ops.len(), 0);
}
runtime
- .execute_script(
+ .execute_script_static(
"filename.js",
r#"
Deno.core.ops.op_unref_op(p1[promiseIdSymbol]);
@@ -2840,7 +2882,7 @@ pub mod tests {
assert_eq!(realm.state(isolate).borrow().unrefed_ops.len(), 2);
}
runtime
- .execute_script(
+ .execute_script_static(
"filename.js",
r#"
Deno.core.ops.op_ref_op(p1[promiseIdSymbol]);
@@ -2861,7 +2903,7 @@ pub mod tests {
fn test_dispatch() {
let (mut runtime, dispatch_count) = setup(Mode::Async);
runtime
- .execute_script(
+ .execute_script_static(
"filename.js",
r#"
let control = 42;
@@ -2881,7 +2923,7 @@ pub mod tests {
fn test_op_async_promise_id() {
let (mut runtime, _dispatch_count) = setup(Mode::Async);
runtime
- .execute_script(
+ .execute_script_static(
"filename.js",
r#"
@@ -2898,7 +2940,7 @@ pub mod tests {
fn test_dispatch_no_zero_copy_buf() {
let (mut runtime, dispatch_count) = setup(Mode::AsyncZeroCopy(false));
runtime
- .execute_script(
+ .execute_script_static(
"filename.js",
r#"
@@ -2913,7 +2955,7 @@ pub mod tests {
fn test_dispatch_stack_zero_copy_bufs() {
let (mut runtime, dispatch_count) = setup(Mode::AsyncZeroCopy(true));
runtime
- .execute_script(
+ .execute_script_static(
"filename.js",
r#"
@@ -2928,13 +2970,16 @@ pub mod tests {
#[test]
fn test_execute_script_return_value() {
let mut runtime = JsRuntime::new(Default::default());
- let value_global = runtime.execute_script("a.js", "a = 1 + 2").unwrap();
+ let value_global =
+ runtime.execute_script_static("a.js", "a = 1 + 2").unwrap();
{
let scope = &mut runtime.handle_scope();
let value = value_global.open(scope);
assert_eq!(value.integer_value(scope).unwrap(), 3);
}
- let value_global = runtime.execute_script("b.js", "b = 'foobar'").unwrap();
+ let value_global = runtime
+ .execute_script_static("b.js", "b = 'foobar'")
+ .unwrap();
{
let scope = &mut runtime.handle_scope();
let value = value_global.open(scope);
@@ -2951,7 +2996,7 @@ pub mod tests {
let mut runtime = JsRuntime::new(Default::default());
run_in_task(move |cx| {
let value_global = runtime
- .execute_script("a.js", "Promise.resolve(1 + 2)")
+ .execute_script_static("a.js", "Promise.resolve(1 + 2)")
.unwrap();
let v = runtime.poll_value(&value_global, cx);
{
@@ -2962,7 +3007,7 @@ pub mod tests {
}
let value_global = runtime
- .execute_script(
+ .execute_script_static(
"a.js",
"Promise.resolve(new Promise(resolve => resolve(2 + 2)))",
)
@@ -2976,7 +3021,7 @@ pub mod tests {
}
let value_global = runtime
- .execute_script("a.js", "Promise.reject(new Error('fail'))")
+ .execute_script_static("a.js", "Promise.reject(new Error('fail'))")
.unwrap();
let v = runtime.poll_value(&value_global, cx);
assert!(
@@ -2984,7 +3029,7 @@ pub mod tests {
);
let value_global = runtime
- .execute_script("a.js", "new Promise(resolve => {})")
+ .execute_script_static("a.js", "new Promise(resolve => {})")
.unwrap();
let v = runtime.poll_value(&value_global, cx);
matches!(v, Poll::Ready(Err(e)) if e.to_string() == "Promise resolution is still pending but the event loop has already resolved.");
@@ -2995,7 +3040,7 @@ pub mod tests {
async fn test_resolve_value() {
let mut runtime = JsRuntime::new(Default::default());
let value_global = runtime
- .execute_script("a.js", "Promise.resolve(1 + 2)")
+ .execute_script_static("a.js", "Promise.resolve(1 + 2)")
.unwrap();
let result_global = runtime.resolve_value(value_global).await.unwrap();
{
@@ -3005,7 +3050,7 @@ pub mod tests {
}
let value_global = runtime
- .execute_script(
+ .execute_script_static(
"a.js",
"Promise.resolve(new Promise(resolve => resolve(2 + 2)))",
)
@@ -3018,7 +3063,7 @@ pub mod tests {
}
let value_global = runtime
- .execute_script("a.js", "Promise.reject(new Error('fail'))")
+ .execute_script_static("a.js", "Promise.reject(new Error('fail'))")
.unwrap();
let err = runtime.resolve_value(value_global).await.unwrap_err();
assert_eq!(
@@ -3027,7 +3072,7 @@ pub mod tests {
);
let value_global = runtime
- .execute_script("a.js", "new Promise(resolve => {})")
+ .execute_script_static("a.js", "new Promise(resolve => {})")
.unwrap();
let error_string = runtime
.resolve_value(value_global)
@@ -3046,7 +3091,7 @@ pub mod tests {
let v8_isolate_handle = runtime.v8_isolate().thread_safe_handle();
// Run an infinite loop in Webassemby code, which should be terminated.
- let promise = runtime.execute_script("infinite_wasm_loop.js",
+ let promise = runtime.execute_script_static("infinite_wasm_loop.js",
r#"
(async () => {
const wasmCode = new Uint8Array([
@@ -3069,7 +3114,7 @@ pub mod tests {
assert!(ok);
});
let err = runtime
- .execute_script(
+ .execute_script_static(
"infinite_wasm_loop2.js",
"globalThis.wasmInstance.exports.infinite_loop();",
)
@@ -3082,7 +3127,7 @@ pub mod tests {
// Verify that the isolate usable again.
runtime
- .execute_script("simple.js", "1 + 1")
+ .execute_script_static("simple.js", "1 + 1")
.expect("execution should be possible again");
terminator_thread.join().unwrap();
@@ -3103,7 +3148,7 @@ pub mod tests {
});
// Rn an infinite loop, which should be terminated.
- match isolate.execute_script("infinite_loop.js", "for(;;) {}") {
+ match isolate.execute_script_static("infinite_loop.js", "for(;;) {}") {
Ok(_) => panic!("execution should be terminated"),
Err(e) => {
assert_eq!(e.to_string(), "Uncaught Error: execution terminated")
@@ -3117,7 +3162,7 @@ pub mod tests {
// Verify that the isolate usable again.
isolate
- .execute_script("simple.js", "1 + 1")
+ .execute_script_static("simple.js", "1 + 1")
.expect("execution should be possible again");
terminator_thread.join().unwrap();
@@ -3139,7 +3184,7 @@ pub mod tests {
fn syntax_error() {
let mut runtime = JsRuntime::new(Default::default());
let src = "hocuspocus(";
- let r = runtime.execute_script("i.js", src);
+ let r = runtime.execute_script_static("i.js", src);
let e = r.unwrap_err();
let js_error = e.downcast::<JsError>().unwrap();
let frame = js_error.frames.first().unwrap();
@@ -3154,7 +3199,7 @@ pub mod tests {
.execute_script(
"encode_decode_test.js",
// Note: We make this to_owned because it contains non-ASCII chars
- include_str!("encode_decode_test.js").to_owned(),
+ include_str!("encode_decode_test.js").to_owned().into(),
)
.unwrap();
if let Poll::Ready(Err(_)) = runtime.poll_event_loop(cx, false) {
@@ -3170,7 +3215,7 @@ pub mod tests {
runtime
.execute_script(
"serialize_deserialize_test.js",
- include_str!("serialize_deserialize_test.js"),
+ include_ascii_string!("serialize_deserialize_test.js"),
)
.unwrap();
if let Poll::Ready(Err(_)) = runtime.poll_event_loop(cx, false) {
@@ -3198,7 +3243,7 @@ pub mod tests {
});
run_in_task(move |cx| {
runtime
- .execute_script(
+ .execute_script_static(
"error_builder_test.js",
include_str!("error_builder_test.js"),
)
@@ -3216,7 +3261,7 @@ pub mod tests {
will_snapshot: true,
..Default::default()
});
- runtime.execute_script("a.js", "a = 1 + 2").unwrap();
+ runtime.execute_script_static("a.js", "a = 1 + 2").unwrap();
runtime.snapshot()
};
@@ -3226,7 +3271,7 @@ pub mod tests {
..Default::default()
});
runtime2
- .execute_script("check.js", "if (a != 3) throw Error('x')")
+ .execute_script_static("check.js", "if (a != 3) throw Error('x')")
.unwrap();
}
@@ -3237,7 +3282,9 @@ pub mod tests {
will_snapshot: true,
..Default::default()
});
- runtime.execute_script("a.js", "let a = 1 + 2").unwrap();
+ runtime
+ .execute_script_static("a.js", "let a = 1 + 2")
+ .unwrap();
runtime.snapshot()
};
@@ -3250,9 +3297,9 @@ pub mod tests {
let startup_data = {
runtime
- .execute_script("check_a.js", "if (a != 3) throw Error('x')")
+ .execute_script_static("check_a.js", "if (a != 3) throw Error('x')")
.unwrap();
- runtime.execute_script("b.js", "b = 2 + 3").unwrap();
+ runtime.execute_script_static("b.js", "b = 2 + 3").unwrap();
runtime.snapshot()
};
@@ -3263,10 +3310,10 @@ pub mod tests {
..Default::default()
});
runtime
- .execute_script("check_b.js", "if (b != 5) throw Error('x')")
+ .execute_script_static("check_b.js", "if (b != 5) throw Error('x')")
.unwrap();
runtime
- .execute_script("check2.js", "if (!Deno.core) throw Error('x')")
+ .execute_script_static("check2.js", "if (!Deno.core) throw Error('x')")
.unwrap();
}
}
@@ -3279,7 +3326,7 @@ pub mod tests {
..Default::default()
});
runtime
- .execute_script(
+ .execute_script_static(
"a.js",
r#"
Deno.core.ops.op_set_macrotask_callback(() => {
@@ -3304,7 +3351,7 @@ pub mod tests {
..Default::default()
});
runtime2
- .execute_script("check.js", "if (a != 3) throw Error('x')")
+ .execute_script_static("check.js", "if (a != 3) throw Error('x')")
.unwrap();
}
@@ -3315,7 +3362,7 @@ pub mod tests {
will_snapshot: true,
..Default::default()
});
- runtime.execute_script("a.js", "a = 1 + 2").unwrap();
+ runtime.execute_script_static("a.js", "a = 1 + 2").unwrap();
let snap: &[u8] = &runtime.snapshot();
Vec::from(snap).into_boxed_slice()
};
@@ -3326,7 +3373,7 @@ pub mod tests {
..Default::default()
});
runtime2
- .execute_script("check.js", "if (a != 3) throw Error('x')")
+ .execute_script_static("check.js", "if (a != 3) throw Error('x')")
.unwrap();
}
@@ -3351,7 +3398,7 @@ pub mod tests {
fn load(
&self,
_module_specifier: &ModuleSpecifier,
- _maybe_referrer: Option<ModuleSpecifier>,
+ _maybe_referrer: Option<&ModuleSpecifier>,
_is_dyn_import: bool,
) -> Pin<Box<ModuleSourceFuture>> {
async { Err(generic_error("Module loading is not supported")) }
@@ -3366,11 +3413,12 @@ pub mod tests {
});
let specifier = crate::resolve_url("file:///main.js").unwrap();
- let source_code = r#"
+ let source_code = ascii_str!(
+ r#"
export const a = "b";
export default 1 + 2;
"#
- .into();
+ );
let module_id = futures::executor::block_on(
runtime.load_main_module(&specifier, Some(source_code)),
@@ -3435,7 +3483,7 @@ pub mod tests {
},
);
let err = runtime
- .execute_script(
+ .execute_script_static(
"script name",
r#"let s = ""; while(true) { s += "Hello"; }"#,
)
@@ -3488,7 +3536,7 @@ pub mod tests {
);
let err = runtime
- .execute_script(
+ .execute_script_static(
"script name",
r#"let s = ""; while(true) { s += "Hello"; }"#,
)
@@ -3520,7 +3568,7 @@ pub mod tests {
fn load(
&self,
_module_specifier: &ModuleSpecifier,
- _maybe_referrer: Option<ModuleSpecifier>,
+ _maybe_referrer: Option<&ModuleSpecifier>,
_is_dyn_import: bool,
) -> Pin<Box<ModuleSourceFuture>> {
eprintln!("load() should not be called");
@@ -3563,7 +3611,7 @@ pub mod tests {
ModuleInfo {
id,
main,
- name: specifier.to_string(),
+ name: specifier.into(),
requests: vec![crate::modules::ModuleRequest {
specifier: format!("file:///{prev}.js"),
asserted_module_type: AssertedModuleType::JavaScriptOrWasm,
@@ -3577,7 +3625,13 @@ pub mod tests {
let module_map = module_map_rc.borrow();
assert_eq!(module_map.handles.len(), modules.len());
assert_eq!(module_map.info.len(), modules.len());
- assert_eq!(module_map.by_name.len(), modules.len());
+ assert_eq!(
+ module_map.by_name(AssertedModuleType::Json).len()
+ + module_map
+ .by_name(AssertedModuleType::JavaScriptOrWasm)
+ .len(),
+ modules.len()
+ );
assert_eq!(module_map.next_load_id, (modules.len() + 1) as ModuleLoadId);
@@ -3586,8 +3640,8 @@ pub mod tests {
assert_eq!(module_map.info.get(info.id).unwrap(), info);
assert_eq!(
module_map
- .by_name
- .get(&(info.name.clone(), AssertedModuleType::JavaScriptOrWasm))
+ .by_name(AssertedModuleType::JavaScriptOrWasm)
+ .get(&info.name)
.unwrap(),
&SymbolicModule::Mod(info.id)
);
@@ -3610,7 +3664,8 @@ pub mod tests {
});
let specifier = crate::resolve_url("file:///0.js").unwrap();
- let source_code = r#"export function f0() { return "hello world" }"#.into();
+ let source_code =
+ ascii_str!(r#"export function f0() { return "hello world" }"#);
let id = futures::executor::block_on(
runtime.load_side_module(&specifier, Some(source_code)),
)
@@ -3624,7 +3679,7 @@ pub mod tests {
modules.push(ModuleInfo {
id,
main: false,
- name: specifier.to_string(),
+ name: specifier.into(),
requests: vec![],
module_type: ModuleType::JavaScript,
});
@@ -3668,9 +3723,8 @@ pub mod tests {
let source_code = r#"(async () => {
const mod = await import("file:///400.js");
return mod.f400() + " " + Deno.core.ops.op_test();
- })();"#
- .to_string();
- let val = runtime3.execute_script(".", source_code).unwrap();
+ })();"#;
+ let val = runtime3.execute_script_static(".", source_code).unwrap();
let val = futures::executor::block_on(runtime3.resolve_value(val)).unwrap();
{
let scope = &mut runtime3.handle_scope();
@@ -3684,7 +3738,7 @@ pub mod tests {
fn test_error_without_stack() {
let mut runtime = JsRuntime::new(RuntimeOptions::default());
// SyntaxError
- let result = runtime.execute_script(
+ let result = runtime.execute_script_static(
"error_without_stack.js",
r#"
function main() {
@@ -3701,7 +3755,7 @@ main();
#[test]
fn test_error_stack() {
let mut runtime = JsRuntime::new(RuntimeOptions::default());
- let result = runtime.execute_script(
+ let result = runtime.execute_script_static(
"error_stack.js",
r#"
function assert(cond) {
@@ -3727,7 +3781,7 @@ main();
let mut runtime = JsRuntime::new(RuntimeOptions::default());
run_in_task(move |cx| {
runtime
- .execute_script(
+ .execute_script_static(
"error_async_stack.js",
r#"
(async () => {
@@ -3781,7 +3835,7 @@ main();
run_in_task(move |cx| {
runtime
- .execute_script(
+ .execute_script_static(
"test_error_context_sync.js",
r#"
let errMessage;
@@ -3798,7 +3852,7 @@ if (errMessage !== "higher-level sync error: original sync error") {
.unwrap();
let promise = runtime
- .execute_script(
+ .execute_script_static(
"test_error_context_async.js",
r#"
@@ -3830,7 +3884,7 @@ if (errMessage !== "higher-level sync error: original sync error") {
let mut runtime = JsRuntime::new(RuntimeOptions::default());
run_in_task(move |cx| {
runtime
- .execute_script(
+ .execute_script_static(
"pump_message_loop.js",
r#"
function assertEquals(a, b) {
@@ -3860,12 +3914,15 @@ assertEquals(1, notify_return_value);
// noop script, will resolve promise from first script
runtime
- .execute_script("pump_message_loop2.js", r#"assertEquals(1, 1);"#)
+ .execute_script_static(
+ "pump_message_loop2.js",
+ r#"assertEquals(1, 1);"#,
+ )
.unwrap();
// check that promise from `Atomics.waitAsync` has been resolved
runtime
- .execute_script(
+ .execute_script_static(
"pump_message_loop3.js",
r#"assertEquals(globalThis.resolved, true);"#,
)
@@ -3878,7 +3935,7 @@ assertEquals(1, notify_return_value);
let mut runtime = JsRuntime::new(RuntimeOptions::default());
// Call non-existent op so we get error from `core.js`
let error = runtime
- .execute_script(
+ .execute_script_static(
"core_js_stack_frame.js",
"Deno.core.opAsync('non_existent');",
)
@@ -3895,7 +3952,7 @@ assertEquals(1, notify_return_value);
..Default::default()
};
let mut runtime = JsRuntime::new(options);
- runtime.execute_script("<none>", "").unwrap();
+ runtime.execute_script_static("<none>", "").unwrap();
}
#[ignore] // TODO(@littledivy): Fast API ops when snapshot is not loaded.
@@ -3903,7 +3960,7 @@ assertEquals(1, notify_return_value);
fn test_is_proxy() {
let mut runtime = JsRuntime::new(RuntimeOptions::default());
let all_true: v8::Global<v8::Value> = runtime
- .execute_script(
+ .execute_script_static(
"is_proxy.js",
r#"
(function () {
@@ -3951,7 +4008,7 @@ assertEquals(1, notify_return_value);
});
runtime
- .execute_script(
+ .execute_script_static(
"op_async_borrow.js",
"Deno.core.opAsync(\"op_async_borrow\")",
)
@@ -3982,7 +4039,7 @@ assertEquals(1, notify_return_value);
});
runtime
- .execute_script(
+ .execute_script_static(
"op_sync_serialize_object_with_numbers_as_keys.js",
r#"
Deno.core.ops.op_sync_serialize_object_with_numbers_as_keys({
@@ -4024,7 +4081,7 @@ Deno.core.ops.op_sync_serialize_object_with_numbers_as_keys({
});
runtime
- .execute_script(
+ .execute_script_static(
"op_async_serialize_object_with_numbers_as_keys.js",
r#"
@@ -4060,7 +4117,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
});
runtime
- .execute_script(
+ .execute_script_static(
"macrotasks_and_nextticks.js",
r#"
@@ -4094,7 +4151,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
let mut runtime = JsRuntime::new(Default::default());
runtime
- .execute_script(
+ .execute_script_static(
"multiple_macrotasks_and_nextticks.js",
r#"
Deno.core.ops.op_set_macrotask_callback(() => { return true; });
@@ -4137,7 +4194,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
});
runtime
- .execute_script(
+ .execute_script_static(
"has_tick_scheduled.js",
r#"
Deno.core.ops.op_set_macrotask_callback(() => {
@@ -4208,16 +4265,14 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
fn load(
&self,
_module_specifier: &ModuleSpecifier,
- _maybe_referrer: Option<ModuleSpecifier>,
+ _maybe_referrer: Option<&ModuleSpecifier>,
_is_dyn_import: bool,
) -> Pin<Box<ModuleSourceFuture>> {
async move {
- Ok(ModuleSource {
- code: b"console.log('hello world');".into(),
- module_url_specified: "file:///main.js".to_string(),
- module_url_found: "file:///main.js".to_string(),
- module_type: ModuleType::JavaScript,
- })
+ Ok(ModuleSource::for_test(
+ "console.log('hello world');",
+ "file:///main.js",
+ ))
}
.boxed_local()
}
@@ -4230,7 +4285,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
});
let specifier = crate::resolve_url("file:///main.js").unwrap();
- let source_code = "Deno.core.print('hello\\n')".into();
+ let source_code = ascii_str!("Deno.core.print('hello\\n')");
let module_id = futures::executor::block_on(
runtime.load_main_module(&specifier, Some(source_code)),
@@ -4264,7 +4319,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
});
runtime
- .execute_script(
+ .execute_script_static(
"promise_reject_callback.js",
r#"
// Note: |promise| is not the promise created below, it's a child.
@@ -4287,7 +4342,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
assert_eq!(1, PROMISE_REJECT.load(Ordering::Relaxed));
runtime
- .execute_script(
+ .execute_script_static(
"promise_reject_callback.js",
r#"
{
@@ -4332,7 +4387,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
}});
Deno.core.opAsync("op_void_async").then(() => Promise.reject({number}));
"#
- )
+ ).into()
)
.unwrap();
}
@@ -4341,7 +4396,11 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
for (realm, realm_name, number) in realm_expectations {
let reject_value = realm
- .execute_script(runtime.v8_isolate(), "", "globalThis.rejectValue")
+ .execute_script_static(
+ runtime.v8_isolate(),
+ "",
+ "globalThis.rejectValue",
+ )
.unwrap();
let scope = &mut realm.handle_scope(runtime.v8_isolate());
let reject_value = v8::Local::new(scope, reject_value);
@@ -4382,25 +4441,18 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
fn load(
&self,
_module_specifier: &ModuleSpecifier,
- _maybe_referrer: Option<ModuleSpecifier>,
+ _maybe_referrer: Option<&ModuleSpecifier>,
_is_dyn_import: bool,
) -> Pin<Box<ModuleSourceFuture>> {
- let source = r#"
+ let code = r#"
Deno.core.ops.op_set_promise_reject_callback((type, promise, reason) => {
Deno.core.ops.op_promise_reject();
});
throw new Error('top level throw');
"#;
- async move {
- Ok(ModuleSource {
- code: source.into(),
- module_url_specified: "file:///main.js".to_string(),
- module_url_found: "file:///main.js".to_string(),
- module_type: ModuleType::JavaScript,
- })
- }
- .boxed_local()
+ async move { Ok(ModuleSource::for_test(code, "file:///main.js")) }
+ .boxed_local()
}
}
@@ -4434,7 +4486,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
..Default::default()
});
assert!(runtime
- .execute_script(
+ .execute_script_static(
"test_op_return_serde_v8_error.js",
"Deno.core.ops.op_err()"
)
@@ -4459,7 +4511,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
..Default::default()
});
let r = runtime
- .execute_script("test.js", "Deno.core.ops.op_add_4(1, 2, 3, 4)")
+ .execute_script_static("test.js", "Deno.core.ops.op_add_4(1, 2, 3, 4)")
.unwrap();
let scope = &mut runtime.handle_scope();
assert_eq!(r.open(scope).integer_value(scope), Some(10));
@@ -4482,7 +4534,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
..Default::default()
});
let r = runtime
- .execute_script("test.js", "Deno.core.ops.op_foo()")
+ .execute_script_static("test.js", "Deno.core.ops.op_foo()")
.unwrap();
let scope = &mut runtime.handle_scope();
assert!(r.open(scope).is_undefined());
@@ -4511,7 +4563,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
});
runtime
- .execute_script(
+ .execute_script_static(
"test.js",
r#"
const a1 = new Uint8Array([1,2,3]);
@@ -4579,7 +4631,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
..Default::default()
});
runtime
- .execute_script(
+ .execute_script_static(
"test.js",
r#"
if (Deno.core.ops.op_foo() !== 42) {
@@ -4607,9 +4659,9 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
assert_ne!(realm.context(), &main_context);
assert_ne!(realm.global_object(runtime.v8_isolate()), main_global);
- let main_object = runtime.execute_script("", "Object").unwrap();
+ let main_object = runtime.execute_script_static("", "Object").unwrap();
let realm_object = realm
- .execute_script(runtime.v8_isolate(), "", "Object")
+ .execute_script_static(runtime.v8_isolate(), "", "Object")
.unwrap();
assert_ne!(main_object, realm_object);
}
@@ -4628,7 +4680,11 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
});
let realm = runtime.create_realm().unwrap();
let ret = realm
- .execute_script(runtime.v8_isolate(), "", "Deno.core.ops.op_test()")
+ .execute_script_static(
+ runtime.v8_isolate(),
+ "",
+ "Deno.core.ops.op_test()",
+ )
.unwrap();
let scope = &mut realm.handle_scope(runtime.v8_isolate());
@@ -4665,7 +4721,11 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
});
let realm = runtime.create_realm().unwrap();
let ret = realm
- .execute_script(runtime.v8_isolate(), "", "Deno.core.ops.op_test()")
+ .execute_script_static(
+ runtime.v8_isolate(),
+ "",
+ "Deno.core.ops.op_test()",
+ )
.unwrap();
let scope = &mut realm.handle_scope(runtime.v8_isolate());
@@ -4701,7 +4761,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
// Test in both realms
for realm in [runtime.global_realm(), new_realm].into_iter() {
let ret = realm
- .execute_script(
+ .execute_script_static(
runtime.v8_isolate(),
"",
r#"
@@ -4753,7 +4813,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
// Test in both realms
for realm in [global_realm, new_realm].into_iter() {
let ret = realm
- .execute_script(
+ .execute_script_static(
runtime.v8_isolate(),
"",
r#"
@@ -4806,7 +4866,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
let other_realm = runtime.create_realm().unwrap();
main_realm
- .execute_script(
+ .execute_script_static(
runtime.v8_isolate(),
"",
r#"
@@ -4816,7 +4876,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
)
.unwrap();
other_realm
- .execute_script(
+ .execute_script_static(
runtime.v8_isolate(),
"",
r#"
@@ -4828,7 +4888,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
assert!(matches!(runtime.poll_event_loop(cx, false), Poll::Pending));
main_realm
- .execute_script(
+ .execute_script_static(
runtime.v8_isolate(),
"",
r#"
@@ -4840,7 +4900,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
assert!(matches!(runtime.poll_event_loop(cx, false), Poll::Pending));
other_realm
- .execute_script(
+ .execute_script_static(
runtime.v8_isolate(),
"",
r#"
@@ -4861,7 +4921,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
// Verify that "array by copy" proposal is enabled (https://github.com/tc39/proposal-change-array-by-copy)
let mut runtime = JsRuntime::new(Default::default());
assert!(runtime
- .execute_script(
+ .execute_script_static(
"test_array_by_copy.js",
"const a = [1, 2, 3];
const b = a.toReversed();
@@ -4880,7 +4940,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
// Verify that "resizable ArrayBuffer" is disabled
let mut runtime = JsRuntime::new(Default::default());
runtime
- .execute_script(
+ .execute_script_static(
"test_rab.js",
r#"const a = new ArrayBuffer(100, {maxByteLength: 200});
if (a.byteLength !== 100) {
@@ -4916,24 +4976,17 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
fn load(
&self,
_module_specifier: &ModuleSpecifier,
- _maybe_referrer: Option<ModuleSpecifier>,
+ _maybe_referrer: Option<&ModuleSpecifier>,
_is_dyn_import: bool,
) -> Pin<Box<ModuleSourceFuture>> {
- let source = r#"
+ let code = r#"
// This module doesn't really exist, just verifying that we'll get
// an error when specifier starts with "ext:".
import { core } from "ext:core.js";
"#;
- async move {
- Ok(ModuleSource {
- code: source.into(),
- module_url_specified: "file:///main.js".to_string(),
- module_url_found: "file:///main.js".to_string(),
- module_type: ModuleType::JavaScript,
- })
- }
- .boxed_local()
+ async move { Ok(ModuleSource::for_test(code, "file:///main.js")) }
+ .boxed_local()
}
}