From a5cda16824ad8ccd3910e4ee436d44016982ecd0 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Wed, 21 Aug 2024 16:33:48 +0200 Subject: [PATCH 01/52] refactor: rework error handling --- Cargo.lock | 1 + core/Cargo.toml | 1 + core/convert.rs | 10 +- core/error.rs | 197 +++++++++++------- core/examples/ts_module_loader.rs | 4 +- core/extension_set.rs | 9 +- core/extensions.rs | 7 +- core/inspector.rs | 4 +- core/io/mod.rs | 4 +- core/io/resource.rs | 23 +- core/io/resource_table.rs | 21 +- core/module_specifier.rs | 113 +++++----- core/modules/loaders.rs | 130 ++++++++---- core/modules/map.rs | 81 ++++--- core/modules/mod.rs | 30 +-- core/modules/recursive_load.rs | 15 +- core/modules/tests.rs | 2 +- core/ops_builtin.rs | 38 ++-- core/ops_builtin_v8.rs | 61 +++--- core/resources.rs | 1 - core/runtime/bindings.rs | 13 +- core/runtime/exception_state.rs | 4 +- core/runtime/jsrealm.rs | 20 +- core/runtime/jsruntime.rs | 100 +++++---- .../op_driver/futures_unordered_driver.rs | 3 +- core/runtime/op_driver/mod.rs | 8 +- core/runtime/op_driver/op_results.rs | 14 +- core/runtime/ops.rs | 13 +- core/runtime/snapshot.rs | 13 +- dcore/src/main.rs | 4 +- testing/checkin/runner/ops_error.rs | 8 +- testing/checkin/runner/ops_worker.rs | 4 +- testing/checkin/runner/ts_module_loader.rs | 45 ++-- 33 files changed, 543 insertions(+), 458 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3fdd6808d..9b59940e5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -584,6 +584,7 @@ dependencies = [ "smallvec", "sourcemap", "static_assertions", + "thiserror", "tokio", "twox-hash", "unicycle", diff --git a/core/Cargo.toml b/core/Cargo.toml index d554ed885..8718f0ab1 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -47,6 +47,7 @@ static_assertions.workspace = true tokio.workspace = true url.workspace = true v8.workspace = true +thiserror = "1.0.60" [dev-dependencies] bencher.workspace = true diff --git a/core/convert.rs b/core/convert.rs index 5c04803e6..672f3d55c 100644 --- a/core/convert.rs +++ b/core/convert.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::StdAnyError; +use crate::error::PubError; use crate::runtime::ops; use std::convert::Infallible; @@ -122,7 +122,7 @@ pub trait FromV8<'a>: Sized { // impls #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -/// Marks a numeric type as being serialized as a v8 `smi` in a `v8::Integer`. +/// Marks a numeric type as being serialized as a v8 `smi` in a `v8::Integer`. #[repr(transparent)] pub struct Smi(pub T); @@ -170,7 +170,7 @@ impl<'a, T: SmallInt> ToV8<'a> for Smi { } impl<'a, T: SmallInt> FromV8<'a> for Smi { - type Error = StdAnyError; + type Error = PubError; #[inline] fn from_v8( @@ -185,7 +185,7 @@ impl<'a, T: SmallInt> FromV8<'a> for Smi { } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -/// Marks a numeric type as being serialized as a v8 `number` in a `v8::Number`. +/// Marks a numeric type as being serialized as a v8 `number` in a `v8::Number`. #[repr(transparent)] pub struct Number(pub T); @@ -240,7 +240,7 @@ impl<'a, T: Numeric> ToV8<'a> for Number { } impl<'a, T: Numeric> FromV8<'a> for Number { - type Error = StdAnyError; + type Error = PubError; #[inline] fn from_v8( _scope: &mut v8::HandleScope<'a>, diff --git a/core/error.rs b/core/error.rs index ba4a2d46b..b27277a15 100644 --- a/core/error.rs +++ b/core/error.rs @@ -7,10 +7,10 @@ use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write as _; - -use anyhow::Error; +use thiserror::__private::AsDynError; use v8::Object; +pub use crate::modules::ModuleLoaderError; use crate::runtime::v8_static_strings; use crate::runtime::JsRealm; use crate::runtime::JsRuntime; @@ -22,115 +22,153 @@ use crate::FastStaticString; // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. pub type AnyError = anyhow::Error; -pub type JsErrorCreateFn = dyn Fn(JsError) -> Error; -pub type GetErrorClassFn = &'static dyn for<'e> Fn(&'e Error) -> &'static str; +pub type JsErrorCreateFn = dyn Fn(JsError) -> anyhow::Error; +pub type GetErrorClassFn = + &'static dyn for<'e> Fn(&'e anyhow::Error) -> &'static str; + +#[derive(Debug, thiserror::Error)] +pub enum PubError { + #[error("level await is not allowed in extensions")] + TLA(JsError), + #[error(transparent)] + Js(#[from] JsError), + #[error(transparent)] + Io(#[from] std::io::Error), + #[error(transparent)] + ExtensionTranspiler(anyhow::Error), + #[error("Failed to parse {0}")] + Parse(FastStaticString), + #[error("Failed to execute {0}")] + Execute(FastStaticString), + #[error( + "Following modules were passed to ExtModuleLoader but never used:\n{}", + .0.iter().map(|s| format!(" - {}\n", s)).collect::>().join("") + )] + UnusedModules(Vec), + #[error( + "Following modules were not evaluated; make sure they are imported from other code:\n{}", + .0.iter().map(|s| format!(" - {}\n", s)).collect::>().join("") + )] + NonEvaluatedModules(Vec), + #[error("not present in the module map")] + MissingFromModuleMap(String), + #[error(transparent)] + ModuleLoader(Box), + #[error("Could not execute {specifier}")] + CouldNotExecute { error: Box, specifier: String }, + #[error( + "\"npm:\" specifiers are currently not supported in import.meta.resolve()" + )] + NpmMetaResolve, + #[error(transparent)] + Custom(#[from] CustomError), + #[error(transparent)] + Url(#[from] url::ParseError), + #[error(transparent)] + FutureCanceled(#[from] futures::channel::oneshot::Canceled), + #[error( + "Cannot evaluate module, because JavaScript execution has been terminated" + )] + ExecutionTerminated, + #[error("Promise resolution is still pending but the event loop has already resolved." + )] + PendingPromiseResolution, + #[error(transparent)] + Anyhow(anyhow::Error), +} + +impl From for PubError { + fn from(err: ModuleLoaderError) -> Self { + PubError::ModuleLoader(Box::new(err)) + } +} + +pub trait JsClassError: std::error::Error { + fn get_class(&self) -> &'static str; + fn get_message(&self) -> Cow<'static, str> { + self.to_string() + } +} + +/// A simple error type that lets the creator specify both the error message and +/// the error class name. This type is private; externally it only ever appears +/// wrapped in an `anyhow::Error`. To retrieve the error class name from a wrapped +/// `CustomError`, use the function `get_custom_error_class()`. +#[derive(Debug, thiserror::Error)] +#[error("{message}")] +pub struct CustomError { + pub class: &'static str, + message: Cow<'static, str>, +} + +impl JsClassError for CustomError { + fn get_class(&self) -> &'static str { + self.class + } + + fn get_message(&self) -> Cow<'static, str> { + self.message.clone() + } +} /// Creates a new error with a caller-specified error class name and message. pub fn custom_error( class: &'static str, message: impl Into>, -) -> Error { - CustomError { +) -> PubError { + PubError::Custom(CustomError { class, message: message.into(), - } - .into() + }) } -pub fn generic_error(message: impl Into>) -> Error { +pub fn generic_error(message: impl Into>) -> PubError { custom_error("Error", message) } -pub fn type_error(message: impl Into>) -> Error { +pub fn type_error(message: impl Into>) -> PubError { custom_error("TypeError", message) } -pub fn range_error(message: impl Into>) -> Error { +pub fn range_error(message: impl Into>) -> PubError { custom_error("RangeError", message) } -pub fn invalid_hostname(hostname: &str) -> Error { +pub fn invalid_hostname(hostname: &str) -> PubError { type_error(format!("Invalid hostname: '{hostname}'")) } -pub fn uri_error(message: impl Into>) -> Error { +pub fn uri_error(message: impl Into>) -> PubError { custom_error("URIError", message) } -pub fn bad_resource(message: impl Into>) -> Error { +pub fn bad_resource(message: impl Into>) -> PubError { custom_error("BadResource", message) } -pub fn bad_resource_id() -> Error { +pub fn bad_resource_id() -> PubError { custom_error("BadResource", "Bad resource ID") } -pub fn not_supported() -> Error { +pub fn not_supported() -> PubError { custom_error("NotSupported", "The operation is not supported") } -pub fn resource_unavailable() -> Error { +pub fn resource_unavailable() -> PubError { custom_error( "Busy", "Resource is unavailable because it is in use by a promise", ) } -/// A simple error type that lets the creator specify both the error message and -/// the error class name. This type is private; externally it only ever appears -/// wrapped in an `anyhow::Error`. To retrieve the error class name from a wrapped -/// `CustomError`, use the function `get_custom_error_class()`. -#[derive(Debug)] -struct CustomError { - class: &'static str, - message: Cow<'static, str>, -} - -impl Display for CustomError { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - f.write_str(&self.message) - } -} - -impl std::error::Error for CustomError {} - -/// If this error was crated with `custom_error()`, return the specified error -/// class name. In all other cases this function returns `None`. -pub fn get_custom_error_class(error: &Error) -> Option<&'static str> { +pub fn get_custom_error_class(error: &anyhow::Error) -> Option<&'static str> { error.downcast_ref::().map(|e| e.class) } -/// A wrapper around `anyhow::Error` that implements `std::error::Error` -#[repr(transparent)] -pub struct StdAnyError(pub Error); -impl std::fmt::Debug for StdAnyError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self.0) - } -} - -impl std::fmt::Display for StdAnyError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.0) - } -} - -impl std::error::Error for StdAnyError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - self.0.source() - } -} - -impl From for StdAnyError { - fn from(err: Error) -> Self { - Self(err) - } -} - pub fn to_v8_error<'a>( scope: &mut v8::HandleScope<'a>, get_class: GetErrorClassFn, - error: &Error, + error: &anyhow::Error, ) -> v8::Local<'a, v8::Value> { let tc_scope = &mut v8::TryCatch::new(scope); let cb = JsRealm::exception_state_from_scope(tc_scope) @@ -501,7 +539,7 @@ impl JsError { // TODO(mmastrac): we need consistency around when we insert "in promise" and when we don't. For now, we // are going to manually replace this part of the string. && (a.exception_message == b.exception_message - || a.exception_message.replace(" (in promise) ", " ") == b.exception_message.replace(" (in promise) ", " ")) + || a.exception_message.replace(" (in promise) ", " ") == b.exception_message.replace(" (in promise) ", " ")) && a.frames == b.frames && a.source_line == b.source_line && a.source_line_frame_index == b.source_line_frame_index @@ -768,15 +806,24 @@ impl Display for JsError { // values of type v8::Global. pub(crate) fn to_v8_type_error( scope: &mut v8::HandleScope, - err: Error, + err: PubError, ) -> v8::Global { let err_string = err.to_string(); - let error_chain = err - .chain() - .skip(1) - .filter(|e| e.to_string() != err_string) - .map(|e| e.to_string()) - .collect::>(); + let mut error_chain = vec![]; + let mut intermediary_error = Some(err.as_dyn_error()); + + while let Some(err) = intermediary_error { + if let Some(source) = err.source() { + let source_str = source.to_string(); + if source_str != err_string { + error_chain.push(source_str); + } + + intermediary_error = Some(source); + } else { + intermediary_error = None; + } + } let message = if !error_chain.is_empty() { format!( @@ -924,7 +971,7 @@ pub(crate) fn exception_to_err_result( exception: v8::Local, mut in_promise: bool, clear_error: bool, -) -> Result { +) -> Result { let state = JsRealm::exception_state_from_scope(scope); let mut was_terminating_execution = scope.is_execution_terminating(); diff --git a/core/examples/ts_module_loader.rs b/core/examples/ts_module_loader.rs index 332963b49..8f0fa6c91 100644 --- a/core/examples/ts_module_loader.rs +++ b/core/examples/ts_module_loader.rs @@ -15,7 +15,6 @@ use anyhow::Error; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; -use deno_core::error::AnyError; use deno_core::resolve_import; use deno_core::resolve_path; use deno_core::JsRuntime; @@ -59,7 +58,7 @@ impl ModuleLoader for TypescriptModuleLoader { fn load( source_maps: SourceMapStore, module_specifier: &ModuleSpecifier, - ) -> Result { + ) -> Result { let path = module_specifier .to_file_path() .map_err(|_| anyhow!("Only file:// URLs are supported."))?; @@ -164,4 +163,5 @@ fn main() -> Result<(), Error> { .build() .unwrap() .block_on(future) + .map_err(|e| e.into()) } diff --git a/core/extension_set.rs b/core/extension_set.rs index 9f111f574..712df8b78 100644 --- a/core/extension_set.rs +++ b/core/extension_set.rs @@ -2,8 +2,7 @@ use std::cell::RefCell; use std::iter::Chain; use std::rc::Rc; - -use crate::error::AnyError; +use crate::error::PubError; use crate::extensions::Extension; use crate::extensions::ExtensionSourceType; use crate::extensions::GlobalObjectMiddlewareFn; @@ -243,13 +242,13 @@ fn load( transpiler: Option<&ExtensionTranspiler>, source: &ExtensionFileSource, load_callback: &mut impl FnMut(&ExtensionFileSource), -) -> Result<(ModuleCodeString, Option), AnyError> { +) -> Result<(ModuleCodeString, Option), PubError> { load_callback(source); let mut source_code = source.load()?; let mut source_map = None; if let Some(transpiler) = transpiler { (source_code, source_map) = - transpiler(ModuleName::from_static(source.specifier), source_code)?; + transpiler(ModuleName::from_static(source.specifier), source_code).map_err(PubError::ExtensionTranspiler)?; } let mut maybe_source_map = None; if let Some(source_map) = source_map { @@ -262,7 +261,7 @@ pub fn into_sources_and_source_maps( transpiler: Option<&ExtensionTranspiler>, extensions: &[Extension], mut load_callback: impl FnMut(&ExtensionFileSource), -) -> Result { +) -> Result { let mut sources = LoadedSources::default(); for extension in extensions { diff --git a/core/extensions.rs b/core/extensions.rs index 40270b4ce..2f97ba5aa 100644 --- a/core/extensions.rs +++ b/core/extensions.rs @@ -5,8 +5,6 @@ use crate::ops::OpMetadata; use crate::runtime::bindings; use crate::FastStaticString; use crate::OpState; -use anyhow::Context as _; -use anyhow::Error; use std::borrow::Cow; use std::marker::PhantomData; use std::sync::Arc; @@ -114,7 +112,7 @@ impl ExtensionFileSource { } #[allow(deprecated)] - pub fn load(&self) -> Result { + pub fn load(&self) -> Result { match &self.code { ExtensionFileSourceCode::LoadedFromMemoryDuringSnapshot(code) | ExtensionFileSourceCode::IncludedInBinary(code) => { @@ -127,8 +125,7 @@ impl ExtensionFileSource { Ok(IntoModuleCodeString::into_module_code(*code)) } ExtensionFileSourceCode::LoadedFromFsDuringSnapshot(path) => { - let msg = || format!("Failed to read \"{}\"", path); - let s = std::fs::read_to_string(path).with_context(msg)?; + let s = std::fs::read_to_string(path)?; debug_assert!( s.is_ascii(), "Extension code must be 7-bit ASCII: {} (found {})", diff --git a/core/inspector.rs b/core/inspector.rs index 1683120ab..7896da6c1 100644 --- a/core/inspector.rs +++ b/core/inspector.rs @@ -5,6 +5,7 @@ //! use crate::error::generic_error; +use crate::error::PubError; use crate::futures::channel::mpsc; use crate::futures::channel::mpsc::UnboundedReceiver; use crate::futures::channel::mpsc::UnboundedSender; @@ -19,7 +20,6 @@ use crate::futures::task::Context; use crate::futures::task::Poll; use crate::serde_json::json; use crate::serde_json::Value; -use anyhow::Error; use parking_lot::Mutex; use std::cell::BorrowMutError; use std::cell::RefCell; @@ -766,7 +766,7 @@ impl LocalInspectorSession { &mut self, method: &str, params: Option, - ) -> Result { + ) -> Result { let id = self.next_message_id; self.next_message_id += 1; diff --git a/core/io/mod.rs b/core/io/mod.rs index 68a2b4d04..bb32b3367 100644 --- a/core/io/mod.rs +++ b/core/io/mod.rs @@ -6,7 +6,6 @@ // resources. Resources may or may not correspond to a real operating system // file descriptor (hence the different name). -use anyhow::Error; use futures::Future; use std::pin::Pin; @@ -28,7 +27,8 @@ pub use resource_table::ResourceId; pub use resource_table::ResourceTable; /// Returned by resource shutdown methods -pub type AsyncResult = Pin>>>; +pub type AsyncResult = + Pin>>>; pub enum WriteOutcome { Partial { nwritten: usize, view: BufView }, diff --git a/core/io/resource.rs b/core/io/resource.rs index c4796e151..37d3e45cf 100644 --- a/core/io/resource.rs +++ b/core/io/resource.rs @@ -7,13 +7,13 @@ // file descriptor (hence the different name). use crate::error::not_supported; +use crate::error::AnyError; use crate::io::AsyncResult; use crate::io::BufMutView; use crate::io::BufView; use crate::io::WriteOutcome; use crate::ResourceHandle; use crate::ResourceHandleFd; -use anyhow::Error; use std::any::type_name; use std::any::Any; use std::any::TypeId; @@ -85,7 +85,7 @@ pub trait Resource: Any + 'static { /// implement `read_byob()`. fn read(self: Rc, limit: usize) -> AsyncResult { _ = limit; - Box::pin(futures::future::err(not_supported())) + Box::pin(futures::future::err(not_supported().into())) } /// Read a single chunk of data from the resource into the provided `BufMutView`. @@ -110,8 +110,8 @@ pub trait Resource: Any + 'static { } /// Write an error state to this resource, if the resource supports it. - fn write_error(self: Rc, _error: Error) -> AsyncResult<()> { - Box::pin(futures::future::err(not_supported())) + fn write_error(self: Rc, _error: AnyError) -> AsyncResult<()> { + Box::pin(futures::future::err(not_supported().into())) } /// Write a single chunk of data to the resource. The operation may not be @@ -123,7 +123,7 @@ pub trait Resource: Any + 'static { /// with a "not supported" error. fn write(self: Rc, buf: BufView) -> AsyncResult { _ = buf; - Box::pin(futures::future::err(not_supported())) + Box::pin(futures::future::err(not_supported().into())) } /// Write an entire chunk of data to the resource. Unlike `write()`, this will @@ -155,15 +155,18 @@ pub trait Resource: Any + 'static { } /// The same as [`read_byob()`][Resource::read_byob], but synchronous. - fn read_byob_sync(self: Rc, data: &mut [u8]) -> Result { + fn read_byob_sync( + self: Rc, + data: &mut [u8], + ) -> Result { _ = data; - Err(not_supported()) + Err(not_supported().into()) } /// The same as [`write()`][Resource::write], but synchronous. - fn write_sync(self: Rc, data: &[u8]) -> Result { + fn write_sync(self: Rc, data: &[u8]) -> Result { _ = data; - Err(not_supported()) + Err(not_supported().into()) } /// The shutdown method can be used to asynchronously close the resource. It @@ -172,7 +175,7 @@ pub trait Resource: Any + 'static { /// If this method is not implemented, the default implementation will error /// with a "not supported" error. fn shutdown(self: Rc) -> AsyncResult<()> { - Box::pin(futures::future::err(not_supported())) + Box::pin(futures::future::err(not_supported().into())) } /// Resources may implement the `close()` trait method if they need to do diff --git a/core/io/resource_table.rs b/core/io/resource_table.rs index 49157d20d..dec488cbb 100644 --- a/core/io/resource_table.rs +++ b/core/io/resource_table.rs @@ -5,7 +5,7 @@ use super::ResourceHandleFd; use super::ResourceHandleSocket; use crate::error::bad_resource_id; use crate::error::custom_error; -use anyhow::Error; +use crate::error::PubError; use std::borrow::Cow; use std::collections::BTreeMap; use std::rc::Rc; @@ -80,7 +80,7 @@ impl ResourceTable { /// Returns a reference counted pointer to the resource of type `T` with the /// given `rid`. If `rid` is not present or has a type different than `T`, /// this function returns `None`. - pub fn get(&self, rid: ResourceId) -> Result, Error> { + pub fn get(&self, rid: ResourceId) -> Result, PubError> { self .index .get(&rid) @@ -89,7 +89,7 @@ impl ResourceTable { .ok_or_else(bad_resource_id) } - pub fn get_any(&self, rid: ResourceId) -> Result, Error> { + pub fn get_any(&self, rid: ResourceId) -> Result, PubError> { self.index.get(&rid).cloned().ok_or_else(bad_resource_id) } @@ -113,7 +113,10 @@ impl ResourceTable { /// assume that `Rc::strong_count(&returned_rc)` is always equal to 1 on success. /// In particular, be really careful when you want to extract the inner value of /// type `T` from `Rc`. - pub fn take(&mut self, rid: ResourceId) -> Result, Error> { + pub fn take( + &mut self, + rid: ResourceId, + ) -> Result, PubError> { let resource = self.get::(rid)?; self.index.remove(&rid); Ok(resource) @@ -130,7 +133,7 @@ impl ResourceTable { pub fn take_any( &mut self, rid: ResourceId, - ) -> Result, Error> { + ) -> Result, PubError> { self.index.remove(&rid).ok_or_else(bad_resource_id) } @@ -141,7 +144,7 @@ impl ResourceTable { /// may implement the `close()` method to perform clean-ups such as canceling /// ops. #[deprecated = "This method may deadlock. Use take() and close() instead."] - pub fn close(&mut self, rid: ResourceId) -> Result<(), Error> { + pub fn close(&mut self, rid: ResourceId) -> Result<(), PubError> { self .index .remove(&rid) @@ -170,7 +173,7 @@ impl ResourceTable { /// Retrieves the [`ResourceHandleFd`] for a given resource, for potential optimization /// purposes within ops. - pub fn get_fd(&self, rid: ResourceId) -> Result { + pub fn get_fd(&self, rid: ResourceId) -> Result { let Some(handle) = self.get_any(rid)?.backing_handle() else { return Err(bad_resource_id()); }; @@ -188,7 +191,7 @@ impl ResourceTable { pub fn get_socket( &self, rid: ResourceId, - ) -> Result { + ) -> Result { let Some(handle) = self.get_any(rid)?.backing_handle() else { return Err(bad_resource_id()); }; @@ -206,7 +209,7 @@ impl ResourceTable { pub fn get_handle( &self, rid: ResourceId, - ) -> ::std::result::Result { + ) -> Result { let Some(handle) = self.get_any(rid)?.backing_handle() else { return Err(bad_resource_id()); }; diff --git a/core/module_specifier.rs b/core/module_specifier.rs index 30cdf2d59..5c9f351e9 100644 --- a/core/module_specifier.rs +++ b/core/module_specifier.rs @@ -1,53 +1,31 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::normalize_path; -use std::error::Error; -use std::fmt; use std::path::Path; use std::path::PathBuf; use url::ParseError; use url::Url; /// Error indicating the reason resolving a module specifier failed. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] pub enum ModuleResolutionError { - InvalidUrl(ParseError), - InvalidBaseUrl(ParseError), + #[error("invalid URL: {0}")] + InvalidUrl(#[source] ParseError), + #[error("invalid base URL for relative import: {0}")] + InvalidBaseUrl(#[source] ParseError), + #[error("invalid module path: {0:?}")] InvalidPath(PathBuf), - ImportPrefixMissing(String, Option), + #[error( + "Relative import path \"{specifier}\" not prefixed with / or ./ or ../{}", + .maybe_referrer.as_ref().map_or(String::new(), |referrer| format!(" from \"{referrer}\"")) + )] + ImportPrefixMissing { + specifier: String, + maybe_referrer: Option, + }, } use ModuleResolutionError::*; -impl Error for ModuleResolutionError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - InvalidUrl(ref err) | InvalidBaseUrl(ref err) => Some(err), - _ => None, - } - } -} - -impl fmt::Display for ModuleResolutionError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - InvalidUrl(ref err) => write!(f, "invalid URL: {err}"), - InvalidBaseUrl(ref err) => { - write!(f, "invalid base URL for relative import: {err}") - } - InvalidPath(ref path) => write!(f, "invalid module path: {path:?}"), - ImportPrefixMissing(ref specifier, ref maybe_referrer) => write!( - f, - "Relative import path \"{}\" not prefixed with / or ./ or ../{}", - specifier, - match maybe_referrer { - Some(referrer) => format!(" from \"{referrer}\""), - None => String::new(), - } - ), - } - } -} - /// Resolved module specifier pub type ModuleSpecifier = Url; @@ -76,7 +54,10 @@ pub fn resolve_import( } else { Some(base.to_string()) }; - return Err(ImportPrefixMissing(specifier.to_string(), maybe_referrer)); + return Err(ImportPrefixMissing { + specifier: specifier.to_string(), + maybe_referrer, + }); } // 3. Return the result of applying the URL parser to specifier with base @@ -252,50 +233,60 @@ mod tests { ( "awesome.ts", "", - ImportPrefixMissing( - "awesome.ts".to_string(), - Some("".to_string()), - ), + ImportPrefixMissing { + specifier: "awesome.ts".to_string(), + maybe_referrer: Some("".to_string()), + }, ), ( "005_more_imports.ts", "http://deno.land/core/tests/006_url_imports.ts", - ImportPrefixMissing( - "005_more_imports.ts".to_string(), - Some("http://deno.land/core/tests/006_url_imports.ts".to_string()), - ), + ImportPrefixMissing { + specifier: "005_more_imports.ts".to_string(), + maybe_referrer: Some( + "http://deno.land/core/tests/006_url_imports.ts".to_string(), + ), + }, ), ( ".tomato", "http://deno.land/core/tests/006_url_imports.ts", - ImportPrefixMissing( - ".tomato".to_string(), - Some("http://deno.land/core/tests/006_url_imports.ts".to_string()), - ), + ImportPrefixMissing { + specifier: ".tomato".to_string(), + maybe_referrer: Some( + "http://deno.land/core/tests/006_url_imports.ts".to_string(), + ), + }, ), ( "..zucchini.mjs", "http://deno.land/core/tests/006_url_imports.ts", - ImportPrefixMissing( - "..zucchini.mjs".to_string(), - Some("http://deno.land/core/tests/006_url_imports.ts".to_string()), - ), + ImportPrefixMissing { + specifier: "..zucchini.mjs".to_string(), + maybe_referrer: Some( + "http://deno.land/core/tests/006_url_imports.ts".to_string(), + ), + }, ), ( r".\yam.es", "http://deno.land/core/tests/006_url_imports.ts", - ImportPrefixMissing( - r".\yam.es".to_string(), - Some("http://deno.land/core/tests/006_url_imports.ts".to_string()), - ), + ImportPrefixMissing { + specifier: r".\yam.es".to_string(), + maybe_referrer: Some( + "http://deno.land/core/tests/006_url_imports.ts".to_string(), + ), + }, ), ( r"..\yam.es", "http://deno.land/core/tests/006_url_imports.ts", - ImportPrefixMissing( - r"..\yam.es".to_string(), - Some("http://deno.land/core/tests/006_url_imports.ts".to_string()), - ), + ImportPrefixMissing { + specifier: r"..\yam.es".to_string(), + maybe_referrer: Some( + "http://deno.land/core/tests/006_url_imports.ts".to_string(), + ), + }, ), ( "https://eggplant:b/c", diff --git a/core/modules/loaders.rs b/core/modules/loaders.rs index 359b5f3fa..ab31ae406 100644 --- a/core/modules/loaders.rs +++ b/core/modules/loaders.rs @@ -13,10 +13,8 @@ use crate::modules::ResolutionKind; use crate::resolve_import; use crate::ModuleSourceCode; -use anyhow::anyhow; -use anyhow::bail; use anyhow::Context; -use anyhow::Error; +use deno_core::error::PubError; use futures::future::FutureExt; use std::cell::RefCell; use std::collections::HashMap; @@ -24,12 +22,52 @@ use std::future::Future; use std::pin::Pin; use std::rc::Rc; +#[derive(Debug, thiserror::Error)] +pub enum ModuleLoaderError { + #[error("Specifier \"{0}\" was not passed as an extension module and was not included in the snapshot.")] + SpecifierExcludedFromSnapshot(ModuleSpecifier), + #[error("Specifier \"{0}\" cannot be lazy-loaded as it was not included in the binary.")] + SpecifierMissingLazyLoadable(ModuleSpecifier), + #[error( + "\"npm:\" specifiers are currently not supported in import.meta.resolve()" + )] + NpmUnsupportedMetaResolve, + #[error("Attempted to load JSON module without specifying \"type\": \"json\" attribute in the import statement.")] + JsonMissingAttribute, + #[error("Module not found")] + NotFound, + #[error( + "Module loading is not supported; attempted to load: \"{specifier}\" from \"{}\"", + .maybe_referrer.as_ref().map_or("(no referrer)", |referrer| referrer.as_str()) + )] + Unsupported { + specifier: ModuleSpecifier, + maybe_referrer: Option, + }, + #[error(transparent)] + Resolution(#[from] crate::ModuleResolutionError), + #[error(transparent)] + Other(#[from] PubError), +} + +impl From for ModuleLoaderError { + fn from(err: anyhow::Error) -> Self { + ModuleLoaderError::Other(PubError::Anyhow(err)) + } +} + +impl From for ModuleLoaderError { + fn from(err: std::io::Error) -> Self { + ModuleLoaderError::Other(PubError::Io(err)) + } +} + /// Result of calling `ModuleLoader::load`. pub enum ModuleLoadResponse { /// Source file is available synchronously - eg. embedder might have /// collected all the necessary sources in `ModuleLoader::prepare_module_load`. /// Slightly cheaper than `Async` as it avoids boxing. - Sync(Result), + Sync(Result), /// Source file needs to be loaded. Requires boxing due to recrusive /// nature of module loading. @@ -52,7 +90,7 @@ pub trait ModuleLoader { specifier: &str, referrer: &str, kind: ResolutionKind, - ) -> Result; + ) -> Result; /// Given ModuleSpecifier, load its source code. /// @@ -79,7 +117,7 @@ pub trait ModuleLoader { _module_specifier: &ModuleSpecifier, _maybe_referrer: Option, _is_dyn_import: bool, - ) -> Pin>>> { + ) -> Pin>>> { async { Ok(()) }.boxed_local() } @@ -133,7 +171,7 @@ impl ModuleLoader for NoopModuleLoader { specifier: &str, referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { Ok(resolve_import(specifier, referrer)?) } @@ -144,55 +182,45 @@ impl ModuleLoader for NoopModuleLoader { _is_dyn_import: bool, _requested_module_type: RequestedModuleType, ) -> ModuleLoadResponse { - let maybe_referrer = maybe_referrer - .map(|s| s.as_str()) - .unwrap_or("(no referrer)"); - let err = generic_error( - format!( - "Module loading is not supported; attempted to load: \"{module_specifier}\" from \"{maybe_referrer}\"", - ) - ); - ModuleLoadResponse::Sync(Err(err)) + ModuleLoadResponse::Sync(Err(ModuleLoaderError::Unsupported { + specifier: module_specifier.clone(), + maybe_referrer: maybe_referrer.cloned(), + })) } } /// Function that can be passed to the `ExtModuleLoader` that allows to /// transpile sources before passing to V8. pub type ExtModuleLoaderCb = - Box Result>; + Box Result>; pub(crate) struct ExtModuleLoader { sources: RefCell>, } impl ExtModuleLoader { - pub fn new( - loaded_sources: Vec<(ModuleName, ModuleCodeString)>, - ) -> Result { + pub fn new(loaded_sources: Vec<(ModuleName, ModuleCodeString)>) -> Self { // Guesstimate a length let mut sources = HashMap::with_capacity(loaded_sources.len()); for source in loaded_sources { sources.insert(source.0, source.1); } - Ok(ExtModuleLoader { + ExtModuleLoader { sources: RefCell::new(sources), - }) + } } - pub fn finalize(self) -> Result<(), Error> { + pub fn finalize(self) -> Result<(), PubError> { let sources = self.sources.take(); let unused_modules: Vec<_> = sources.iter().collect(); if !unused_modules.is_empty() { - let mut msg = - "Following modules were passed to ExtModuleLoader but never used:\n" - .to_string(); - for m in unused_modules { - msg.push_str(" - "); - msg.push_str(m.0); - msg.push('\n'); - } - bail!(msg); + return Err(PubError::UnusedModules( + unused_modules + .into_iter() + .map(|(name, _)| name.to_string()) + .collect::>(), + )); } Ok(()) @@ -205,7 +233,7 @@ impl ModuleLoader for ExtModuleLoader { specifier: &str, referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { // If specifier is relative to an extension module, we need to do some special handling if specifier.starts_with("../") || specifier.starts_with("./") @@ -234,7 +262,13 @@ impl ModuleLoader for ExtModuleLoader { let mut sources = self.sources.borrow_mut(); let source = match sources.remove(specifier.as_str()) { Some(source) => source, - None => return ModuleLoadResponse::Sync(Err(anyhow!("Specifier \"{}\" was not passed as an extension module and was not included in the snapshot.", specifier))), + None => { + return ModuleLoadResponse::Sync(Err( + ModuleLoaderError::SpecifierExcludedFromSnapshot( + specifier.to_owned(), + ), + )) + } }; ModuleLoadResponse::Sync(Ok(ModuleSource::new( ModuleType::JavaScript, @@ -249,7 +283,7 @@ impl ModuleLoader for ExtModuleLoader { _specifier: &ModuleSpecifier, _maybe_referrer: Option, _is_dyn_import: bool, - ) -> Pin>>> { + ) -> Pin>>> { async { Ok(()) }.boxed_local() } } @@ -275,7 +309,7 @@ impl ModuleLoader for LazyEsmModuleLoader { specifier: &str, referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { Ok(resolve_import(specifier, referrer)?) } @@ -289,7 +323,11 @@ impl ModuleLoader for LazyEsmModuleLoader { let mut sources = self.sources.borrow_mut(); let source = match sources.remove(specifier.as_str()) { Some(source) => source, - None => return ModuleLoadResponse::Sync(Err(anyhow!("Specifier \"{}\" cannot be lazy-loaded as it was not included in the binary.", specifier))), + None => { + return ModuleLoadResponse::Sync(Err( + ModuleLoaderError::SpecifierMissingLazyLoadable(specifier.clone()), + )) + } }; ModuleLoadResponse::Sync(Ok(ModuleSource::new( ModuleType::JavaScript, @@ -304,7 +342,7 @@ impl ModuleLoader for LazyEsmModuleLoader { _specifier: &ModuleSpecifier, _maybe_referrer: Option, _is_dyn_import: bool, - ) -> Pin>>> { + ) -> Pin>>> { async { Ok(()) }.boxed_local() } } @@ -322,7 +360,7 @@ impl ModuleLoader for FsModuleLoader { specifier: &str, referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { Ok(resolve_import(specifier, referrer)?) } @@ -336,9 +374,9 @@ impl ModuleLoader for FsModuleLoader { let module_specifier = module_specifier.clone(); let fut = async move { let path = module_specifier.to_file_path().map_err(|_| { - generic_error(format!( + anyhow::Error::from(generic_error(format!( "Provided module specifier \"{module_specifier}\" is not a file URL." - )) + ))) })?; let module_type = if let Some(extension) = path.extension() { let ext = extension.to_string_lossy().to_lowercase(); @@ -362,7 +400,7 @@ impl ModuleLoader for FsModuleLoader { if module_type == ModuleType::Json && requested_module_type != RequestedModuleType::Json { - return Err(generic_error("Attempted to load JSON module without specifying \"type\": \"json\" attribute in the import statement.")); + return Err(ModuleLoaderError::JsonMissingAttribute); } let code = std::fs::read(path).with_context(|| { @@ -418,7 +456,7 @@ impl ModuleLoader for StaticModuleLoader { specifier: &str, referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { Ok(resolve_import(specifier, referrer)?) } @@ -437,7 +475,7 @@ impl ModuleLoader for StaticModuleLoader { None, )) } else { - Err(generic_error("Module not found")) + Err(ModuleLoaderError::NotFound) }; ModuleLoadResponse::Sync(res) } @@ -483,7 +521,7 @@ impl ModuleLoader for TestingModuleLoader { specifier: &str, referrer: &str, kind: ResolutionKind, - ) -> Result { + ) -> Result { self.resolve_count.set(self.resolve_count.get() + 1); self.loader.resolve(specifier, referrer, kind) } @@ -493,7 +531,7 @@ impl ModuleLoader for TestingModuleLoader { module_specifier: &ModuleSpecifier, maybe_referrer: Option, is_dyn_import: bool, - ) -> Pin>>> { + ) -> Pin>>> { self.prepare_count.set(self.prepare_count.get() + 1); self .loader diff --git a/core/modules/map.rs b/core/modules/map.rs index be2d70ef7..3139e8906 100644 --- a/core/modules/map.rs +++ b/core/modules/map.rs @@ -7,7 +7,6 @@ use crate::error::exception_to_err_result; use crate::error::generic_error; use crate::error::throw_type_error; use crate::error::to_v8_type_error; -use crate::error::AnyError; use crate::error::JsError; use crate::modules::get_requested_module_type_from_attributes; use crate::modules::parse_import_attributes; @@ -31,9 +30,6 @@ use crate::JsRuntime; use crate::ModuleLoadResponse; use crate::ModuleSource; use crate::ModuleSpecifier; -use anyhow::bail; -use anyhow::Context as _; -use anyhow::Error; use futures::future::FutureExt; use futures::stream::FuturesUnordered; use futures::stream::StreamFuture; @@ -44,6 +40,11 @@ use futures::StreamExt; use v8::Function; use v8::PromiseState; +use super::module_map_data::ModuleMapData; +use super::CustomModuleEvaluationKind; +use super::LazyEsmModuleLoader; +use super::RequestedModuleType; +use deno_core::error::PubError; use std::borrow::Cow; use std::cell::Cell; use std::cell::RefCell; @@ -55,13 +56,8 @@ use std::task::Context; use std::task::Poll; use tokio::sync::oneshot; -use super::module_map_data::ModuleMapData; -use super::CustomModuleEvaluationKind; -use super::LazyEsmModuleLoader; -use super::RequestedModuleType; - type PrepareLoadFuture = - dyn Future)>; + dyn Future)>; type CodeCacheReadyFuture = dyn Future; @@ -69,7 +65,7 @@ use super::ImportMetaResolveCallback; struct ModEvaluate { module_map: Rc, - sender: Option>>, + sender: Option>>, module: Option>, notify: Vec>, } @@ -169,7 +165,7 @@ impl ModuleMap { pub(crate) fn check_all_modules_evaluated( &self, scope: &mut v8::HandleScope, - ) -> Result<(), Error> { + ) -> Result<(), PubError> { let mut not_evaluated = vec![]; let data = self.data.borrow(); @@ -189,11 +185,7 @@ impl ModuleMap { } if !not_evaluated.is_empty() { - let mut msg = String::new(); - for m in not_evaluated { - msg.push_str(&format!(" - {}\n", m)); - } - bail!("Following modules were not evaluated; make sure they are imported from other code:\n {}", msg); + return Err(PubError::NonEvaluatedModules(not_evaluated)); } Ok(()) @@ -415,7 +407,7 @@ impl ModuleMap { &module_url_found, code, ) - .map_err(ModuleError::Other)?; + .map_err(|e| ModuleError::Other(PubError::Anyhow(e)))?; match module_evaluation_kind { // Simple case, we just got a single value so we create a regular @@ -857,7 +849,7 @@ impl ModuleMap { specifier: &str, referrer: &str, kind: ResolutionKind, - ) -> Result { + ) -> Result { if specifier.starts_with("ext:") && !referrer.starts_with("ext:") && !referrer.starts_with("node:") @@ -874,7 +866,11 @@ impl ModuleMap { return Err(generic_error(msg)); } - self.loader.borrow().resolve(specifier, referrer, kind) + self + .loader + .borrow() + .resolve(specifier, referrer, kind) + .map_err(|e| e.into()) } /// Called by `module_resolve_callback` during module instantiation. @@ -917,7 +913,7 @@ impl ModuleMap { pub(crate) async fn load_main( module_map_rc: Rc, specifier: impl AsRef, - ) -> Result { + ) -> Result { let load = RecursiveModuleLoad::main(specifier.as_ref(), module_map_rc.clone()); load.prepare().await?; @@ -927,7 +923,7 @@ impl ModuleMap { pub(crate) async fn load_side( module_map_rc: Rc, specifier: impl AsRef, - ) -> Result { + ) -> Result { let load = RecursiveModuleLoad::side(specifier.as_ref(), module_map_rc.clone()); load.prepare().await?; @@ -992,7 +988,7 @@ impl ModuleMap { self: &Rc, scope: &mut v8::HandleScope, id: ModuleId, - ) -> impl Future> + Unpin { + ) -> impl Future> + Unpin { let tc_scope = &mut v8::TryCatch::new(scope); let module = self @@ -1014,11 +1010,8 @@ impl ModuleMap { ); let (sender, receiver) = oneshot::channel(); - let receiver = receiver.map(|res| { - res.unwrap_or_else(|_| { - bail!("Cannot evaluate module, because JavaScript execution has been terminated") - } - )}); + let receiver = receiver + .map(|res| res.unwrap_or_else(|_| Err(PubError::ExecutionTerminated))); let Some(value) = module.evaluate(tc_scope) else { if tc_scope.has_terminated() || tc_scope.is_execution_terminating() { @@ -1166,7 +1159,7 @@ impl ModuleMap { self: &Rc, scope: &mut v8::HandleScope, id: ModuleId, - ) -> Result<(), Error> { + ) -> Result<(), PubError> { let mut receiver = self.mod_evaluate(scope, id); // After evaluate_pending_module, if the module isn't fully evaluated @@ -1174,9 +1167,9 @@ impl ModuleMap { // uses TLA. match receiver.poll_unpin(&mut Context::from_waker(noop_waker_ref())) { Poll::Ready(result) => { - result.with_context(|| { - let specifier = self.get_name_by_id(id).unwrap(); - format!("Couldn't execute '{specifier}'") + result.map_err(|e| PubError::CouldNotExecute { + error: Box::new(e), + specifier: self.get_name_by_id(id).unwrap(), })?; } Poll::Pending => { @@ -1185,8 +1178,7 @@ impl ModuleMap { assert!(!messages.is_empty()); let msg = v8::Local::new(scope, &messages[0]); let js_error = JsError::from_v8_message(scope, msg); - return Err(Error::from(js_error)) - .with_context(|| "Top-level await is not allowed in extensions"); + return Err(PubError::TLA(js_error)); } } @@ -1198,7 +1190,7 @@ impl ModuleMap { scope: &mut v8::HandleScope, load_id: ModuleLoadId, id: ModuleId, - ) -> Result<(), Error> { + ) -> Result<(), PubError> { let module_handle = self.get_handle(id).expect("ModuleInfo not found"); let status = { @@ -1390,7 +1382,7 @@ impl ModuleMap { &self, cx: &mut Context, scope: &mut v8::HandleScope, - ) -> Result<(), Error> { + ) -> Result<(), PubError> { let mut has_evaluated = true; // TODO(mmastrac): We register this waker unconditionally because we occasionally need to re-run @@ -1441,7 +1433,7 @@ impl ModuleMap { &self, cx: &mut Context, scope: &mut v8::HandleScope, - ) -> Poll> { + ) -> Poll> { if !self.preparing_dynamic_imports_pending.get() { return Poll::Ready(Ok(())); } @@ -1485,7 +1477,7 @@ impl ModuleMap { &self, cx: &mut Context, scope: &mut v8::HandleScope, - ) -> Poll> { + ) -> Poll> { if !self.pending_dynamic_imports_pending.get() { return Poll::Ready(Ok(())); } @@ -1564,7 +1556,10 @@ impl ModuleMap { } } - fn poll_code_cache_ready(&self, cx: &mut Context) -> Poll> { + fn poll_code_cache_ready( + &self, + cx: &mut Context, + ) -> Poll> { if !self.pending_code_cache_ready.get() { return Poll::Ready(Ok(())); } @@ -1592,7 +1587,7 @@ impl ModuleMap { &self, scope: &mut v8::HandleScope, module_id: ModuleId, - ) -> Result, Error> { + ) -> Result, PubError> { let module_handle = self .data .borrow() @@ -1689,7 +1684,7 @@ impl ModuleMap { module_specifier: &str, source_code: ModuleCodeString, code_cache_info: Option, - ) -> Result, Error> { + ) -> Result, PubError> { let specifier = ModuleSpecifier::parse(module_specifier)?; let mod_id = self .new_es_module( @@ -1700,7 +1695,7 @@ impl ModuleMap { false, code_cache_info, ) - .map_err(|e| e.into_any_error(scope, false, true))?; + .map_err(|e| e.into_error(scope, false, true))?; self.instantiate_module(scope, mod_id).map_err(|e| { let exception = v8::Local::new(scope, e); @@ -1750,7 +1745,7 @@ impl ModuleMap { &self, scope: &mut v8::HandleScope, module_specifier: &str, - ) -> Result, Error> { + ) -> Result, PubError> { let lazy_esm_sources = self.data.borrow().lazy_esm_sources.clone(); let loader = LazyEsmModuleLoader::new(lazy_esm_sources); diff --git a/core/modules/mod.rs b/core/modules/mod.rs index e8eefe1d6..6bd8543dc 100644 --- a/core/modules/mod.rs +++ b/core/modules/mod.rs @@ -1,11 +1,9 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::error::exception_to_err_result; -use crate::error::AnyError; +use crate::error::PubError; use crate::fast_string::FastString; use crate::module_specifier::ModuleSpecifier; use crate::FastStaticString; -use anyhow::bail; -use anyhow::Error; use serde::Deserialize; use serde::Serialize; use std::borrow::Cow; @@ -28,6 +26,7 @@ pub use loaders::FsModuleLoader; pub(crate) use loaders::LazyEsmModuleLoader; pub use loaders::ModuleLoadResponse; pub use loaders::ModuleLoader; +pub use loaders::ModuleLoaderError; pub use loaders::NoopModuleLoader; pub use loaders::StaticModuleLoader; pub(crate) use map::script_origin; @@ -180,16 +179,20 @@ impl From<&'static [u8]> for ModuleCodeBytes { /// Callback to customize value of `import.meta.resolve("./foo.ts")`. pub type ImportMetaResolveCallback = Box< - dyn Fn(&dyn ModuleLoader, String, String) -> Result, + dyn Fn( + &dyn ModuleLoader, + String, + String, + ) -> Result, >; pub(crate) fn default_import_meta_resolve_cb( loader: &dyn ModuleLoader, specifier: String, referrer: String, -) -> Result { +) -> Result { if specifier.starts_with("npm:") { - bail!("\"npm:\" specifiers are currently not supported in import.meta.resolve()"); + return Err(ModuleLoaderError::NpmUnsupportedMetaResolve); } loader.resolve(&specifier, &referrer, ResolutionKind::DynamicImport) @@ -208,13 +211,13 @@ pub type CustomModuleEvaluationCb = Box< Cow<'_, str>, &FastString, ModuleSourceCode, - ) -> Result, + ) -> Result, >; /// A callback to get the code cache for a script. /// (specifier, code) -> ... pub type EvalContextGetCodeCacheCb = - Box Result>; + Box Result>; /// Callback when the code cache is ready. /// (specifier, hash, data) -> () @@ -472,7 +475,8 @@ impl ModuleSource { } } -pub type ModuleSourceFuture = dyn Future>; +pub type ModuleSourceFuture = + dyn Future>; #[derive(Debug, PartialEq, Eq)] pub enum ResolutionKind { @@ -620,18 +624,18 @@ pub(crate) struct ModuleInfo { } #[derive(Debug)] -pub(crate) enum ModuleError { +pub enum ModuleError { Exception(v8::Global), - Other(Error), + Other(PubError), } impl ModuleError { - pub fn into_any_error( + pub fn into_error( self, scope: &mut v8::HandleScope, in_promise: bool, clear_error: bool, - ) -> AnyError { + ) -> PubError { match self { ModuleError::Exception(exception) => { let exception = v8::Local::new(scope, exception); diff --git a/core/modules/recursive_load.rs b/core/modules/recursive_load.rs index 08b00595a..ca443159f 100644 --- a/core/modules/recursive_load.rs +++ b/core/modules/recursive_load.rs @@ -1,9 +1,11 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +use crate::error::PubError; use crate::module_specifier::ModuleSpecifier; use crate::modules::map::ModuleMap; use crate::modules::ModuleError; use crate::modules::ModuleId; use crate::modules::ModuleLoadId; +use crate::modules::ModuleLoaderError; use crate::modules::ModuleRequest; use crate::modules::RequestedModuleType; use crate::modules::ResolutionKind; @@ -11,7 +13,6 @@ use crate::resolve_url; use crate::ModuleLoadResponse; use crate::ModuleLoader; use crate::ModuleSource; -use anyhow::Error; use futures::future::FutureExt; use futures::stream::FuturesUnordered; use futures::stream::Stream; @@ -25,8 +26,9 @@ use std::rc::Rc; use std::task::Context; use std::task::Poll; -type ModuleLoadFuture = - dyn Future, Error>>; +type ModuleLoadFuture = dyn Future< + Output = Result, ModuleLoaderError>, +>; /// Describes the entrypoint of a recursive module load. #[derive(Debug)] @@ -125,7 +127,7 @@ impl RecursiveModuleLoad { load } - fn resolve_root(&self) -> Result { + fn resolve_root(&self) -> Result { match self.init { LoadInit::Main(ref specifier) => { self @@ -143,7 +145,7 @@ impl RecursiveModuleLoad { } } - pub(crate) async fn prepare(&self) -> Result<(), Error> { + pub(crate) async fn prepare(&self) -> Result<(), PubError> { let (module_specifier, maybe_referrer) = match self.init { LoadInit::Main(ref specifier) => { let spec = self.module_map_rc.resolve( @@ -174,6 +176,7 @@ impl RecursiveModuleLoad { .loader .prepare_load(&module_specifier, maybe_referrer, self.is_dynamic_import()) .await + .map_err(|e| PubError::ModuleLoader(Box::new(e))) } fn is_currently_loading_main_module(&self) -> bool { @@ -297,7 +300,7 @@ impl RecursiveModuleLoad { } impl Stream for RecursiveModuleLoad { - type Item = Result<(ModuleRequest, ModuleSource), Error>; + type Item = Result<(ModuleRequest, ModuleSource), PubError>; fn poll_next( self: Pin<&mut Self>, diff --git a/core/modules/tests.rs b/core/modules/tests.rs index 9adf65fc6..af314d991 100644 --- a/core/modules/tests.rs +++ b/core/modules/tests.rs @@ -1897,7 +1897,7 @@ fn test_load_with_code_cache() { #[test] fn ext_module_loader_relative() { - let loader = ExtModuleLoader::new(vec![]).unwrap(); + let loader = ExtModuleLoader::new(vec![]); let cases = [ ( ("../../foo.js", "ext:test/nested/mod/bar.js"), diff --git a/core/ops_builtin.rs b/core/ops_builtin.rs index 41676c0d5..023cdf455 100644 --- a/core/ops_builtin.rs +++ b/core/ops_builtin.rs @@ -1,6 +1,7 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::error::format_file_name; use crate::error::type_error; +use crate::error::AnyError; use crate::io::AdaptiveBufferStrategy; use crate::io::BufMutView; use crate::io::BufView; @@ -13,7 +14,6 @@ use crate::JsBuffer; use crate::OpDecl; use crate::OpState; use crate::Resource; -use anyhow::Error; use bytes::BytesMut; use serde_v8::ByteString; use std::cell::RefCell; @@ -168,14 +168,14 @@ pub async fn op_void_async() {} #[allow(clippy::unused_async)] #[op2(async)] -pub async fn op_error_async() -> Result<(), Error> { - Err(Error::msg("error")) +pub async fn op_error_async() -> Result<(), AnyError> { + Err(AnyError::msg("error")) } #[allow(clippy::unused_async)] #[op2(async(deferred), fast)] -pub async fn op_error_async_deferred() -> Result<(), Error> { - Err(Error::msg("error")) +pub async fn op_error_async_deferred() -> Result<(), AnyError> { + Err(AnyError::msg("error")) } #[allow(clippy::unused_async)] @@ -187,7 +187,7 @@ pub async fn op_void_async_deferred() {} pub fn op_close( state: Rc>, #[smi] rid: ResourceId, -) -> Result<(), Error> { +) -> Result<(), AnyError> { let resource = state.borrow_mut().resource_table.take_any(rid)?; resource.close(); Ok(()) @@ -204,7 +204,7 @@ pub fn op_try_close(state: Rc>, #[smi] rid: ResourceId) { /// Builtin utility to print to stdout/stderr #[op2(fast)] -pub fn op_print(#[string] msg: &str, is_err: bool) -> Result<(), Error> { +pub fn op_print(#[string] msg: &str, is_err: bool) -> Result<(), AnyError> { if is_err { stderr().write_all(msg.as_bytes())?; stderr().flush().unwrap(); @@ -236,7 +236,7 @@ pub fn op_wasm_streaming_feed( state: Rc>, #[smi] rid: ResourceId, #[buffer] bytes: &[u8], -) -> Result<(), Error> { +) -> Result<(), AnyError> { let wasm_streaming = state .borrow_mut() .resource_table @@ -252,7 +252,7 @@ pub fn op_wasm_streaming_set_url( state: &mut OpState, #[smi] rid: ResourceId, #[string] url: &str, -) -> Result<(), Error> { +) -> Result<(), AnyError> { let wasm_streaming = state.resource_table.get::(rid)?; @@ -266,7 +266,7 @@ async fn op_read( state: Rc>, #[smi] rid: ResourceId, #[buffer] buf: JsBuffer, -) -> Result { +) -> Result { let resource = state.borrow().resource_table.get_any(rid)?; let view = BufMutView::from(buf); resource.read_byob(view).await.map(|(n, _)| n as u32) @@ -277,7 +277,7 @@ async fn op_read( async fn op_read_all( state: Rc>, #[smi] rid: ResourceId, -) -> Result { +) -> Result { let resource = state.borrow().resource_table.get_any(rid)?; let (min, maybe_max) = resource.size_hint(); @@ -312,7 +312,7 @@ async fn op_write( state: Rc>, #[smi] rid: ResourceId, #[buffer] buf: JsBuffer, -) -> Result { +) -> Result { let resource = state.borrow().resource_table.get_any(rid)?; let view = BufView::from(buf); let resp = resource.write(view).await?; @@ -324,7 +324,7 @@ fn op_read_sync( state: Rc>, #[smi] rid: ResourceId, #[buffer] data: &mut [u8], -) -> Result { +) -> Result { let resource = state.borrow_mut().resource_table.get_any(rid)?; resource.read_byob_sync(data).map(|n| n as u32) } @@ -334,7 +334,7 @@ fn op_write_sync( state: Rc>, #[smi] rid: ResourceId, #[buffer] data: &[u8], -) -> Result { +) -> Result { let resource = state.borrow_mut().resource_table.get_any(rid)?; let nwritten = resource.write_sync(data)?; Ok(nwritten as u32) @@ -345,7 +345,7 @@ async fn op_write_all( state: Rc>, #[smi] rid: ResourceId, #[buffer] buf: JsBuffer, -) -> Result<(), Error> { +) -> Result<(), AnyError> { let resource = state.borrow().resource_table.get_any(rid)?; let view = BufView::from(buf); resource.write_all(view).await?; @@ -357,9 +357,9 @@ async fn op_write_type_error( state: Rc>, #[smi] rid: ResourceId, #[string] error: String, -) -> Result<(), Error> { +) -> Result<(), AnyError> { let resource = state.borrow().resource_table.get_any(rid)?; - resource.write_error(type_error(error)).await?; + resource.write_error(type_error(error).into()).await?; Ok(()) } @@ -367,7 +367,7 @@ async fn op_write_type_error( async fn op_shutdown( state: Rc>, #[smi] rid: ResourceId, -) -> Result<(), Error> { +) -> Result<(), AnyError> { let resource = state.borrow().resource_table.get_any(rid)?; resource.shutdown().await } @@ -407,7 +407,7 @@ fn op_encode_binary_string(#[buffer] s: &[u8]) -> ByteString { fn op_is_terminal( state: &mut OpState, #[smi] rid: ResourceId, -) -> Result { +) -> Result { let handle = state.resource_table.get_handle(rid)?; Ok(handle.is_terminal()) } diff --git a/core/ops_builtin_v8.rs b/core/ops_builtin_v8.rs index 54bf21d77..5e03ea54e 100644 --- a/core/ops_builtin_v8.rs +++ b/core/ops_builtin_v8.rs @@ -3,7 +3,9 @@ use crate::error::custom_error; use crate::error::is_instance_of_error; use crate::error::range_error; use crate::error::type_error; +use crate::error::AnyError; use crate::error::JsError; +use crate::error::PubError; use crate::modules::script_origin; use crate::op2; use crate::ops_builtin::WasmStreamingResource; @@ -15,7 +17,6 @@ use crate::stats::RuntimeActivityType; use crate::JsBuffer; use crate::JsRuntime; use crate::OpState; -use anyhow::Error; use serde::Deserialize; use serde::Serialize; use std::cell::RefCell; @@ -194,9 +195,11 @@ pub fn op_timer_unref(scope: &mut v8::HandleScope, id: f64) { pub fn op_lazy_load_esm( scope: &mut v8::HandleScope, #[string] module_specifier: String, -) -> Result, Error> { +) -> Result, AnyError> { let module_map_rc = JsRealm::module_map_from(scope); - module_map_rc.lazy_load_esm_module(scope, &module_specifier) + module_map_rc + .lazy_load_esm_module(scope, &module_specifier) + .map_err(|e| e.into()) } // We run in a `nofast` op here so we don't get put into a `DisallowJavascriptExecutionScope` and we're @@ -263,7 +266,7 @@ pub fn op_eval_context<'a>( source: v8::Local<'a, v8::Value>, #[string] specifier: String, host_defined_options: Option>, -) -> Result, Error> { +) -> Result, AnyError> { let out = v8::Array::new(scope, 2); let state = JsRuntime::state_from(scope); let tc_scope = &mut v8::TryCatch::new(scope); @@ -376,7 +379,7 @@ pub fn op_eval_context<'a>( pub fn op_encode<'a>( scope: &mut v8::HandleScope<'a>, text: v8::Local<'a, v8::Value>, -) -> Result, Error> { +) -> Result, AnyError> { let text = v8::Local::::try_from(text) .map_err(|_| type_error("Invalid argument"))?; let text_str = serde_v8::to_utf8(text, scope); @@ -393,7 +396,7 @@ pub fn op_encode<'a>( pub fn op_decode<'a>( scope: &mut v8::HandleScope<'a>, #[buffer] zero_copy: &[u8], -) -> Result, Error> { +) -> Result, AnyError> { let buf = &zero_copy; // Strip BOM @@ -414,7 +417,7 @@ pub fn op_decode<'a>( // - https://github.com/v8/v8/blob/d68fb4733e39525f9ff0a9222107c02c28096e2a/include/v8.h#L3277-L3278 match v8::String::new_from_utf8(scope, buf, v8::NewStringType::Normal) { Some(text) => Ok(text), - None => Err(range_error("string too long")), + None => Err(range_error("string too long").into()), } } @@ -594,7 +597,7 @@ pub fn op_serialize( transferred_array_buffers: Option>, for_storage: bool, error_callback: Option>, -) -> Result, Error> { +) -> Result, AnyError> { let error_callback = match error_callback { Some(cb) => Some( v8::Local::::try_from(cb) @@ -642,16 +645,20 @@ pub fn op_serialize( if let Some(shared_array_buffer_store) = &state.shared_array_buffer_store { if !buf.is_detachable() { - return Err(type_error( - "item in transferredArrayBuffers is not transferable", - )); + return Err( + type_error("item in transferredArrayBuffers is not transferable") + .into(), + ); } if buf.was_detached() { - return Err(custom_error( - "DOMExceptionOperationError", - format!("ArrayBuffer at index {index} is already detached"), - )); + return Err( + custom_error( + "DOMExceptionOperationError", + format!("ArrayBuffer at index {index} is already detached"), + ) + .into(), + ); } let backing_store = buf.get_backing_store(); @@ -674,7 +681,7 @@ pub fn op_serialize( let vector = value_serializer.release(); Ok(vector) } else { - Err(type_error("Failed to serialize response")) + Err(type_error("Failed to serialize response").into()) } } @@ -685,7 +692,7 @@ pub fn op_deserialize<'a>( host_objects: Option>, transferred_array_buffers: Option>, for_storage: bool, -) -> Result, Error> { +) -> Result, AnyError> { let host_objects = match host_objects { Some(value) => Some( v8::Local::::try_from(value) @@ -713,7 +720,7 @@ pub fn op_deserialize<'a>( .read_header(scope.get_current_context()) .unwrap_or_default(); if !parsed_header { - return Err(range_error("could not deserialize value")); + return Err(range_error("could not deserialize value").into()); } if let Some(transferred_array_buffers) = transferred_array_buffers { @@ -725,9 +732,9 @@ pub fn op_deserialize<'a>( let id = match id_val.number_value(scope) { Some(id) => id as u32, None => { - return Err(type_error( - "item in transferredArrayBuffers not number", - )) + return Err( + type_error("item in transferredArrayBuffers not number").into(), + ) } }; if let Some(backing_store) = shared_array_buffer_store.take(id) { @@ -738,7 +745,7 @@ pub fn op_deserialize<'a>( } else { return Err(type_error( "transferred array buffer not present in shared_array_buffer_store", - )); + ).into()); } } } @@ -747,7 +754,7 @@ pub fn op_deserialize<'a>( let value = value_deserializer.read_value(scope.get_current_context()); match value { Some(deserialized) => Ok(deserialized), - None => Err(range_error("could not deserialize value")), + None => Err(range_error("could not deserialize value").into()), } } @@ -783,7 +790,7 @@ pub fn op_set_promise_hooks( before_hook: v8::Local, after_hook: v8::Local, resolve_hook: v8::Local, -) -> Result<(), Error> { +) -> Result<(), AnyError> { let v8_fns = [init_hook, before_hook, after_hook, resolve_hook] .into_iter() .enumerate() @@ -792,7 +799,7 @@ pub fn op_set_promise_hooks( let v8_fn = v8::Local::::try_from(hook) .map_err(|err| type_error(err.to_string()))?; v8_fns[i] = Some(v8_fn); - Ok::<_, Error>(v8_fns) + Ok::<_, AnyError>(v8_fns) })?; scope.set_promise_hooks( @@ -929,7 +936,7 @@ pub fn op_memory_usage(scope: &mut v8::HandleScope) -> MemoryUsage { pub fn op_set_wasm_streaming_callback( scope: &mut v8::HandleScope, #[global] cb: v8::Global, -) -> Result<(), Error> { +) -> Result<(), PubError> { let context_state_rc = JsRealm::state_from_scope(scope); // The callback to pass to the v8 API has to be a unit type, so it can't // borrow or move any local variables. Therefore, we're storing the JS @@ -974,7 +981,7 @@ pub fn op_abort_wasm_streaming( state: Rc>, rid: u32, error: v8::Local, -) -> Result<(), Error> { +) -> Result<(), AnyError> { // NOTE: v8::WasmStreaming::abort can't be called while `state` is borrowed; let wasm_streaming = state .borrow_mut() diff --git a/core/resources.rs b/core/resources.rs index 2df5a8041..ea1f8e173 100644 --- a/core/resources.rs +++ b/core/resources.rs @@ -12,7 +12,6 @@ use crate::error::not_supported; use crate::io::BufMutView; use crate::io::BufView; use crate::io::WriteOutcome; -use anyhow::Error; use futures::Future; use std::any::type_name; use std::any::Any; diff --git a/core/runtime/bindings.rs b/core/runtime/bindings.rs index 5a520d771..2e4c218a1 100644 --- a/core/runtime/bindings.rs +++ b/core/runtime/bindings.rs @@ -1,5 +1,4 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use anyhow::Context; use std::mem::MaybeUninit; use std::os::raw::c_void; use std::path::PathBuf; @@ -14,8 +13,8 @@ use crate::error::callsite_fns; use crate::error::has_call_site; use crate::error::is_instance_of_error; use crate::error::throw_type_error; -use crate::error::AnyError; use crate::error::JsStackFrame; +use crate::error::PubError; use crate::extension_set::LoadedSources; use crate::modules::get_requested_module_type_from_attributes; use crate::modules::parse_import_attributes; @@ -307,7 +306,7 @@ pub(crate) fn initialize_deno_core_namespace<'s>( /// to function properly pub(crate) fn initialize_primordials_and_infra( scope: &mut v8::HandleScope, -) -> Result<(), AnyError> { +) -> Result<(), PubError> { for source_file in &CONTEXT_SETUP_SOURCES { let name = source_file.specifier.v8_string(scope); let source = source_file.source.v8_string(scope); @@ -315,10 +314,10 @@ pub(crate) fn initialize_primordials_and_infra( let origin = crate::modules::script_origin(scope, name, false, None); // TODO(bartlomieju): these two calls will panic if there's any problem in the JS code let script = v8::Script::compile(scope, source, Some(&origin)) - .with_context(|| format!("Failed to parse {}", source_file.specifier))?; - script.run(scope).with_context(|| { - format!("Failed to execute {}", source_file.specifier) - })?; + .ok_or_else(|| PubError::Parse(source_file.specifier))?; + script + .run(scope) + .ok_or_else(|| PubError::Execute(source_file.specifier))?; } Ok(()) diff --git a/core/runtime/exception_state.rs b/core/runtime/exception_state.rs index d04ae89c9..270e57696 100644 --- a/core/runtime/exception_state.rs +++ b/core/runtime/exception_state.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::error::exception_to_err_result; -use anyhow::Error; +use crate::error::PubError; use std::cell::Cell; use std::cell::RefCell; use std::collections::VecDeque; @@ -70,7 +70,7 @@ impl ExceptionState { pub(crate) fn check_exception_condition( &self, scope: &mut v8::HandleScope, - ) -> Result<(), Error> { + ) -> Result<(), PubError> { if self.has_dispatched_exception() { let undefined = v8::undefined(scope); exception_to_err_result( diff --git a/core/runtime/jsrealm.rs b/core/runtime/jsrealm.rs index edf510b1a..c143f2df7 100644 --- a/core/runtime/jsrealm.rs +++ b/core/runtime/jsrealm.rs @@ -3,6 +3,7 @@ use super::exception_state::ExceptionState; #[cfg(test)] use super::op_driver::OpDriver; use crate::error::exception_to_err_result; +use crate::error::PubError; use crate::module_specifier::ModuleSpecifier; use crate::modules::script_origin; use crate::modules::IntoModuleCodeString; @@ -17,7 +18,6 @@ use crate::stats::RuntimeActivityTraces; use crate::tasks::V8TaskSpawnerFactory; use crate::web_timeout::WebTimers; use crate::GetErrorClassFn; -use anyhow::Error; use futures::stream::StreamExt; use std::cell::Cell; use std::cell::RefCell; @@ -309,7 +309,7 @@ impl JsRealm { isolate: &mut v8::Isolate, name: impl IntoModuleName, source_code: impl IntoModuleCodeString, - ) -> Result, Error> { + ) -> Result, PubError> { let scope = &mut self.0.handle_scope(isolate); let source = source_code.into_module_code().v8_string(scope); @@ -347,7 +347,7 @@ impl JsRealm { &self, isolate: &mut v8::Isolate, module_id: ModuleId, - ) -> Result, Error> { + ) -> Result, PubError> { self .0 .module_map() @@ -383,14 +383,14 @@ impl JsRealm { isolate: &mut v8::Isolate, specifier: &ModuleSpecifier, code: Option, - ) -> Result { + ) -> Result { let module_map_rc = self.0.module_map(); if let Some(code) = code { let scope = &mut self.handle_scope(isolate); // true for main module module_map_rc .new_es_module(scope, true, specifier.to_owned(), code, false, None) - .map_err(|e| e.into_any_error(scope, false, false))?; + .map_err(|e| e.into_error(scope, false, false))?; } let mut load = @@ -401,7 +401,7 @@ impl JsRealm { let scope = &mut self.handle_scope(isolate); load .register_and_recurse(scope, &request, info) - .map_err(|e| e.into_any_error(scope, false, false))?; + .map_err(|e| e.into_error(scope, false, false))?; } let root_id = load.root_module_id.expect("Root module should be loaded"); @@ -428,7 +428,7 @@ impl JsRealm { isolate: &mut v8::Isolate, specifier: &ModuleSpecifier, code: Option, - ) -> Result { + ) -> Result { let module_map_rc = self.0.module_map(); if let Some(code) = code { let specifier = specifier.to_owned(); @@ -436,7 +436,7 @@ impl JsRealm { // false for side module (not main module) module_map_rc .new_es_module(scope, false, specifier, code, false, None) - .map_err(|e| e.into_any_error(scope, false, false))?; + .map_err(|e| e.into_error(scope, false, false))?; } let mut load = @@ -447,7 +447,7 @@ impl JsRealm { let scope = &mut self.handle_scope(isolate); load .register_and_recurse(scope, &request, info) - .map_err(|e| e.into_any_error(scope, false, false))?; + .map_err(|e| e.into_error(scope, false, false))?; } let root_id = load.root_module_id.expect("Root module should be loaded"); @@ -471,7 +471,7 @@ impl JsRealm { isolate: &mut v8::Isolate, module_specifier: ModuleName, code: ModuleCodeString, - ) -> Result, Error> { + ) -> Result, PubError> { let module_map_rc = self.0.module_map(); let scope = &mut self.handle_scope(isolate); module_map_rc.lazy_load_es_module_with_code( diff --git a/core/runtime/jsruntime.rs b/core/runtime/jsruntime.rs index cf709acfa..dda781b28 100644 --- a/core/runtime/jsruntime.rs +++ b/core/runtime/jsruntime.rs @@ -13,10 +13,9 @@ use super::SnapshotStoreDataStore; use super::SnapshottedData; use crate::ascii_str; use crate::ascii_str_include; -use crate::error::exception_to_err_result; -use crate::error::AnyError; use crate::error::GetErrorClassFn; use crate::error::JsError; +use crate::error::{exception_to_err_result, PubError}; use crate::extension_set; use crate::extension_set::LoadedSources; use crate::extensions::GlobalObjectMiddlewareFn; @@ -59,10 +58,6 @@ use crate::NoopModuleLoader; use crate::OpMetadata; use crate::OpMetricsEvent; use crate::OpState; -use anyhow::anyhow; -use anyhow::bail; -use anyhow::Context as _; -use anyhow::Error; use futures::future::poll_fn; use futures::task::AtomicWaker; use futures::Future; @@ -95,7 +90,7 @@ pub type ExtensionTranspiler = dyn Fn( ModuleName, ModuleCodeString, - ) -> Result<(ModuleCodeString, Option), AnyError>; + ) -> Result<(ModuleCodeString, Option), anyhow::Error>; /// Objects that need to live as long as the isolate #[derive(Default)] @@ -271,7 +266,7 @@ impl InitMode { #[derive(Default)] struct PromiseFuture { - resolved: Cell, Error>>>, + resolved: Cell, PubError>>>, waker: Cell>, } @@ -279,7 +274,7 @@ struct PromiseFuture { struct RcPromiseFuture(Rc); impl RcPromiseFuture { - pub fn new(res: Result, Error>) -> Self { + pub fn new(res: Result, PubError>) -> Self { Self(Rc::new(PromiseFuture { resolved: Some(res).into(), ..Default::default() @@ -288,7 +283,7 @@ impl RcPromiseFuture { } impl Future for RcPromiseFuture { - type Output = Result, Error>; + type Output = Result, PubError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.get_mut(); if let Some(resolved) = this.0.resolved.take() { @@ -736,7 +731,7 @@ impl JsRuntime { /// Only constructor, configuration is done through `options`. /// Returns an error if the runtime cannot be initialized. - pub fn try_new(mut options: RuntimeOptions) -> Result { + pub fn try_new(mut options: RuntimeOptions) -> Result { setup::init_v8( options.v8_platform.take(), cfg!(test), @@ -783,7 +778,7 @@ impl JsRuntime { fn new_inner( mut options: RuntimeOptions, will_snapshot: bool, - ) -> Result { + ) -> Result { let init_mode = InitMode::from_options(&options); let mut extensions = std::mem::take(&mut options.extensions); let mut isolate_allocations = IsolateAllocations::default(); @@ -1264,7 +1259,7 @@ impl JsRuntime { realm: &JsRealm, module_map: &Rc, files_loaded: &mut Vec<&'static str>, - ) -> Result<(), Error> { + ) -> Result<(), PubError> { let scope = &mut realm.handle_scope(self.v8_isolate()); for source_file in &BUILTIN_SOURCES { @@ -1273,12 +1268,10 @@ impl JsRuntime { let origin = script_origin(scope, name, false, None); let script = v8::Script::compile(scope, source, Some(&origin)) - .with_context(|| { - format!("Failed to parse {}", source_file.specifier) - })?; - script.run(scope).with_context(|| { - format!("Failed to execute {}", source_file.specifier) - })?; + .ok_or_else(|| PubError::Parse(source_file.specifier))?; + script + .run(scope) + .ok_or_else(|| PubError::Execute(source_file.specifier))?; } for file_source in &BUILTIN_ES_MODULES { @@ -1300,7 +1293,7 @@ impl JsRuntime { realm: &JsRealm, module_map: &Rc, loaded_sources: LoadedSources, - ) -> Result<(), Error> { + ) -> Result<(), PubError> { // First, add all the lazy ESM for source in loaded_sources.lazy_esm { module_map.add_lazy_loaded_esm_source(source.specifier, source.code); @@ -1318,7 +1311,7 @@ impl JsRuntime { modules.push(ModuleSpecifier::parse(&esm.specifier).unwrap()); sources.push((esm.specifier, esm.code)); } - let ext_loader = Rc::new(ExtModuleLoader::new(sources)?); + let ext_loader = Rc::new(ExtModuleLoader::new(sources)); *module_map.loader.borrow_mut() = ext_loader.clone(); // Next, load the extension modules as side modules (but do not execute them) @@ -1338,7 +1331,7 @@ impl JsRuntime { let Some(mod_id) = module_map.get_id(&specifier, RequestedModuleType::None) else { - bail!("{} not present in the module map", specifier); + return Err(PubError::MissingFromModuleMap(specifier.to_string())); }; let isolate = self.v8_isolate(); @@ -1368,7 +1361,7 @@ impl JsRuntime { realm: &JsRealm, module_map: &Rc, loaded_sources: LoadedSources, - ) -> Result<(), Error> { + ) -> Result<(), PubError> { futures::executor::block_on(self.init_extension_js_inner( realm, module_map, @@ -1500,7 +1493,7 @@ impl JsRuntime { &mut self, name: &'static str, source_code: impl IntoModuleCodeString, - ) -> Result, Error> { + ) -> Result, PubError> { let isolate = &mut self.inner.v8_isolate; self.inner.main_realm.execute_script( isolate, @@ -1519,7 +1512,7 @@ impl JsRuntime { pub fn call( &mut self, function: &v8::Global, - ) -> impl Future, Error>> { + ) -> impl Future, PubError>> { self.call_with_args(function, &[]) } @@ -1533,7 +1526,7 @@ impl JsRuntime { pub fn scoped_call( scope: &mut v8::HandleScope, function: &v8::Global, - ) -> impl Future, Error>> { + ) -> impl Future, PubError>> { Self::scoped_call_with_args(scope, function, &[]) } @@ -1548,7 +1541,7 @@ impl JsRuntime { &mut self, function: &v8::Global, args: &[v8::Global], - ) -> impl Future, Error>> { + ) -> impl Future, PubError>> { let scope = &mut self.handle_scope(); Self::scoped_call_with_args(scope, function, args) } @@ -1564,7 +1557,7 @@ impl JsRuntime { scope: &mut v8::HandleScope, function: &v8::Global, args: &[v8::Global], - ) -> impl Future, Error>> { + ) -> impl Future, PubError>> { let scope = &mut v8::TryCatch::new(scope); let cb = function.open(scope); let this = v8::undefined(scope).into(); @@ -1606,7 +1599,7 @@ impl JsRuntime { pub async fn call_and_await( &mut self, function: &v8::Global, - ) -> Result, Error> { + ) -> Result, PubError> { let call = self.call(function); self .with_event_loop_promise(call, PollEventLoopOptions::default()) @@ -1621,7 +1614,7 @@ impl JsRuntime { &mut self, function: &v8::Global, args: &[v8::Global], - ) -> Result, Error> { + ) -> Result, PubError> { let call = self.call_with_args(function, args); self .with_event_loop_promise(call, PollEventLoopOptions::default()) @@ -1635,7 +1628,7 @@ impl JsRuntime { pub fn get_module_namespace( &mut self, module_id: ModuleId, - ) -> Result, Error> { + ) -> Result, PubError> { let isolate = &mut self.inner.v8_isolate; self .inner @@ -1682,7 +1675,7 @@ impl JsRuntime { fn pump_v8_message_loop( &mut self, scope: &mut v8::HandleScope, - ) -> Result<(), Error> { + ) -> Result<(), PubError> { while v8::Platform::pump_message_loop( &v8::V8::get_current_platform(), scope, @@ -1729,7 +1722,7 @@ impl JsRuntime { pub fn resolve( &mut self, promise: v8::Global, - ) -> impl Future, Error>> { + ) -> impl Future, PubError>> { let scope = &mut self.handle_scope(); Self::scoped_resolve(scope, promise) } @@ -1741,7 +1734,7 @@ impl JsRuntime { pub fn scoped_resolve( scope: &mut v8::HandleScope, promise: v8::Global, - ) -> impl Future, Error>> { + ) -> impl Future, PubError>> { let promise = v8::Local::new(scope, promise); if !promise.is_promise() { return RcPromiseFuture::new(Ok(v8::Global::new(scope, promise))); @@ -1758,7 +1751,7 @@ impl JsRuntime { pub async fn resolve_value( &mut self, global: v8::Global, - ) -> Result, Error> { + ) -> Result, PubError> { let resolve = self.resolve(global); self .with_event_loop_promise(resolve, PollEventLoopOptions::default()) @@ -1796,7 +1789,7 @@ impl JsRuntime { pub async fn run_event_loop( &mut self, poll_options: PollEventLoopOptions, - ) -> Result<(), Error> { + ) -> Result<(), PubError> { poll_fn(|cx| self.poll_event_loop(cx, poll_options)).await } @@ -1808,9 +1801,9 @@ impl JsRuntime { &mut self, mut fut: impl Future> + Unpin + 'fut, poll_options: PollEventLoopOptions, - ) -> Result + ) -> Result where - AnyError: From, + PubError: From, { // Manually implement tokio::select poll_fn(|cx| { @@ -1822,10 +1815,11 @@ impl JsRuntime { if let Poll::Ready(t) = fut.poll_unpin(cx) { return Poll::Ready(t.map_err(|e| e.into())); } - return Poll::Ready(Err(anyhow!("Promise resolution is still pending but the event loop has already resolved."))); + return Poll::Ready(Err(PubError::PendingPromiseResolution)); } Poll::Pending - }).await + }) + .await } /// A utility function that run provided future concurrently with the event loop. @@ -1838,9 +1832,9 @@ impl JsRuntime { &mut self, mut fut: impl Future> + Unpin + 'fut, poll_options: PollEventLoopOptions, - ) -> Result + ) -> Result where - AnyError: From, + PubError: From, { // Manually implement tokio::select poll_fn(|cx| { @@ -1866,7 +1860,7 @@ impl JsRuntime { &mut self, cx: &mut Context, poll_options: PollEventLoopOptions, - ) -> Poll> { + ) -> Poll> { // SAFETY: We know this isolate is valid and non-null at this time let mut isolate_scope = v8::HandleScope::new(unsafe { &mut *self.v8_isolate_ptr() }); @@ -1881,7 +1875,7 @@ impl JsRuntime { cx: &mut Context, scope: &mut v8::HandleScope, poll_options: PollEventLoopOptions, - ) -> Poll> { + ) -> Poll> { let has_inspector = self.inner.state.has_inspector.get(); self.inner.state.waker.register(cx.waker()); @@ -2008,7 +2002,7 @@ impl JsRuntime { fn find_and_report_stalled_level_await_in_any_realm( scope: &mut v8::HandleScope, inner_realm: &JsRealmInner, -) -> Error { +) -> PubError { let module_map = inner_realm.module_map(); let messages = module_map.find_stalled_top_level_await(scope); @@ -2076,7 +2070,7 @@ impl JsRuntimeForSnapshot { /// Try to create a new runtime, returning an error if the process fails. pub fn try_new( mut options: RuntimeOptions, - ) -> Result { + ) -> Result { setup::init_v8( options.v8_platform.take(), true, @@ -2332,7 +2326,7 @@ impl JsRuntime { pub fn mod_evaluate( &mut self, id: ModuleId, - ) -> impl Future> { + ) -> impl Future> { let isolate = &mut self.inner.v8_isolate; let realm = &self.inner.main_realm; let scope = &mut realm.handle_scope(isolate); @@ -2355,7 +2349,7 @@ impl JsRuntime { &mut self, specifier: &ModuleSpecifier, code: impl IntoModuleCodeString, - ) -> Result { + ) -> Result { let isolate = &mut self.inner.v8_isolate; self .inner @@ -2379,7 +2373,7 @@ impl JsRuntime { pub async fn load_main_es_module( &mut self, specifier: &ModuleSpecifier, - ) -> Result { + ) -> Result { let isolate = &mut self.inner.v8_isolate; self .inner @@ -2405,7 +2399,7 @@ impl JsRuntime { &mut self, specifier: &ModuleSpecifier, code: impl IntoModuleCodeString, - ) -> Result { + ) -> Result { let isolate = &mut self.inner.v8_isolate; self .inner @@ -2429,7 +2423,7 @@ impl JsRuntime { pub async fn load_side_es_module( &mut self, specifier: &ModuleSpecifier, - ) -> Result { + ) -> Result { let isolate = &mut self.inner.v8_isolate; self .inner @@ -2449,7 +2443,7 @@ impl JsRuntime { &mut self, specifier: impl IntoModuleName, code: impl IntoModuleCodeString, - ) -> Result, Error> { + ) -> Result, PubError> { let isolate = &mut self.inner.v8_isolate; self.inner.main_realm.lazy_load_es_module_with_code( isolate, @@ -2463,7 +2457,7 @@ impl JsRuntime { scope: &mut v8::HandleScope, context_state: &ContextState, exception_state: &ExceptionState, - ) -> Result { + ) -> Result { let mut dispatched_ops = false; // Poll any pending task spawner tasks. Note that we need to poll separately because otherwise diff --git a/core/runtime/op_driver/futures_unordered_driver.rs b/core/runtime/op_driver/futures_unordered_driver.rs index 240abb1c1..4f7aa20f9 100644 --- a/core/runtime/op_driver/futures_unordered_driver.rs +++ b/core/runtime/op_driver/futures_unordered_driver.rs @@ -6,7 +6,6 @@ use super::OpDriver; use super::OpInflightStats; use crate::OpId; use crate::PromiseId; -use anyhow::Error; use bit_set::BitSet; use deno_unsync::spawn; use deno_unsync::JoinHandle; @@ -124,7 +123,7 @@ impl FuturesUnorderedDriver { impl OpDriver for FuturesUnorderedDriver { fn submit_op_fallible< R: 'static, - E: Into + 'static, + E: Into + 'static, const LAZY: bool, const DEFERRED: bool, >( diff --git a/core/runtime/op_driver/mod.rs b/core/runtime/op_driver/mod.rs index 4133ec18d..d8ce54233 100644 --- a/core/runtime/op_driver/mod.rs +++ b/core/runtime/op_driver/mod.rs @@ -1,8 +1,8 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::OpId; use crate::PromiseId; -use anyhow::Error; use bit_set::BitSet; +use deno_core::error::AnyError; use std::future::Future; use std::task::Context; use std::task::Poll; @@ -84,7 +84,7 @@ pub(crate) trait OpDriver: /// might return an error (`Result`). fn submit_op_fallible< R: 'static, - E: Into + 'static, + E: Into + 'static, const LAZY: bool, const DEFERRED: bool, >( @@ -98,7 +98,7 @@ pub(crate) trait OpDriver: /// Submits an operation that is expected to complete successfully without errors. #[inline(always)] #[allow(clippy::too_many_arguments)] - fn submit_op_fallible_scheduling + 'static>( + fn submit_op_fallible_scheduling + 'static>( &self, scheduling: OpScheduling, op_id: OpId, @@ -160,7 +160,7 @@ mod tests { fn map_error( _context: &mut Self::Context, - err: Error, + err: AnyError, _get_error_class_fn: GetErrorClassFn, ) -> UnmappedResult<'s, Self> { Ok(format!("{err:?}")) diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index 097bff233..999e37e20 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -4,7 +4,7 @@ use super::future_arena::FutureContextMapper; use crate::GetErrorClassFn; use crate::OpId; use crate::PromiseId; -use anyhow::Error; +use deno_core::error::AnyError; use serde::Serialize; const MAX_RESULT_SIZE: usize = 32; @@ -25,7 +25,7 @@ pub trait OpMappingContextLifetime<'s> { fn map_error( context: &mut Self::Context, - err: Error, + err: AnyError, get_error_class_fn: GetErrorClassFn, ) -> UnmappedResult<'s, Self>; fn map_mapping_error( @@ -67,7 +67,7 @@ impl<'s> OpMappingContextLifetime<'s> for V8OpMappingContext { #[inline(always)] fn map_error( scope: &mut v8::HandleScope<'s>, - err: Error, + err: AnyError, get_error_class_fn: GetErrorClassFn, ) -> UnmappedResult<'s, Self> { serde_v8::to_v8(scope, OpError::new(get_error_class_fn, err)) @@ -106,7 +106,7 @@ pub struct PendingOp(pub PendingOpInfo, pub OpResult); impl PendingOp { #[inline(always)] - pub fn new + 'static>( + pub fn new + 'static>( info: PendingOpInfo, rv_map: C::MappingFn, result: Result, @@ -149,7 +149,7 @@ impl Clone } } -impl + 'static> +impl + 'static> FutureContextMapper, PendingOpInfo, Result> for PendingOpMappingInfo { @@ -225,7 +225,7 @@ impl ValueLargeFn for ValueLarge { pub enum OpResult { /// Errors. - Err(Error), + Err(AnyError), /// For small ops, we include them in an erased type container. Value(OpValue), /// For ops that return "large" results (> MAX_RESULT_SIZE bytes) we just box a function @@ -272,7 +272,7 @@ pub struct OpError { } impl OpError { - pub fn new(get_class: GetErrorClassFn, err: Error) -> Self { + pub fn new(get_class: GetErrorClassFn, err: AnyError) -> Self { Self { class_name: (get_class)(&err), message: format!("{err:#}"), diff --git a/core/runtime/ops.rs b/core/runtime/ops.rs index fc5d1daa5..e07144f52 100644 --- a/core/runtime/ops.rs +++ b/core/runtime/ops.rs @@ -1,6 +1,9 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +use super::op_driver::OpDriver; +use super::op_driver::OpScheduling; +use super::op_driver::V8RetValMapper; +use crate::error::AnyError; use crate::ops::*; -use anyhow::Error; use futures::future::Future; use serde::Deserialize; use serde_v8::from_v8; @@ -11,10 +14,6 @@ use std::mem::MaybeUninit; use std::ptr::NonNull; use v8::WriteOptions; -use super::op_driver::OpDriver; -use super::op_driver::OpScheduling; -use super::op_driver::V8RetValMapper; - /// The default string buffer size on the stack that prevents mallocs in some /// string functions. Keep in mind that Windows only offers 1MB stacks by default, /// so this is a limited resource! @@ -49,7 +48,7 @@ pub fn map_async_op_infallible( } #[inline(always)] -pub fn map_async_op_fallible + 'static>( +pub fn map_async_op_fallible + 'static>( ctx: &OpCtx, lazy: bool, deferred: bool, @@ -760,7 +759,7 @@ mod tests { runtime.run_event_loop(Default::default()).await?; if FAIL.with(|b| b.get()) { - Err(generic_error(format!("{op} test failed ({test})"))) + Err(generic_error(format!("{op} test failed ({test})")).into()) } else { Ok(()) } diff --git a/core/runtime/snapshot.rs b/core/runtime/snapshot.rs index 7fc5d051a..7d0f0c03c 100644 --- a/core/runtime/snapshot.rs +++ b/core/runtime/snapshot.rs @@ -1,6 +1,10 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use anyhow::Error; +use crate::error::PubError; +use crate::modules::ModuleMapSnapshotData; +use crate::Extension; +use crate::JsRuntimeForSnapshot; +use crate::RuntimeOptions; use serde::Deserialize; use serde::Serialize; use std::collections::HashMap; @@ -9,11 +13,6 @@ use std::path::PathBuf; use std::rc::Rc; use std::time::Instant; -use crate::modules::ModuleMapSnapshotData; -use crate::Extension; -use crate::JsRuntimeForSnapshot; -use crate::RuntimeOptions; - use super::ExtensionTranspiler; pub type WithRuntimeCb = dyn Fn(&mut JsRuntimeForSnapshot); @@ -130,7 +129,7 @@ pub struct CreateSnapshotOutput { pub fn create_snapshot( create_snapshot_options: CreateSnapshotOptions, warmup_script: Option<&'static str>, -) -> Result { +) -> Result { let mut mark = Instant::now(); #[allow(clippy::print_stdout)] { diff --git a/dcore/src/main.rs b/dcore/src/main.rs index 705fad8c4..04fba60a6 100644 --- a/dcore/src/main.rs +++ b/dcore/src/main.rs @@ -1,6 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use anyhow::Context; use clap::builder::Arg; use clap::builder::Command; use clap::ArgMatches; @@ -10,6 +9,7 @@ use deno_core_testing::create_runtime_from_snapshot; use std::net::SocketAddr; +use anyhow::Context; use std::sync::Arc; static SNAPSHOT: &[u8] = @@ -65,7 +65,7 @@ fn main() -> Result<(), Error> { js_runtime.run_event_loop(Default::default()).await?; result.await }; - runtime.block_on(future) + runtime.block_on(future).map_err(|e| e.into()) } fn build_cli() -> Command { diff --git a/testing/checkin/runner/ops_error.rs b/testing/checkin/runner/ops_error.rs index f0c8c7d31..3dc74d486 100644 --- a/testing/checkin/runner/ops_error.rs +++ b/testing/checkin/runner/ops_error.rs @@ -7,22 +7,22 @@ use deno_core::op2; #[op2(async)] pub async fn op_async_throw_error_eager() -> Result<(), Error> { - Err(type_error("Error")) + Err(type_error("Error").into()) } #[op2(async(deferred), fast)] pub async fn op_async_throw_error_deferred() -> Result<(), Error> { - Err(type_error("Error")) + Err(type_error("Error").into()) } #[op2(async(lazy), fast)] pub async fn op_async_throw_error_lazy() -> Result<(), Error> { - Err(type_error("Error")) + Err(type_error("Error").into()) } #[op2(fast)] pub fn op_error_custom_sync(#[string] message: String) -> Result<(), Error> { - Err(custom_error("BadResource", message)) + Err(custom_error("BadResource", message).into()) } #[op2(fast)] diff --git a/testing/checkin/runner/ops_worker.rs b/testing/checkin/runner/ops_worker.rs index 3aa0715f5..4d0fbedf0 100644 --- a/testing/checkin/runner/ops_worker.rs +++ b/testing/checkin/runner/ops_worker.rs @@ -138,7 +138,9 @@ async fn run_worker_task( // This matches the v8 error. We'll hit both, depending on timing. return Poll::Ready(Err(anyhow!("Uncaught Error: execution terminated"))); } - runtime.poll_event_loop(cx, PollEventLoopOptions::default()) + runtime + .poll_event_loop(cx, PollEventLoopOptions::default()) + .map_err(|e| e.into()) }) .await { diff --git a/testing/checkin/runner/ts_module_loader.rs b/testing/checkin/runner/ts_module_loader.rs index 8c18f4e94..f9db85030 100644 --- a/testing/checkin/runner/ts_module_loader.rs +++ b/testing/checkin/runner/ts_module_loader.rs @@ -5,14 +5,13 @@ use std::fs; use std::path::Path; use std::rc::Rc; -use anyhow::bail; use anyhow::Context; -use anyhow::Error; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; use deno_core::error::AnyError; +use deno_core::error::ModuleLoaderError; use deno_core::resolve_import; use deno_core::url::Url; use deno_core::ModuleCodeBytes; @@ -44,7 +43,7 @@ impl ModuleLoader for TypescriptModuleLoader { specifier: &str, referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { Ok(resolve_import(specifier, referrer)?) } @@ -60,7 +59,7 @@ impl ModuleLoader for TypescriptModuleLoader { source_maps: SourceMapStore, module_specifier: &ModuleSpecifier, requested_module_type: RequestedModuleType, - ) -> Result { + ) -> Result { let root = Path::new(env!("CARGO_MANIFEST_DIR")); let start = if module_specifier.scheme() == "test" { 1 @@ -96,11 +95,14 @@ impl ModuleLoader for TypescriptModuleLoader { if path.extension().unwrap_or_default() == "nocompile" { (ModuleType::JavaScript, false) } else { - bail!("Unknown extension {:?}", path.extension()); + return Err( + anyhow::anyhow!("Unknown extension {:?}", path.extension()) + .into(), + ); } } }; - let code = std::fs::read_to_string(&path).with_context(|| { + let code = fs::read_to_string(&path).with_context(|| { format!("Trying to load {path:?} for {module_specifier}") })?; let code = if should_transpile { @@ -111,20 +113,23 @@ impl ModuleLoader for TypescriptModuleLoader { capture_tokens: false, scope_analysis: false, maybe_syntax: None, - })?; - let res = parsed.transpile( - &deno_ast::TranspileOptions { - imports_not_used_as_values: - deno_ast::ImportsNotUsedAsValues::Remove, - use_decorators_proposal: true, - ..Default::default() - }, - &deno_ast::EmitOptions { - source_map: SourceMapOption::Separate, - inline_sources: false, - ..Default::default() - }, - )?; + }) + .map_err(AnyError::from)?; + let res = parsed + .transpile( + &deno_ast::TranspileOptions { + imports_not_used_as_values: + deno_ast::ImportsNotUsedAsValues::Remove, + use_decorators_proposal: true, + ..Default::default() + }, + &deno_ast::EmitOptions { + source_map: SourceMapOption::Separate, + inline_sources: false, + ..Default::default() + }, + ) + .map_err(AnyError::from)?; let res = res.into_source(); let source_map = res.source_map.unwrap(); source_maps From 9628c15c6e83d84ae2529c454ff273f363ca9645 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Thu, 22 Aug 2024 14:41:19 +0200 Subject: [PATCH 02/52] more error handling! --- core/benches/ops/async.rs | 4 +- core/benches/ops/sync.rs | 6 +- core/benches/snapshot/snapshot.rs | 3 +- core/convert.rs | 5 +- core/error.rs | 228 +++++++++++++----- core/error_codes.rs | 8 +- core/examples/hello_world.rs | 4 +- core/extension_set.rs | 12 +- core/inspector.rs | 4 +- core/io/resource.rs | 14 +- core/io/resource_table.rs | 60 +++-- core/lib.rs | 3 - core/module_specifier.rs | 12 + core/modules/loaders.rs | 13 +- core/modules/map.rs | 50 ++-- core/modules/tests.rs | 6 +- core/ops.rs | 13 +- core/ops_builtin.rs | 54 +++-- core/ops_builtin_v8.rs | 98 +++++--- core/runtime/jsrealm.rs | 4 - core/runtime/jsruntime.rs | 13 +- .../op_driver/futures_unordered_driver.rs | 2 +- core/runtime/op_driver/mod.rs | 25 +- core/runtime/op_driver/op_results.rs | 66 +++-- core/runtime/ops.rs | 96 ++++---- core/runtime/tests/error.rs | 1 - core/runtime/tests/misc.rs | 25 +- core/runtime/tests/mod.rs | 7 +- core/runtime/tests/ops.rs | 20 +- dcore/src/inspector_server.rs | 12 +- ops/op2/dispatch_slow.rs | 5 +- ops/op2/signature.rs | 38 +-- ops/op2/test_cases/async/async_result_impl.rs | 4 +- ops/op2/test_cases/compiler_pass/async.rs | 6 +- ops/op2/test_cases/sync/bool_result.rs | 4 +- ops/op2/test_cases/sync/result_external.rs | 4 +- ops/op2/test_cases/sync/result_primitive.rs | 4 +- ops/op2/test_cases/sync/result_scope.rs | 4 +- ops/op2/test_cases_fail/lifetimes.rs | 1 - testing/checkin/runner/mod.rs | 3 - testing/checkin/runner/ops_error.rs | 11 +- testing/checkin/runner/ts_module_loader.rs | 7 +- 42 files changed, 564 insertions(+), 395 deletions(-) diff --git a/core/benches/ops/async.rs b/core/benches/ops/async.rs index 84656ff72..8c3664f0c 100644 --- a/core/benches/ops/async.rs +++ b/core/benches/ops/async.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use bencher::*; -use deno_core::error::generic_error; +use deno_core::error::JsNativeError; use deno_core::*; use std::ffi::c_void; use tokio::runtime::Runtime; @@ -118,7 +118,7 @@ fn bench_op( ..Default::default() }); let err_mapper = - |err| generic_error(format!("{op} test failed ({call}): {err:?}")); + |err| JsNativeError::generic(format!("{op} test failed ({call}): {err:?}")); let args = (0..arg_count) .map(|n| format!("arg{n}")) diff --git a/core/benches/ops/sync.rs b/core/benches/ops/sync.rs index 9f483ea41..32e3811bf 100644 --- a/core/benches/ops/sync.rs +++ b/core/benches/ops/sync.rs @@ -1,7 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. #![allow(deprecated)] use bencher::*; -use deno_core::error::generic_error; use deno_core::*; use std::borrow::Cow; use std::ffi::c_void; @@ -169,8 +168,9 @@ fn bench_op( })), ..Default::default() }); - let err_mapper = - |err| generic_error(format!("{op} test failed ({call}): {err:?}")); + let err_mapper = |err| { + error::JsNativeError::generic(format!("{op} test failed ({call}): {err:?}")) + }; let args = (0..arg_count) .map(|n| format!("arg{n}")) diff --git a/core/benches/snapshot/snapshot.rs b/core/benches/snapshot/snapshot.rs index 7e0b019b9..28a100290 100644 --- a/core/benches/snapshot/snapshot.rs +++ b/core/benches/snapshot/snapshot.rs @@ -3,7 +3,6 @@ use criterion::*; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; -use deno_core::error::AnyError; use deno_core::Extension; use deno_core::JsRuntime; use deno_core::JsRuntimeForSnapshot; @@ -52,7 +51,7 @@ fn make_extensions_ops() -> Vec { pub fn maybe_transpile_source( specifier: ModuleName, source: ModuleCodeString, -) -> Result<(ModuleCodeString, Option), AnyError> { +) -> Result<(ModuleCodeString, Option), anyhow::Error> { let media_type = MediaType::TypeScript; let parsed = deno_ast::parse_module(ParseParams { diff --git a/core/convert.rs b/core/convert.rs index 672f3d55c..6b5fc0c97 100644 --- a/core/convert.rs +++ b/core/convert.rs @@ -178,7 +178,7 @@ impl<'a, T: SmallInt> FromV8<'a> for Smi { value: v8::Local<'a, v8::Value>, ) -> Result { let v = crate::runtime::ops::to_i32_option(&value).ok_or_else(|| { - crate::error::type_error(format!("Expected {}", T::NAME)) + crate::error::JsNativeError::type_error(format!("Expected {}", T::NAME)) })?; Ok(Smi(T::from_i32(v))) } @@ -247,7 +247,8 @@ impl<'a, T: Numeric> FromV8<'a> for Number { value: v8::Local<'a, v8::Value>, ) -> Result { T::from_value(&value).map(Number).ok_or_else(|| { - crate::error::type_error(format!("Expected {}", T::NAME)).into() + crate::error::JsNativeError::type_error(format!("Expected {}", T::NAME)) + .into() }) } } diff --git a/core/error.rs b/core/error.rs index b27277a15..ce0d4106f 100644 --- a/core/error.rs +++ b/core/error.rs @@ -1,5 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +pub use super::runtime::op_driver::OpError; use std::borrow::Cow; use std::collections::HashSet; use std::fmt; @@ -8,7 +9,6 @@ use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write as _; use thiserror::__private::AsDynError; -use v8::Object; pub use crate::modules::ModuleLoaderError; use crate::runtime::v8_static_strings; @@ -22,13 +22,9 @@ use crate::FastStaticString; // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. pub type AnyError = anyhow::Error; -pub type JsErrorCreateFn = dyn Fn(JsError) -> anyhow::Error; -pub type GetErrorClassFn = - &'static dyn for<'e> Fn(&'e anyhow::Error) -> &'static str; - #[derive(Debug, thiserror::Error)] pub enum PubError { - #[error("level await is not allowed in extensions")] + #[error("top level await is not allowed in extensions")] TLA(JsError), #[error(transparent)] Js(#[from] JsError), @@ -61,7 +57,7 @@ pub enum PubError { )] NpmMetaResolve, #[error(transparent)] - Custom(#[from] CustomError), + JsNativeError(#[from] JsNativeError), #[error(transparent)] Url(#[from] url::ParseError), #[error(transparent)] @@ -83,10 +79,107 @@ impl From for PubError { } } -pub trait JsClassError: std::error::Error { +pub trait JsErrorClass: std::any::Any + Debug + 'static { fn get_class(&self) -> &'static str; + fn get_message(&self) -> Cow<'static, str>; +} + +pub fn get_error_class(error: &dyn std::any::Any) -> &'static str { + if let Some(error) = error.downcast_ref::() { + error.get_class() + } else { + // Default value when trait is not implemented + "Error" + } +} + +impl JsErrorClass for serde_v8::Error { + fn get_class(&self) -> &'static str { + "TypeError" + } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } +} + +impl JsErrorClass for std::io::Error { + fn get_class(&self) -> &'static str { + use std::io::ErrorKind::*; + + match self.kind() { + NotFound => "NotFound", + PermissionDenied => "PermissionDenied", + ConnectionRefused => "ConnectionRefused", + ConnectionReset => "ConnectionReset", + ConnectionAborted => "ConnectionAborted", + NotConnected => "NotConnected", + AddrInUse => "AddrInUse", + AddrNotAvailable => "AddrNotAvailable", + BrokenPipe => "BrokenPipe", + AlreadyExists => "AlreadyExists", + InvalidInput => "TypeError", + InvalidData => "InvalidData", + TimedOut => "TimedOut", + Interrupted => "Interrupted", + WriteZero => "WriteZero", + UnexpectedEof => "UnexpectedEof", + Other => "Error", + WouldBlock => "WouldBlock", + FilesystemLoop => "FilesystemLoop", + IsADirectory => "IsADirectory", + NetworkUnreachable => "NetworkUnreachable", + NotADirectory => "NotADirectory", + // Non-exhaustive enum - might add new variants + // in the future + _ => "Error", + } + } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } +} + +impl JsErrorClass for v8::DataError { + fn get_class(&self) -> &'static str { + todo!() + } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } +} + +impl JsErrorClass for serde_json::Error { + fn get_class(&self) -> &'static str { + use serde::de::StdError; + use serde_json::error::*; + + match self.classify() { + Category::Io => self + .source() + .and_then(|e| e.downcast_ref::()) + .unwrap() + .get_class(), + Category::Syntax => "SyntaxError", + Category::Data => "InvalidData", + Category::Eof => "UnexpectedEof", + } + } + fn get_message(&self) -> Cow<'static, str> { - self.to_string() + self.to_string().into() + } +} + +impl JsErrorClass for url::ParseError { + fn get_class(&self) -> &'static str { + "URIError" + } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() } } @@ -95,13 +188,13 @@ pub trait JsClassError: std::error::Error { /// wrapped in an `anyhow::Error`. To retrieve the error class name from a wrapped /// `CustomError`, use the function `get_custom_error_class()`. #[derive(Debug, thiserror::Error)] -#[error("{message}")] -pub struct CustomError { +#[error("{class}: {message}")] +pub struct JsNativeError { pub class: &'static str, message: Cow<'static, str>, } -impl JsClassError for CustomError { +impl JsErrorClass for JsNativeError { fn get_class(&self) -> &'static str { self.class } @@ -111,64 +204,61 @@ impl JsClassError for CustomError { } } -/// Creates a new error with a caller-specified error class name and message. -pub fn custom_error( - class: &'static str, - message: impl Into>, -) -> PubError { - PubError::Custom(CustomError { - class, - message: message.into(), - }) -} +impl JsNativeError { + pub fn new( + class: &'static str, + message: impl Into>, + ) -> JsNativeError { + JsNativeError { + class, + message: message.into(), + } + } -pub fn generic_error(message: impl Into>) -> PubError { - custom_error("Error", message) -} + pub fn generic(message: impl Into>) -> JsNativeError { + Self::new("Error", message) + } -pub fn type_error(message: impl Into>) -> PubError { - custom_error("TypeError", message) -} + pub fn type_error(message: impl Into>) -> JsNativeError { + Self::new("TypeError", message) + } -pub fn range_error(message: impl Into>) -> PubError { - custom_error("RangeError", message) -} + pub fn range_error(message: impl Into>) -> JsNativeError { + Self::new("RangeError", message) + } -pub fn invalid_hostname(hostname: &str) -> PubError { - type_error(format!("Invalid hostname: '{hostname}'")) -} + pub fn reference_error( + message: impl Into>, + ) -> JsNativeError { + Self::new("RangeError", message) + } -pub fn uri_error(message: impl Into>) -> PubError { - custom_error("URIError", message) -} + pub fn uri_error(message: impl Into>) -> JsNativeError { + Self::new("URIError", message) + } -pub fn bad_resource(message: impl Into>) -> PubError { - custom_error("BadResource", message) -} + // Non-standard errors -pub fn bad_resource_id() -> PubError { - custom_error("BadResource", "Bad resource ID") -} + pub fn bad_resource(message: impl Into>) -> JsNativeError { + Self::new("BadResource", message) + } -pub fn not_supported() -> PubError { - custom_error("NotSupported", "The operation is not supported") -} + pub fn bad_resource_id() -> JsNativeError { + Self::bad_resource("Bad resource ID") + } -pub fn resource_unavailable() -> PubError { - custom_error( - "Busy", - "Resource is unavailable because it is in use by a promise", - ) + pub fn not_supported() -> JsNativeError { + Self::new("NotSupported", "The operation is not supported") + } } pub fn get_custom_error_class(error: &anyhow::Error) -> Option<&'static str> { - error.downcast_ref::().map(|e| e.class) + error.downcast_ref::().map(|e| e.class) } pub fn to_v8_error<'a>( scope: &mut v8::HandleScope<'a>, - get_class: GetErrorClassFn, - error: &anyhow::Error, + error: &impl JsErrorClass, ) -> v8::Local<'a, v8::Value> { let tc_scope = &mut v8::TryCatch::new(scope); let cb = JsRealm::exception_state_from_scope(tc_scope) @@ -178,8 +268,8 @@ pub fn to_v8_error<'a>( .expect("Custom error builder must be set"); let cb = cb.open(tc_scope); let this = v8::undefined(tc_scope).into(); - let class = v8::String::new(tc_scope, get_class(error)).unwrap(); - let message = v8::String::new(tc_scope, &format!("{error:#}")).unwrap(); + let class = v8::String::new(tc_scope, error.get_class()).unwrap(); + let message = v8::String::new(tc_scope, &error.get_message()).unwrap(); let mut args = vec![class.into(), message.into()]; if let Some(code) = crate::error_codes::get_error_code(error) { args.push(v8::String::new(tc_scope, code).unwrap().into()); @@ -1067,8 +1157,12 @@ fn make_patched_callsite<'s>( callsite: v8::Local<'s, v8::Object>, prototype: v8::Local<'s, v8::Object>, ) -> v8::Local<'s, v8::Object> { - let out_obj = - Object::with_prototype_and_properties(scope, prototype.into(), &[], &[]); + let out_obj = v8::Object::with_prototype_and_properties( + scope, + prototype.into(), + &[], + &[], + ); let orig_key = original_call_site_key(scope); out_obj.set_private(scope, orig_key, callsite.into()); out_obj @@ -1433,7 +1527,7 @@ pub fn format_location(frame: &JsStackFrame) -> String { ErrorElement::EvalOrigin, frame.eval_origin.as_ref().unwrap(), ) - .to_string() + .to_string() + ", "); } result += &F::fmt_element(Anonymous, ""); @@ -1444,14 +1538,14 @@ pub fn format_location(frame: &JsStackFrame) -> String { ":{}", F::fmt_element(LineNumber, &line_number.to_string()) ) - .unwrap(); + .unwrap(); if let Some(column_number) = frame.column_number { write!( result, ":{}", F::fmt_element(ColumnNumber, &column_number.to_string()) ) - .unwrap(); + .unwrap(); } } result @@ -1529,13 +1623,13 @@ mod tests { #[test] fn test_bad_resource() { - let err = bad_resource("Resource has been closed"); + let err = JsNativeError::bad_resource("Resource has been closed"); assert_eq!(err.to_string(), "Resource has been closed"); } #[test] fn test_bad_resource_id() { - let err = bad_resource_id(); + let err = JsNativeError::bad_resource_id(); assert_eq!(err.to_string(), "Bad resource ID"); } @@ -1595,10 +1689,10 @@ mod tests { for (input, expect) in cases { match expect { Some(( - expect_before, - (expect_file, expect_line, expect_col), - expect_after, - )) => { + expect_before, + (expect_file, expect_line, expect_col), + expect_after, + )) => { let (before, (file_name, line_number, column_number), after) = parse_eval_origin(input).unwrap(); assert_eq!(before, expect_before); diff --git a/core/error_codes.rs b/core/error_codes.rs index fea5d383f..d96ea42de 100644 --- a/core/error_codes.rs +++ b/core/error_codes.rs @@ -1,9 +1,9 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use anyhow::Error; - -pub fn get_error_code(err: &Error) -> Option<&'static str> { - err +pub fn get_error_code( + err: &impl crate::error::JsErrorClass, +) -> Option<&'static str> { + (&err as &dyn std::any::Any) .downcast_ref::() .map(|e| match e.raw_os_error() { Some(code) => get_os_error_code(code), diff --git a/core/examples/hello_world.rs b/core/examples/hello_world.rs index 6e99349a7..e254ac9ab 100644 --- a/core/examples/hello_world.rs +++ b/core/examples/hello_world.rs @@ -7,10 +7,10 @@ use deno_core::*; /// An op for summing an array of numbers. The op-layer automatically /// deserializes inputs and serializes the returned Result & value. #[op2] -fn op_sum(#[serde] nums: Vec) -> Result { +fn op_sum(#[serde] nums: Vec) -> Result { // Sum inputs let sum = nums.iter().fold(0.0, |a, v| a + v); - // return as a Result + // return as a Result Ok(sum) } diff --git a/core/extension_set.rs b/core/extension_set.rs index 712df8b78..dbb6a1390 100644 --- a/core/extension_set.rs +++ b/core/extension_set.rs @@ -1,7 +1,4 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use std::cell::RefCell; -use std::iter::Chain; -use std::rc::Rc; use crate::error::PubError; use crate::extensions::Extension; use crate::extensions::ExtensionSourceType; @@ -15,12 +12,14 @@ use crate::runtime::JsRuntimeState; use crate::runtime::OpDriverImpl; use crate::ExtensionFileSource; use crate::FastString; -use crate::GetErrorClassFn; use crate::ModuleCodeString; use crate::OpDecl; use crate::OpMetricsFactoryFn; use crate::OpState; use crate::SourceMapData; +use std::cell::RefCell; +use std::iter::Chain; +use std::rc::Rc; /// Contribute to the `OpState` from each extension. pub fn setup_op_state(op_state: &mut OpState, extensions: &mut [Extension]) { @@ -124,7 +123,6 @@ pub fn create_op_ctxs( op_driver: Rc, op_state: Rc>, runtime_state: Rc, - get_error_class_fn: GetErrorClassFn, ) -> Box<[OpCtx]> { let op_count = op_decls.len(); let mut op_ctxs = Vec::with_capacity(op_count); @@ -142,7 +140,6 @@ pub fn create_op_ctxs( decl, op_state.clone(), runtime_state_ptr, - get_error_class_fn, metrics_fn, ); @@ -248,7 +245,8 @@ fn load( let mut source_map = None; if let Some(transpiler) = transpiler { (source_code, source_map) = - transpiler(ModuleName::from_static(source.specifier), source_code).map_err(PubError::ExtensionTranspiler)?; + transpiler(ModuleName::from_static(source.specifier), source_code) + .map_err(PubError::ExtensionTranspiler)?; } let mut maybe_source_map = None; if let Some(source_map) = source_map { diff --git a/core/inspector.rs b/core/inspector.rs index 7896da6c1..75e7b8518 100644 --- a/core/inspector.rs +++ b/core/inspector.rs @@ -4,7 +4,6 @@ //! //! -use crate::error::generic_error; use crate::error::PubError; use crate::futures::channel::mpsc; use crate::futures::channel::mpsc::UnboundedReceiver; @@ -20,6 +19,7 @@ use crate::futures::task::Context; use crate::futures::task::Poll; use crate::serde_json::json; use crate::serde_json::Value; +use deno_core::error::JsNativeError; use parking_lot::Mutex; use std::cell::BorrowMutError; use std::cell::RefCell; @@ -790,7 +790,7 @@ impl LocalInspectorSession { Either::Right((result, _)) => { let response = result?; if let Some(error) = response.get("error") { - return Err(generic_error(error.to_string())); + return Err(JsNativeError::generic(error.to_string()).into()); } let result = response.get("result").unwrap().clone(); diff --git a/core/io/resource.rs b/core/io/resource.rs index 37d3e45cf..7c02a9f42 100644 --- a/core/io/resource.rs +++ b/core/io/resource.rs @@ -6,8 +6,8 @@ // resources. Resources may or may not correspond to a real operating system // file descriptor (hence the different name). -use crate::error::not_supported; use crate::error::AnyError; +use crate::error::JsNativeError; use crate::io::AsyncResult; use crate::io::BufMutView; use crate::io::BufView; @@ -85,7 +85,7 @@ pub trait Resource: Any + 'static { /// implement `read_byob()`. fn read(self: Rc, limit: usize) -> AsyncResult { _ = limit; - Box::pin(futures::future::err(not_supported().into())) + Box::pin(futures::future::err(JsNativeError::not_supported().into())) } /// Read a single chunk of data from the resource into the provided `BufMutView`. @@ -111,7 +111,7 @@ pub trait Resource: Any + 'static { /// Write an error state to this resource, if the resource supports it. fn write_error(self: Rc, _error: AnyError) -> AsyncResult<()> { - Box::pin(futures::future::err(not_supported().into())) + Box::pin(futures::future::err(JsNativeError::not_supported().into())) } /// Write a single chunk of data to the resource. The operation may not be @@ -123,7 +123,7 @@ pub trait Resource: Any + 'static { /// with a "not supported" error. fn write(self: Rc, buf: BufView) -> AsyncResult { _ = buf; - Box::pin(futures::future::err(not_supported().into())) + Box::pin(futures::future::err(JsNativeError::not_supported().into())) } /// Write an entire chunk of data to the resource. Unlike `write()`, this will @@ -160,13 +160,13 @@ pub trait Resource: Any + 'static { data: &mut [u8], ) -> Result { _ = data; - Err(not_supported().into()) + Err(JsNativeError::not_supported().into()) } /// The same as [`write()`][Resource::write], but synchronous. fn write_sync(self: Rc, data: &[u8]) -> Result { _ = data; - Err(not_supported().into()) + Err(JsNativeError::not_supported().into()) } /// The shutdown method can be used to asynchronously close the resource. It @@ -175,7 +175,7 @@ pub trait Resource: Any + 'static { /// If this method is not implemented, the default implementation will error /// with a "not supported" error. fn shutdown(self: Rc) -> AsyncResult<()> { - Box::pin(futures::future::err(not_supported().into())) + Box::pin(futures::future::err(JsNativeError::not_supported().into())) } /// Resources may implement the `close()` trait method if they need to do diff --git a/core/io/resource_table.rs b/core/io/resource_table.rs index dec488cbb..08f246d5d 100644 --- a/core/io/resource_table.rs +++ b/core/io/resource_table.rs @@ -3,9 +3,7 @@ use super::Resource; use super::ResourceHandle; use super::ResourceHandleFd; use super::ResourceHandleSocket; -use crate::error::bad_resource_id; -use crate::error::custom_error; -use crate::error::PubError; +use crate::error::JsNativeError; use std::borrow::Cow; use std::collections::BTreeMap; use std::rc::Rc; @@ -80,17 +78,27 @@ impl ResourceTable { /// Returns a reference counted pointer to the resource of type `T` with the /// given `rid`. If `rid` is not present or has a type different than `T`, /// this function returns `None`. - pub fn get(&self, rid: ResourceId) -> Result, PubError> { + pub fn get( + &self, + rid: ResourceId, + ) -> Result, JsNativeError> { self .index .get(&rid) .and_then(|rc| rc.downcast_rc::()) .cloned() - .ok_or_else(bad_resource_id) + .ok_or_else(JsNativeError::bad_resource_id) } - pub fn get_any(&self, rid: ResourceId) -> Result, PubError> { - self.index.get(&rid).cloned().ok_or_else(bad_resource_id) + pub fn get_any( + &self, + rid: ResourceId, + ) -> Result, JsNativeError> { + self + .index + .get(&rid) + .cloned() + .ok_or_else(JsNativeError::bad_resource_id) } /// Replaces a resource with a new resource. @@ -116,7 +124,7 @@ impl ResourceTable { pub fn take( &mut self, rid: ResourceId, - ) -> Result, PubError> { + ) -> Result, JsNativeError> { let resource = self.get::(rid)?; self.index.remove(&rid); Ok(resource) @@ -133,8 +141,11 @@ impl ResourceTable { pub fn take_any( &mut self, rid: ResourceId, - ) -> Result, PubError> { - self.index.remove(&rid).ok_or_else(bad_resource_id) + ) -> Result, JsNativeError> { + self + .index + .remove(&rid) + .ok_or_else(JsNativeError::bad_resource_id) } /// Removes the resource with the given `rid` from the resource table. If the @@ -144,11 +155,11 @@ impl ResourceTable { /// may implement the `close()` method to perform clean-ups such as canceling /// ops. #[deprecated = "This method may deadlock. Use take() and close() instead."] - pub fn close(&mut self, rid: ResourceId) -> Result<(), PubError> { + pub fn close(&mut self, rid: ResourceId) -> Result<(), JsNativeError> { self .index .remove(&rid) - .ok_or_else(bad_resource_id) + .ok_or_else(JsNativeError::bad_resource_id) .map(|resource| resource.close()) } @@ -173,15 +184,18 @@ impl ResourceTable { /// Retrieves the [`ResourceHandleFd`] for a given resource, for potential optimization /// purposes within ops. - pub fn get_fd(&self, rid: ResourceId) -> Result { + pub fn get_fd( + &self, + rid: ResourceId, + ) -> Result { let Some(handle) = self.get_any(rid)?.backing_handle() else { - return Err(bad_resource_id()); + return Err(JsNativeError::bad_resource_id()); }; let Some(fd) = handle.as_fd_like() else { - return Err(bad_resource_id()); + return Err(JsNativeError::bad_resource_id()); }; if !handle.is_valid() { - return Err(custom_error("ReferenceError", "null or invalid handle")); + return Err(JsNativeError::reference_error("null or invalid handle")); } Ok(fd) } @@ -191,15 +205,15 @@ impl ResourceTable { pub fn get_socket( &self, rid: ResourceId, - ) -> Result { + ) -> Result { let Some(handle) = self.get_any(rid)?.backing_handle() else { - return Err(bad_resource_id()); + return Err(JsNativeError::bad_resource_id()); }; let Some(socket) = handle.as_socket_like() else { - return Err(bad_resource_id()); + return Err(JsNativeError::bad_resource_id()); }; if !handle.is_valid() { - return Err(custom_error("ReferenceError", "null or invalid handle")); + return Err(JsNativeError::reference_error("null or invalid handle")); } Ok(socket) } @@ -209,12 +223,12 @@ impl ResourceTable { pub fn get_handle( &self, rid: ResourceId, - ) -> Result { + ) -> Result { let Some(handle) = self.get_any(rid)?.backing_handle() else { - return Err(bad_resource_id()); + return Err(JsNativeError::bad_resource_id()); }; if !handle.is_valid() { - return Err(custom_error("ReferenceError", "null or invalid handle")); + return Err(JsNativeError::reference_error("null or invalid handle")); } Ok(handle) } diff --git a/core/lib.rs b/core/lib.rs index 977fa1317..a08f23d50 100644 --- a/core/lib.rs +++ b/core/lib.rs @@ -70,8 +70,6 @@ pub use crate::async_cell::RcRef; pub use crate::convert::FromV8; pub use crate::convert::ToV8; pub use crate::cppgc::GarbageCollected; -pub use crate::error::GetErrorClassFn; -pub use crate::error::JsErrorCreateFn; pub use crate::extensions::Extension; pub use crate::extensions::ExtensionFileSource; pub use crate::extensions::ExtensionFileSourceCode; @@ -179,7 +177,6 @@ pub mod _ops { pub use super::cppgc::make_cppgc_object; pub use super::cppgc::try_unwrap_cppgc_object; pub use super::error::throw_type_error; - pub use super::error_codes::get_error_code; pub use super::extensions::Op; pub use super::extensions::OpDecl; #[cfg(debug_assertions)] diff --git a/core/module_specifier.rs b/core/module_specifier.rs index 5c9f351e9..4179dcff7 100644 --- a/core/module_specifier.rs +++ b/core/module_specifier.rs @@ -1,6 +1,7 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::normalize_path; +use std::borrow::Cow; use std::path::Path; use std::path::PathBuf; use url::ParseError; @@ -24,6 +25,17 @@ pub enum ModuleResolutionError { maybe_referrer: Option, }, } + +impl super::error::JsErrorClass for ModuleResolutionError { + fn get_class(&self) -> &'static str { + "URIError" + } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } +} + use ModuleResolutionError::*; /// Resolved module specifier diff --git a/core/modules/loaders.rs b/core/modules/loaders.rs index ab31ae406..01b81e87b 100644 --- a/core/modules/loaders.rs +++ b/core/modules/loaders.rs @@ -1,5 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::generic_error; +use crate::error::JsNativeError; use crate::extensions::ExtensionFileSource; use crate::module_specifier::ModuleSpecifier; use crate::modules::IntoModuleCodeString; @@ -24,15 +24,18 @@ use std::rc::Rc; #[derive(Debug, thiserror::Error)] pub enum ModuleLoaderError { - #[error("Specifier \"{0}\" was not passed as an extension module and was not included in the snapshot.")] + #[error("Specifier \"{0}\" was not passed as an extension module and was not included in the snapshot." + )] SpecifierExcludedFromSnapshot(ModuleSpecifier), - #[error("Specifier \"{0}\" cannot be lazy-loaded as it was not included in the binary.")] + #[error("Specifier \"{0}\" cannot be lazy-loaded as it was not included in the binary." + )] SpecifierMissingLazyLoadable(ModuleSpecifier), #[error( "\"npm:\" specifiers are currently not supported in import.meta.resolve()" )] NpmUnsupportedMetaResolve, - #[error("Attempted to load JSON module without specifying \"type\": \"json\" attribute in the import statement.")] + #[error("Attempted to load JSON module without specifying \"type\": \"json\" attribute in the import statement." + )] JsonMissingAttribute, #[error("Module not found")] NotFound, @@ -374,7 +377,7 @@ impl ModuleLoader for FsModuleLoader { let module_specifier = module_specifier.clone(); let fut = async move { let path = module_specifier.to_file_path().map_err(|_| { - anyhow::Error::from(generic_error(format!( + anyhow::Error::from(JsNativeError::generic(format!( "Provided module specifier \"{module_specifier}\" is not a file URL." ))) })?; diff --git a/core/modules/map.rs b/core/modules/map.rs index 3139e8906..f2cb4e20d 100644 --- a/core/modules/map.rs +++ b/core/modules/map.rs @@ -4,10 +4,10 @@ use super::IntoModuleCodeString; use super::IntoModuleName; use crate::ascii_str; use crate::error::exception_to_err_result; -use crate::error::generic_error; use crate::error::throw_type_error; use crate::error::to_v8_type_error; use crate::error::JsError; +use crate::error::JsNativeError; use crate::modules::get_requested_module_type_from_attributes; use crate::modules::parse_import_attributes; use crate::modules::recursive_load::RecursiveModuleLoad; @@ -377,9 +377,12 @@ impl ModuleMap { )? } ModuleType::Wasm => { - return Err(ModuleError::Other(generic_error( - "Importing Wasm modules is currently not supported.", - ))); + return Err(ModuleError::Other( + JsNativeError::generic( + "Importing Wasm modules is currently not supported.", + ) + .into(), + )); } ModuleType::Json => { let code = ModuleSource::get_string_source(code); @@ -391,10 +394,13 @@ impl ModuleMap { state.custom_module_evaluation_cb.as_ref(); let Some(custom_evaluation_cb) = custom_module_evaluation_cb else { - return Err(ModuleError::Other(generic_error(format!( - "Importing '{}' modules is not supported", - module_type - )))); + return Err(ModuleError::Other( + JsNativeError::generic(format!( + "Importing '{}' modules is not supported", + module_type + )) + .into(), + )); }; // TODO(bartlomieju): creating a global just to create a local from it @@ -580,11 +586,11 @@ impl ModuleMap { let data = self.data.borrow(); if let Some(main_module) = data.main_module_id { let main_name = self.data.borrow().get_name_by_id(main_module).unwrap(); - return Err(ModuleError::Other(generic_error( + return Err(ModuleError::Other(JsNativeError::generic( format!("Trying to create \"main\" module ({:?}), when one already exists ({:?})", - name, - main_name, - )))); + name, + main_name, + )).into())); } } @@ -647,9 +653,12 @@ impl ModuleMap { let unbound_module_script = module.get_unbound_module_script(tc_scope); let code_cache = unbound_module_script.create_code_cache().ok_or_else(|| { - ModuleError::Other(generic_error( - "Unable to get code cache from unbound module script", - )) + ModuleError::Other( + JsNativeError::generic( + "Unable to get code cache from unbound module script", + ) + .into(), + ) })?; let fut = async move { (code_cache_info.ready_callback)(&code_cache).await } @@ -863,7 +872,7 @@ impl ModuleMap { referrer }; let msg = format!("Importing ext: modules is only allowed from ext: and node: modules. Tried to import {} from {}", specifier, referrer); - return Err(generic_error(msg)); + return Err(JsNativeError::generic(msg).into()); } self @@ -1265,7 +1274,7 @@ impl ModuleMap { self.pending_dyn_mod_evaluations_pending.set(true); } else if tc_scope.has_terminated() || tc_scope.is_execution_terminating() { return Err( - generic_error("Cannot evaluate dynamically imported module, because JavaScript execution has been terminated.") + JsNativeError::generic("Cannot evaluate dynamically imported module, because JavaScript execution has been terminated.").into() ); } else { assert_eq!(status, v8::ModuleStatus::Errored); @@ -1606,9 +1615,10 @@ impl ModuleMap { v8::ModuleStatus::Instantiated | v8::ModuleStatus::Evaluated )); - let module_namespace: v8::Local = - v8::Local::try_from(module.get_module_namespace()) - .map_err(|err: v8::DataError| generic_error(err.to_string()))?; + let module_namespace: v8::Local = v8::Local::try_from( + module.get_module_namespace(), + ) + .map_err(|err: v8::DataError| JsNativeError::generic(err.to_string()))?; Ok(v8::Global::new(scope, module_namespace)) } diff --git a/core/modules/tests.rs b/core/modules/tests.rs index af314d991..8f7d3a191 100644 --- a/core/modules/tests.rs +++ b/core/modules/tests.rs @@ -4,7 +4,7 @@ use crate::ascii_str; use crate::error::exception_to_err_result; -use crate::error::generic_error; +use crate::error::JsNativeError; use crate::modules::loaders::ModuleLoadEventCounts; use crate::modules::loaders::TestingModuleLoader; use crate::modules::loaders::*; @@ -799,7 +799,7 @@ fn test_custom_module_type_callback_synthetic() { module_code: ModuleSourceCode, ) -> Result { if module_type != "bytes" { - return Err(generic_error(format!( + return Err(JsNativeError::generic(format!( "Can't load '{}' module", module_type ))); @@ -883,7 +883,7 @@ fn test_custom_module_type_callback_computed() { module_code: ModuleSourceCode, ) -> Result { if module_type != "foobar" { - return Err(generic_error(format!( + return Err(JsNativeError::generic(format!( "Can't load '{}' module", module_type ))); diff --git a/core/ops.rs b/core/ops.rs index 30c79be63..432b1433f 100644 --- a/core/ops.rs +++ b/core/ops.rs @@ -1,7 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::AnyError; -use crate::error::GetErrorClassFn; +use crate::error::OpError; use crate::gotham_state::GothamState; use crate::io::ResourceTable; use crate::ops_metrics::OpMetricsFn; @@ -94,14 +93,12 @@ pub struct OpCtx { #[doc(hidden)] pub state: Rc>, - #[doc(hidden)] - pub get_error_class_fn: GetErrorClassFn, pub(crate) decl: OpDecl, pub(crate) fast_fn_info: Option, pub(crate) metrics_fn: Option, /// If the last fast op failed, stores the error to be picked up by the slow op. - pub(crate) last_fast_error: UnsafeCell>, + pub(crate) last_fast_error: UnsafeCell>, op_driver: Rc, runtime_state: *const JsRuntimeState, @@ -116,7 +113,6 @@ impl OpCtx { decl: OpDecl, state: Rc>, runtime_state: *const JsRuntimeState, - get_error_class_fn: GetErrorClassFn, metrics_fn: Option, ) -> Self { // If we want metrics for this function, create the fastcall `CFunctionInfo` from the metrics @@ -152,7 +148,6 @@ impl OpCtx { Self { id, state, - get_error_class_fn, runtime_state, decl, op_driver, @@ -231,7 +226,7 @@ impl OpCtx { #[inline(always)] pub unsafe fn unsafely_take_last_error_for_ops_only( &self, - ) -> Option { + ) -> Option { let opt_mut = &mut *self.last_fast_error.get(); opt_mut.take() } @@ -243,7 +238,7 @@ impl OpCtx { /// /// Must only be called from op implementations. #[inline(always)] - pub unsafe fn unsafely_set_last_error_for_ops_only(&self, error: AnyError) { + pub unsafe fn unsafely_set_last_error_for_ops_only(&self, error: OpError) { let opt_mut = &mut *self.last_fast_error.get(); *opt_mut = Some(error); } diff --git a/core/ops_builtin.rs b/core/ops_builtin.rs index 023cdf455..7f11315c7 100644 --- a/core/ops_builtin.rs +++ b/core/ops_builtin.rs @@ -1,7 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::error::format_file_name; -use crate::error::type_error; -use crate::error::AnyError; +use crate::error::OpError; use crate::io::AdaptiveBufferStrategy; use crate::io::BufMutView; use crate::io::BufView; @@ -168,14 +167,14 @@ pub async fn op_void_async() {} #[allow(clippy::unused_async)] #[op2(async)] -pub async fn op_error_async() -> Result<(), AnyError> { - Err(AnyError::msg("error")) +pub async fn op_error_async() -> Result<(), OpError> { + Err(anyhow::Error::msg("error").into()) } #[allow(clippy::unused_async)] #[op2(async(deferred), fast)] -pub async fn op_error_async_deferred() -> Result<(), AnyError> { - Err(AnyError::msg("error")) +pub async fn op_error_async_deferred() -> Result<(), OpError> { + Err(anyhow::Error::msg("error").into()) } #[allow(clippy::unused_async)] @@ -187,7 +186,7 @@ pub async fn op_void_async_deferred() {} pub fn op_close( state: Rc>, #[smi] rid: ResourceId, -) -> Result<(), AnyError> { +) -> Result<(), OpError> { let resource = state.borrow_mut().resource_table.take_any(rid)?; resource.close(); Ok(()) @@ -204,7 +203,7 @@ pub fn op_try_close(state: Rc>, #[smi] rid: ResourceId) { /// Builtin utility to print to stdout/stderr #[op2(fast)] -pub fn op_print(#[string] msg: &str, is_err: bool) -> Result<(), AnyError> { +pub fn op_print(#[string] msg: &str, is_err: bool) -> Result<(), OpError> { if is_err { stderr().write_all(msg.as_bytes())?; stderr().flush().unwrap(); @@ -236,7 +235,7 @@ pub fn op_wasm_streaming_feed( state: Rc>, #[smi] rid: ResourceId, #[buffer] bytes: &[u8], -) -> Result<(), AnyError> { +) -> Result<(), OpError> { let wasm_streaming = state .borrow_mut() .resource_table @@ -252,7 +251,7 @@ pub fn op_wasm_streaming_set_url( state: &mut OpState, #[smi] rid: ResourceId, #[string] url: &str, -) -> Result<(), AnyError> { +) -> Result<(), OpError> { let wasm_streaming = state.resource_table.get::(rid)?; @@ -266,10 +265,14 @@ async fn op_read( state: Rc>, #[smi] rid: ResourceId, #[buffer] buf: JsBuffer, -) -> Result { +) -> Result { let resource = state.borrow().resource_table.get_any(rid)?; let view = BufMutView::from(buf); - resource.read_byob(view).await.map(|(n, _)| n as u32) + resource + .read_byob(view) + .await + .map(|(n, _)| n as u32) + .map_err(|err| err.into()) } #[op2(async)] @@ -277,7 +280,7 @@ async fn op_read( async fn op_read_all( state: Rc>, #[smi] rid: ResourceId, -) -> Result { +) -> Result { let resource = state.borrow().resource_table.get_any(rid)?; let (min, maybe_max) = resource.size_hint(); @@ -312,7 +315,7 @@ async fn op_write( state: Rc>, #[smi] rid: ResourceId, #[buffer] buf: JsBuffer, -) -> Result { +) -> Result { let resource = state.borrow().resource_table.get_any(rid)?; let view = BufView::from(buf); let resp = resource.write(view).await?; @@ -324,9 +327,12 @@ fn op_read_sync( state: Rc>, #[smi] rid: ResourceId, #[buffer] data: &mut [u8], -) -> Result { +) -> Result { let resource = state.borrow_mut().resource_table.get_any(rid)?; - resource.read_byob_sync(data).map(|n| n as u32) + resource + .read_byob_sync(data) + .map(|n| n as u32) + .map_err(|err| err.into()) } #[op2(fast)] @@ -334,7 +340,7 @@ fn op_write_sync( state: Rc>, #[smi] rid: ResourceId, #[buffer] data: &[u8], -) -> Result { +) -> Result { let resource = state.borrow_mut().resource_table.get_any(rid)?; let nwritten = resource.write_sync(data)?; Ok(nwritten as u32) @@ -345,7 +351,7 @@ async fn op_write_all( state: Rc>, #[smi] rid: ResourceId, #[buffer] buf: JsBuffer, -) -> Result<(), AnyError> { +) -> Result<(), OpError> { let resource = state.borrow().resource_table.get_any(rid)?; let view = BufView::from(buf); resource.write_all(view).await?; @@ -357,9 +363,11 @@ async fn op_write_type_error( state: Rc>, #[smi] rid: ResourceId, #[string] error: String, -) -> Result<(), AnyError> { +) -> Result<(), OpError> { let resource = state.borrow().resource_table.get_any(rid)?; - resource.write_error(type_error(error).into()).await?; + resource + .write_error(super::error::JsNativeError::type_error(error).into()) + .await?; Ok(()) } @@ -367,9 +375,9 @@ async fn op_write_type_error( async fn op_shutdown( state: Rc>, #[smi] rid: ResourceId, -) -> Result<(), AnyError> { +) -> Result<(), OpError> { let resource = state.borrow().resource_table.get_any(rid)?; - resource.shutdown().await + resource.shutdown().await.map_err(|err| err.into()) } #[op2] @@ -407,7 +415,7 @@ fn op_encode_binary_string(#[buffer] s: &[u8]) -> ByteString { fn op_is_terminal( state: &mut OpState, #[smi] rid: ResourceId, -) -> Result { +) -> Result { let handle = state.resource_table.get_handle(rid)?; Ok(handle.is_terminal()) } diff --git a/core/ops_builtin_v8.rs b/core/ops_builtin_v8.rs index 5e03ea54e..a545b7bcd 100644 --- a/core/ops_builtin_v8.rs +++ b/core/ops_builtin_v8.rs @@ -1,10 +1,8 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::custom_error; use crate::error::is_instance_of_error; -use crate::error::range_error; -use crate::error::type_error; -use crate::error::AnyError; use crate::error::JsError; +use crate::error::JsNativeError; +use crate::error::OpError; use crate::error::PubError; use crate::modules::script_origin; use crate::op2; @@ -195,7 +193,7 @@ pub fn op_timer_unref(scope: &mut v8::HandleScope, id: f64) { pub fn op_lazy_load_esm( scope: &mut v8::HandleScope, #[string] module_specifier: String, -) -> Result, AnyError> { +) -> Result, OpError> { let module_map_rc = JsRealm::module_map_from(scope); module_map_rc .lazy_load_esm_module(scope, &module_specifier) @@ -266,12 +264,12 @@ pub fn op_eval_context<'a>( source: v8::Local<'a, v8::Value>, #[string] specifier: String, host_defined_options: Option>, -) -> Result, AnyError> { +) -> Result, OpError> { let out = v8::Array::new(scope, 2); let state = JsRuntime::state_from(scope); let tc_scope = &mut v8::TryCatch::new(scope); let source = v8::Local::::try_from(source) - .map_err(|_| type_error("Invalid source"))?; + .map_err(|_| JsNativeError::type_error("Invalid source"))?; let specifier = resolve_url(&specifier)?; let specifier_v8 = v8::String::new(tc_scope, specifier.as_str()).unwrap(); let host_defined_options = match host_defined_options { @@ -347,7 +345,9 @@ pub fn op_eval_context<'a>( if let Some(cb) = state.eval_context_code_cache_ready_cb.as_ref() { let unbound_script = script.get_unbound_script(tc_scope); let code_cache = unbound_script.create_code_cache().ok_or_else(|| { - type_error("Unable to get code cache from unbound module script") + JsNativeError::type_error( + "Unable to get code cache from unbound module script", + ) })?; cb(specifier, code_cache_hash, &code_cache); } @@ -379,9 +379,9 @@ pub fn op_eval_context<'a>( pub fn op_encode<'a>( scope: &mut v8::HandleScope<'a>, text: v8::Local<'a, v8::Value>, -) -> Result, AnyError> { +) -> Result, OpError> { let text = v8::Local::::try_from(text) - .map_err(|_| type_error("Invalid argument"))?; + .map_err(|_| JsNativeError::type_error("Invalid argument"))?; let text_str = serde_v8::to_utf8(text, scope); let bytes = text_str.into_bytes(); let len = bytes.len(); @@ -396,7 +396,7 @@ pub fn op_encode<'a>( pub fn op_decode<'a>( scope: &mut v8::HandleScope<'a>, #[buffer] zero_copy: &[u8], -) -> Result, AnyError> { +) -> Result, OpError> { let buf = &zero_copy; // Strip BOM @@ -417,7 +417,7 @@ pub fn op_decode<'a>( // - https://github.com/v8/v8/blob/d68fb4733e39525f9ff0a9222107c02c28096e2a/include/v8.h#L3277-L3278 match v8::String::new_from_utf8(scope, buf, v8::NewStringType::Normal) { Some(text) => Ok(text), - None => Err(range_error("string too long").into()), + None => Err(JsNativeError::range_error("string too long").into()), } } @@ -444,7 +444,7 @@ impl<'a> v8::ValueSerializerImpl for SerializeDeserialize<'a> { return; }; } - let error = v8::Exception::type_error(scope, message); + let error = v8::Exception::CustomError::type_error(scope, message); scope.throw_exception(error); } @@ -597,26 +597,27 @@ pub fn op_serialize( transferred_array_buffers: Option>, for_storage: bool, error_callback: Option>, -) -> Result, AnyError> { +) -> Result, OpError> { let error_callback = match error_callback { Some(cb) => Some( v8::Local::::try_from(cb) - .map_err(|_| type_error("Invalid error callback"))?, + .map_err(|_| JsNativeError::type_error("Invalid error callback"))?, ), None => None, }; let host_objects = match host_objects { Some(value) => Some( v8::Local::::try_from(value) - .map_err(|_| type_error("hostObjects not an array"))?, + .map_err(|_| JsNativeError::type_error("hostObjects not an array"))?, ), None => None, }; let transferred_array_buffers = match transferred_array_buffers { - Some(value) => Some( - v8::Local::::try_from(value) - .map_err(|_| type_error("transferredArrayBuffers not an array"))?, - ), + Some(value) => { + Some(v8::Local::::try_from(value).map_err(|_| { + JsNativeError::type_error("transferredArrayBuffers not an array") + })?) + } None => None, }; @@ -640,20 +641,24 @@ pub fn op_serialize( let i = v8::Number::new(scope, index as f64).into(); let buf = transferred_array_buffers.get(scope, i).unwrap(); let buf = v8::Local::::try_from(buf).map_err(|_| { - type_error("item in transferredArrayBuffers not an ArrayBuffer") + JsNativeError::type_error( + "item in transferredArrayBuffers not an ArrayBuffer", + ) })?; if let Some(shared_array_buffer_store) = &state.shared_array_buffer_store { if !buf.is_detachable() { return Err( - type_error("item in transferredArrayBuffers is not transferable") - .into(), + JsNativeError::type_error( + "item in transferredArrayBuffers is not transferable", + ) + .into(), ); } if buf.was_detached() { return Err( - custom_error( + JsNativeError::new( "DOMExceptionOperationError", format!("ArrayBuffer at index {index} is already detached"), ) @@ -681,7 +686,7 @@ pub fn op_serialize( let vector = value_serializer.release(); Ok(vector) } else { - Err(type_error("Failed to serialize response").into()) + Err(JsNativeError::type_error("Failed to serialize response").into()) } } @@ -692,19 +697,20 @@ pub fn op_deserialize<'a>( host_objects: Option>, transferred_array_buffers: Option>, for_storage: bool, -) -> Result, AnyError> { +) -> Result, OpError> { let host_objects = match host_objects { Some(value) => Some( v8::Local::::try_from(value) - .map_err(|_| type_error("hostObjects not an array"))?, + .map_err(|_| JsNativeError::type_error("hostObjects not an array"))?, ), None => None, }; let transferred_array_buffers = match transferred_array_buffers { - Some(value) => Some( - v8::Local::::try_from(value) - .map_err(|_| type_error("transferredArrayBuffers not an array"))?, - ), + Some(value) => { + Some(v8::Local::::try_from(value).map_err(|_| { + JsNativeError::type_error("transferredArrayBuffers not an array") + })?) + } None => None, }; @@ -720,7 +726,9 @@ pub fn op_deserialize<'a>( .read_header(scope.get_current_context()) .unwrap_or_default(); if !parsed_header { - return Err(range_error("could not deserialize value").into()); + return Err( + JsNativeError::range_error("could not deserialize value").into(), + ); } if let Some(transferred_array_buffers) = transferred_array_buffers { @@ -733,7 +741,10 @@ pub fn op_deserialize<'a>( Some(id) => id as u32, None => { return Err( - type_error("item in transferredArrayBuffers not number").into(), + JsNativeError::type_error( + "item in transferredArrayBuffers not number", + ) + .into(), ) } }; @@ -743,7 +754,7 @@ pub fn op_deserialize<'a>( value_deserializer.transfer_array_buffer(id, array_buffer); transferred_array_buffers.set(scope, i, array_buffer.into()); } else { - return Err(type_error( + return Err(JsNativeError::type_error( "transferred array buffer not present in shared_array_buffer_store", ).into()); } @@ -754,7 +765,9 @@ pub fn op_deserialize<'a>( let value = value_deserializer.read_value(scope.get_current_context()); match value { Some(deserialized) => Ok(deserialized), - None => Err(range_error("could not deserialize value").into()), + None => { + Err(JsNativeError::range_error("could not deserialize value").into()) + } } } @@ -790,16 +803,16 @@ pub fn op_set_promise_hooks( before_hook: v8::Local, after_hook: v8::Local, resolve_hook: v8::Local, -) -> Result<(), AnyError> { +) -> Result<(), OpError> { let v8_fns = [init_hook, before_hook, after_hook, resolve_hook] .into_iter() .enumerate() .filter(|(_, hook)| !hook.is_undefined()) .try_fold([None; 4], |mut v8_fns, (i, hook)| { let v8_fn = v8::Local::::try_from(hook) - .map_err(|err| type_error(err.to_string()))?; + .map_err(|err| JsNativeError::type_error(err.to_string()))?; v8_fns[i] = Some(v8_fn); - Ok::<_, AnyError>(v8_fns) + Ok::<_, OpError>(v8_fns) })?; scope.set_promise_hooks( @@ -942,7 +955,12 @@ pub fn op_set_wasm_streaming_callback( // borrow or move any local variables. Therefore, we're storing the JS // callback in a JsRuntimeState slot. if context_state_rc.js_wasm_streaming_cb.borrow().is_some() { - return Err(type_error("op_set_wasm_streaming_callback already called")); + return Err( + JsNativeError::type_error( + "op_set_wasm_streaming_callback already called", + ) + .into(), + ); } *context_state_rc.js_wasm_streaming_cb.borrow_mut() = Some(Rc::new(cb)); @@ -981,7 +999,7 @@ pub fn op_abort_wasm_streaming( state: Rc>, rid: u32, error: v8::Local, -) -> Result<(), AnyError> { +) -> Result<(), OpError> { // NOTE: v8::WasmStreaming::abort can't be called while `state` is borrowed; let wasm_streaming = state .borrow_mut() diff --git a/core/runtime/jsrealm.rs b/core/runtime/jsrealm.rs index c143f2df7..c356b3baf 100644 --- a/core/runtime/jsrealm.rs +++ b/core/runtime/jsrealm.rs @@ -17,7 +17,6 @@ use crate::ops::OpCtx; use crate::stats::RuntimeActivityTraces; use crate::tasks::V8TaskSpawnerFactory; use crate::web_timeout::WebTimers; -use crate::GetErrorClassFn; use futures::stream::StreamExt; use std::cell::Cell; use std::cell::RefCell; @@ -70,7 +69,6 @@ pub struct ContextState { pub(crate) isolate: Option<*mut v8::OwnedIsolate>, pub(crate) exception_state: Rc, pub(crate) has_next_tick_scheduled: Cell, - pub(crate) get_error_class_fn: GetErrorClassFn, pub(crate) external_ops_tracker: ExternalOpsTracker, } @@ -78,13 +76,11 @@ impl ContextState { pub(crate) fn new( op_driver: Rc, isolate_ptr: *mut v8::OwnedIsolate, - get_error_class_fn: GetErrorClassFn, op_ctxs: Box<[OpCtx]>, external_ops_tracker: ExternalOpsTracker, ) -> Self { Self { isolate: Some(isolate_ptr), - get_error_class_fn, exception_state: Default::default(), has_next_tick_scheduled: Default::default(), js_event_loop_tick_cb: Default::default(), diff --git a/core/runtime/jsruntime.rs b/core/runtime/jsruntime.rs index dda781b28..9a0ab01a5 100644 --- a/core/runtime/jsruntime.rs +++ b/core/runtime/jsruntime.rs @@ -13,9 +13,9 @@ use super::SnapshotStoreDataStore; use super::SnapshottedData; use crate::ascii_str; use crate::ascii_str_include; -use crate::error::GetErrorClassFn; +use crate::error::exception_to_err_result; use crate::error::JsError; -use crate::error::{exception_to_err_result, PubError}; +use crate::error::PubError; use crate::extension_set; use crate::extension_set::LoadedSources; use crate::extensions::GlobalObjectMiddlewareFn; @@ -439,10 +439,6 @@ pub struct JsRuntimeState { #[derive(Default)] pub struct RuntimeOptions { - /// Allows to map error type to a string "class" used to represent - /// error in JavaScript. - pub get_error_class_fn: Option, - /// Implementation of `ModuleLoader` which will be /// called when V8 requests to load ES modules in the main realm. /// @@ -852,7 +848,6 @@ impl JsRuntime { let op_driver = Rc::new(OpDriverImpl::default()); let op_metrics_factory_fn = options.op_metrics_factory_fn.take(); - let get_error_class_fn = options.get_error_class_fn.unwrap_or(&|_| "Error"); let mut op_ctxs = extension_set::create_op_ctxs( op_decls, @@ -860,7 +855,6 @@ impl JsRuntime { op_driver.clone(), op_state.clone(), state_rc.clone(), - get_error_class_fn, ); // ...ops are now almost fully set up; let's create a V8 isolate... @@ -956,7 +950,6 @@ impl JsRuntime { let context_state = Rc::new(ContextState::new( op_driver.clone(), isolate_ptr, - options.get_error_class_fn.unwrap_or(&|_| "Error"), op_ctxs, op_state.borrow().external_ops_tracker.clone(), )); @@ -2510,7 +2503,7 @@ impl JsRuntime { break; }; - let res = res.unwrap(scope, context_state.get_error_class_fn); + let res = res.unwrap(scope); { let op_ctx = &context_state.op_ctxs[op_id as usize]; diff --git a/core/runtime/op_driver/futures_unordered_driver.rs b/core/runtime/op_driver/futures_unordered_driver.rs index 4f7aa20f9..a5d3d5bb4 100644 --- a/core/runtime/op_driver/futures_unordered_driver.rs +++ b/core/runtime/op_driver/futures_unordered_driver.rs @@ -123,7 +123,7 @@ impl FuturesUnorderedDriver { impl OpDriver for FuturesUnorderedDriver { fn submit_op_fallible< R: 'static, - E: Into + 'static, + E: Into + 'static, const LAZY: bool, const DEFERRED: bool, >( diff --git a/core/runtime/op_driver/mod.rs b/core/runtime/op_driver/mod.rs index d8ce54233..16c3c89a3 100644 --- a/core/runtime/op_driver/mod.rs +++ b/core/runtime/op_driver/mod.rs @@ -2,7 +2,6 @@ use crate::OpId; use crate::PromiseId; use bit_set::BitSet; -use deno_core::error::AnyError; use std::future::Future; use std::task::Context; use std::task::Poll; @@ -15,6 +14,7 @@ mod op_results; #[allow(unused)] pub use futures_unordered_driver::FuturesUnorderedDriver; +pub use self::op_results::OpError; pub use self::op_results::OpMappingContext; pub use self::op_results::OpResult; use self::op_results::PendingOpInfo; @@ -84,7 +84,7 @@ pub(crate) trait OpDriver: /// might return an error (`Result`). fn submit_op_fallible< R: 'static, - E: Into + 'static, + E: Into + 'static, const LAZY: bool, const DEFERRED: bool, >( @@ -98,7 +98,7 @@ pub(crate) trait OpDriver: /// Submits an operation that is expected to complete successfully without errors. #[inline(always)] #[allow(clippy::too_many_arguments)] - fn submit_op_fallible_scheduling + 'static>( + fn submit_op_fallible_scheduling + 'static>( &self, scheduling: OpScheduling, op_id: OpId, @@ -144,8 +144,6 @@ pub(crate) trait OpDriver: #[cfg(test)] mod tests { - use crate::GetErrorClassFn; - use super::op_results::*; use super::*; use bit_set::BitSet; @@ -160,8 +158,7 @@ mod tests { fn map_error( _context: &mut Self::Context, - err: AnyError, - _get_error_class_fn: GetErrorClassFn, + err: OpError, ) -> UnmappedResult<'s, Self> { Ok(format!("{err:?}")) } @@ -233,11 +230,12 @@ mod tests { let (promise_id, op_id, result) = poll_fn(|cx| driver.poll_ready(cx)).await; assert!(bitset.insert(promise_id as usize)); assert_eq!(1234, op_id); - assert_eq!(expected, &(result.unwrap(&mut (), &|_| "Error").unwrap())); + assert_eq!(expected, &(result.unwrap(&mut ()).unwrap())); } #[rstest] - #[case::futures_unordered(FuturesUnorderedDriver::::default())] + #[case::futures_unordered(FuturesUnorderedDriver::::default() + )] fn test_driver>( #[case] driver: D, #[values(2, 16)] count: usize, @@ -267,7 +265,8 @@ mod tests { } #[rstest] - #[case::futures_unordered(FuturesUnorderedDriver::::default())] + #[case::futures_unordered(FuturesUnorderedDriver::::default() + )] fn test_driver_yield>( #[case] driver: D, #[values(2, 16)] count: usize, @@ -304,7 +303,8 @@ mod tests { } #[rstest] - #[case::futures_unordered(FuturesUnorderedDriver::::default())] + #[case::futures_unordered(FuturesUnorderedDriver::::default() + )] fn test_driver_large>( #[case] driver: D, #[values(2, 16)] count: usize, @@ -343,7 +343,8 @@ mod tests { #[cfg(not(miri))] // needs I/O #[rstest] - #[case::futures_unordered(FuturesUnorderedDriver::::default())] + #[case::futures_unordered(FuturesUnorderedDriver::::default() + )] fn test_driver_io>( #[case] driver: D, #[values(2, 16)] count: usize, diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index 999e37e20..c128900e2 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -1,10 +1,10 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use super::erased_future::TypeErased; use super::future_arena::FutureContextMapper; -use crate::GetErrorClassFn; +use crate::error::JsErrorClass; use crate::OpId; use crate::PromiseId; -use deno_core::error::AnyError; +use serde::ser::SerializeStruct; use serde::Serialize; const MAX_RESULT_SIZE: usize = 32; @@ -25,8 +25,7 @@ pub trait OpMappingContextLifetime<'s> { fn map_error( context: &mut Self::Context, - err: AnyError, - get_error_class_fn: GetErrorClassFn, + err: OpError, ) -> UnmappedResult<'s, Self>; fn map_mapping_error( context: &mut Self::Context, @@ -67,17 +66,16 @@ impl<'s> OpMappingContextLifetime<'s> for V8OpMappingContext { #[inline(always)] fn map_error( scope: &mut v8::HandleScope<'s>, - err: AnyError, - get_error_class_fn: GetErrorClassFn, + err: OpError, ) -> UnmappedResult<'s, Self> { - serde_v8::to_v8(scope, OpError::new(get_error_class_fn, err)) + serde_v8::to_v8(scope, err) } fn map_mapping_error( scope: &mut v8::HandleScope<'s>, err: Self::MappingError, ) -> v8::Local<'s, v8::Value> { - serde_v8::to_v8(scope, OpError::new(&|_| "TypeError", err.into())).unwrap() + serde_v8::to_v8(scope, OpError::from(err)).unwrap() } } @@ -106,7 +104,7 @@ pub struct PendingOp(pub PendingOpInfo, pub OpResult); impl PendingOp { #[inline(always)] - pub fn new + 'static>( + pub fn new + 'static>( info: PendingOpInfo, rv_map: C::MappingFn, result: Result, @@ -149,7 +147,7 @@ impl Clone } } -impl + 'static> +impl + 'static> FutureContextMapper, PendingOpInfo, Result> for PendingOpMappingInfo { @@ -225,7 +223,7 @@ impl ValueLargeFn for ValueLarge { pub enum OpResult { /// Errors. - Err(AnyError), + Err(OpError), /// For small ops, we include them in an erased type container. Value(OpValue), /// For ops that return "large" results (> MAX_RESULT_SIZE bytes) we just box a function @@ -245,10 +243,9 @@ impl OpResult { pub fn unwrap<'a>( self, context: &mut >::Context, - get_error_class_fn: GetErrorClassFn, ) -> MappedResult<'a, C> { let (success, res) = match self { - Self::Err(err) => (false, C::map_error(context, err, get_error_class_fn)), + Self::Err(err) => (false, C::map_error(context, err)), Self::Value(f) => (true, (f.map_fn)(&(), context, f.rv_map, f.value)), Self::ValueLarge(f) => (true, f.unwrap(context)), }; @@ -262,21 +259,42 @@ impl OpResult { } } -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] +#[derive(Debug)] pub struct OpError { - #[serde(rename = "$err_class_name")] - class_name: &'static str, - message: String, - code: Option<&'static str>, + error: Box, + error_code: Option<&'static str>, } -impl OpError { - pub fn new(get_class: GetErrorClassFn, err: AnyError) -> Self { +impl From for OpError { + fn from(err: T) -> Self { Self { - class_name: (get_class)(&err), - message: format!("{err:#}"), - code: crate::error_codes::get_error_code(&err), + error_code: crate::error_codes::get_error_code(&err), + error: Box::new(err), } } } + +impl From for OpError { + fn from(err: anyhow::Error) -> Self { + match err.downcast::() { + Ok(err) => err.into(), + Err(_) => todo!(), + } + } +} + +impl Serialize for OpError { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + let class_name = self.error.get_class(); + let message = self.error.get_message(); + + let mut serde_state = serializer.serialize_struct("OpError", 3)?; + serde_state.serialize_field("$err_class_name", class_name)?; + serde_state.serialize_field("message", &message)?; + serde_state.serialize_field("code", &self.error_code)?; + serde_state.end() + } +} diff --git a/core/runtime/ops.rs b/core/runtime/ops.rs index e07144f52..a919f60c2 100644 --- a/core/runtime/ops.rs +++ b/core/runtime/ops.rs @@ -2,7 +2,6 @@ use super::op_driver::OpDriver; use super::op_driver::OpScheduling; use super::op_driver::V8RetValMapper; -use crate::error::AnyError; use crate::ops::*; use futures::future::Future; use serde::Deserialize; @@ -48,7 +47,10 @@ pub fn map_async_op_infallible( } #[inline(always)] -pub fn map_async_op_fallible + 'static>( +pub fn map_async_op_fallible< + R: 'static, + E: Into + 'static, +>( ctx: &OpCtx, lazy: bool, deferred: bool, @@ -516,9 +518,9 @@ pub fn to_v8_slice_any( mod tests { use crate::convert::Number; use crate::convert::Smi; - use crate::error::generic_error; - use crate::error::AnyError; use crate::error::JsError; + use crate::error::JsNativeError; + use crate::error::OpError; use crate::external; use crate::external::ExternalPointer; use crate::op2; @@ -664,13 +666,18 @@ mod tests { } /// Run a test for a single op. - fn run_test2(repeat: usize, op: &str, test: &str) -> Result<(), AnyError> { + fn run_test2( + repeat: usize, + op: &str, + test: &str, + ) -> Result<(), anyhow::Error> { let mut runtime = JsRuntime::new(RuntimeOptions { extensions: vec![testing::init_ops_and_esm()], ..Default::default() }); - let err_mapper = - |err| generic_error(format!("{op} test failed ({test}): {err:?}")); + let err_mapper = |err| { + JsNativeError::generic(format!("{op} test failed ({test}): {err:?}")) + }; runtime .execute_script( "", @@ -704,7 +711,7 @@ mod tests { ), )?; if FAIL.with(|b| b.get()) { - Err(generic_error(format!("{op} test failed ({test})"))) + Err(JsNativeError::generic(format!("{op} test failed ({test})")).into()) } else { Ok(()) } @@ -715,13 +722,14 @@ mod tests { repeat: usize, op: &str, test: &str, - ) -> Result<(), AnyError> { + ) -> Result<(), anyhow::Error> { let mut runtime = JsRuntime::new(RuntimeOptions { extensions: vec![testing::init_ops_and_esm()], ..Default::default() }); - let err_mapper = - |err| generic_error(format!("{op} test failed ({test}): {err:?}")); + let err_mapper = |err| { + JsNativeError::generic(format!("{op} test failed ({test}): {err:?}")) + }; runtime .execute_script( "", @@ -759,7 +767,7 @@ mod tests { runtime.run_event_loop(Default::default()).await?; if FAIL.with(|b| b.get()) { - Err(generic_error(format!("{op} test failed ({test})")).into()) + Err(JsNativeError::generic(format!("{op} test failed ({test})")).into()) } else { Ok(()) } @@ -861,26 +869,26 @@ mod tests { } #[op2(fast)] - pub fn op_test_result_void_switch() -> Result<(), AnyError> { + pub fn op_test_result_void_switch() -> Result<(), OpError> { let count = RETURN_COUNT.with(|count| { let new = count.get() + 1; count.set(new); new }); if count > 5000 { - Err(generic_error("failed!!!")) + Err(JsNativeError::generic("failed!!!").into()) } else { Ok(()) } } #[op2(fast)] - pub fn op_test_result_void_err() -> Result<(), AnyError> { - Err(generic_error("failed!!!")) + pub fn op_test_result_void_err() -> Result<(), OpError> { + Err(JsNativeError::generic("failed!!!").into()) } #[op2(fast)] - pub fn op_test_result_void_ok() -> Result<(), AnyError> { + pub fn op_test_result_void_ok() -> Result<(), OpError> { Ok(()) } @@ -917,12 +925,12 @@ mod tests { } #[op2(fast)] - pub fn op_test_result_primitive_err() -> Result { - Err(generic_error("failed!!!")) + pub fn op_test_result_primitive_err() -> Result { + Err(JsNativeError::generic("failed!!!").into()) } #[op2(fast)] - pub fn op_test_result_primitive_ok() -> Result { + pub fn op_test_result_primitive_ok() -> Result { Ok(123) } @@ -948,11 +956,11 @@ mod tests { } #[op2(fast)] - pub fn op_test_bool_result(b: bool) -> Result { + pub fn op_test_bool_result(b: bool) -> Result { if b { Ok(true) } else { - Err(generic_error("false!!!")) + Err(JsNativeError::generic("false!!!").into()) } } @@ -982,12 +990,12 @@ mod tests { } #[op2(fast)] - pub fn op_test_float_result(a: f32, b: f64) -> Result { + pub fn op_test_float_result(a: f32, b: f64) -> Result { let a = a as f64; if a + b >= 0. { Ok(a + b) } else { - Err(generic_error("negative!!!")) + Err(JsNativeError::generic("negative!!!").into()) } } @@ -1037,12 +1045,12 @@ mod tests { &format!("assert(op_test_bigint_i64({}n) == {}n)", i64::MAX, i64::MAX), )?; run_test2( - JIT_ITERATIONS, + JIT_ITERATIONS, "op_test_bigint_i64_as_number", "assert(op_test_bigint_i64_as_number(Number.MAX_SAFE_INTEGER) == Number.MAX_SAFE_INTEGER)", )?; run_test2( - JIT_ITERATIONS, + JIT_ITERATIONS, "op_test_bigint_i64_as_number", "assert(op_test_bigint_i64_as_number(Number.MIN_SAFE_INTEGER) == Number.MIN_SAFE_INTEGER)", )?; @@ -1151,7 +1159,7 @@ mod tests { run_test2( 10, "op_test_string_roundtrip_char_onebyte", - "try { op_test_string_roundtrip_char_onebyte('\\u1000'); assert(false); } catch (e) {}" + "try { op_test_string_roundtrip_char_onebyte('\\u1000'); assert(false); } catch (e) {}", )?; Ok(()) @@ -1295,11 +1303,11 @@ mod tests { pub fn op_test_v8_type_handle_scope_result<'s>( scope: &mut v8::HandleScope<'s>, o: &v8::Object, - ) -> Result, AnyError> { + ) -> Result, OpError> { let key = v8::String::new(scope, "key").unwrap().into(); o.get(scope, key) .filter(|v| !v.is_null_or_undefined()) - .ok_or(generic_error("error!!!")) + .ok_or(JsNativeError::generic("error!!!").into()) } #[tokio::test] @@ -1442,12 +1450,12 @@ mod tests { #[tokio::test] pub async fn test_op_state() -> Result<(), Box> { run_test2( - JIT_ITERATIONS, + JIT_ITERATIONS, "op_state_rc", "if (__index__ == 0) { op_state_rc(__index__) } else { assert(op_state_rc(__index__) == __index__ - 1) }", )?; run_test2( - JIT_ITERATIONS, + JIT_ITERATIONS, "op_state_mut_attr", "if (__index__ == 0) { op_state_mut_attr(__index__) } else { assert(op_state_mut_attr(__index__) == __index__ - 1) }", )?; @@ -1717,7 +1725,7 @@ mod tests { "assert(op_buffer_any(new Uint32Array([1,2,3,4,0x01010101])) == 14);", )?; run_test2( - JIT_ITERATIONS, + JIT_ITERATIONS, "op_buffer_any", "assert(op_buffer_any(new DataView(new Uint8Array([1,2,3,4]).buffer)) == 10);", )?; @@ -2036,7 +2044,7 @@ mod tests { #[tokio::test] pub async fn test_typed_external() -> Result<(), Box> { run_test2( - JIT_ITERATIONS, + JIT_ITERATIONS, "op_typed_external, op_typed_external_process, op_typed_external_take", "let external = op_typed_external(); op_typed_external_process(external); assert(op_typed_external_take(external) == 43);", )?; @@ -2183,11 +2191,11 @@ mod tests { ) .await?; run_async_test( - JIT_SLOW_ITERATIONS, + JIT_SLOW_ITERATIONS, "op_async_deferred_error", "try { await op_async_deferred_error(); assert(false) } catch (e) {{ assertErrorContains(e, 'whoops') }}", ) - .await?; + .await?; Ok(()) } @@ -2210,11 +2218,11 @@ mod tests { ) .await?; run_async_test( - JIT_SLOW_ITERATIONS, + JIT_SLOW_ITERATIONS, "op_async_lazy_error", "try { await op_async_lazy_error(); assert(false) } catch (e) {{ assertErrorContains(e, 'whoops') }}", ) - .await?; + .await?; Ok(()) } @@ -2225,15 +2233,15 @@ mod tests { mode: u8, ) -> Result>, Error> { if mode == 0 { - return Err(generic_error("early exit")); + return Err(JsNativeError::generic("early exit").into()); } Ok(async move { if mode == 1 { - return Err(generic_error("early async exit")); + return Err(JsNativeError::generic("early async exit").into()); } tokio::time::sleep(Duration::from_millis(500)).await; if mode == 2 { - return Err(generic_error("late async exit")); + return Err(JsNativeError::generic("late async exit").into()); } Ok(()) }) @@ -2252,7 +2260,7 @@ mod tests { "op_async_result_impl", &format!("try {{ await op_async_result_impl({n}); assert(false) }} catch (e) {{ assertErrorContains(e, '{msg}') }}"), ) - .await?; + .await?; } run_async_test(5, "op_async_result_impl", "await op_async_result_impl(3);") .await?; @@ -2307,13 +2315,13 @@ mod tests { "op_async_buffer", "let output = await op_async_buffer(new Uint8Array([1,2,3])); assert(output.length == 3); assert(output[0] == 1);", ) - .await?; + .await?; run_async_test( 2, "op_async_buffer_vec", "let output = await op_async_buffer_vec(new Uint8Array([3,2,1])); assert(output.length == 3); assert(output[0] == 1);", ) - .await?; + .await?; run_async_test( 2, "op_async_buffer_impl", @@ -2347,7 +2355,7 @@ mod tests { #[serde] pub async fn op_async_serde_option_v8( #[serde] mut serde: Serde, - ) -> Result, AnyError> { + ) -> Result, OpError> { serde.s += "!"; Ok(Some(serde)) } diff --git a/core/runtime/tests/error.rs b/core/runtime/tests/error.rs index 82ae74f6b..b5cd32e7b 100644 --- a/core/runtime/tests/error.rs +++ b/core/runtime/tests/error.rs @@ -22,7 +22,6 @@ async fn test_error_builder() { deno_core::extension!(test_ext, ops = [op_err]); let mut runtime = JsRuntime::new(RuntimeOptions { extensions: vec![test_ext::init_ops()], - get_error_class_fn: Some(&get_error_class_name), ..Default::default() }); poll_fn(move |cx| { diff --git a/core/runtime/tests/misc.rs b/core/runtime/tests/misc.rs index 4bc0c9443..996dc6d74 100644 --- a/core/runtime/tests/misc.rs +++ b/core/runtime/tests/misc.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::AnyError; use crate::error::JsError; +use crate::error::OpError; use crate::modules::StaticModuleLoader; use crate::runtime::tests::setup; use crate::runtime::tests::Mode; @@ -150,7 +150,10 @@ async fn test_wakers_for_async_ops() { "Promise.reject(new Error('fail'))", Err("Error: fail\n at a.js:1:16") )] -#[case("new Promise(resolve => {})", Err("Promise resolution is still pending but the event loop has already resolved."))] +#[case("new Promise(resolve => {})", + Err("Promise resolution is still pending but the event loop has already resolved." + ) +)] #[tokio::test] async fn test_resolve_promise( #[case] script: &'static str, @@ -225,7 +228,9 @@ async fn test_resolve_promise( "() => { Deno.core.reportUnhandledException(new Error('fail')); return 1; }", Ok(Some(1)) )] -#[case("call", "() => { Deno.core.reportUnhandledException(new Error('fail')); willNotCall(); }", Err("Uncaught Error: fail"))] +#[case("call", "() => { Deno.core.reportUnhandledException(new Error('fail')); willNotCall(); }", + Err("Uncaught Error: fail") +)] #[tokio::test] async fn test_resolve_value( #[case] runner: &'static str, @@ -291,7 +296,7 @@ fn terminate_execution_webassembly() { // Run an infinite loop in WebAssembly code, which should be terminated. let promise = runtime.execute_script("infinite_wasm_loop.js", - r#" + r#" (async () => { const wasmCode = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, @@ -374,7 +379,7 @@ async fn wasm_streaming_op_invocation_in_import() { // Run an infinite loop in WebAssembly code, which should be terminated. runtime.execute_script("setup.js", - r#" + r#" Deno.core.setWasmStreamingCallback((source, rid) => { Deno.core.ops.op_wasm_streaming_set_url(rid, "file:///foo.wasm"); Deno.core.ops.op_wasm_streaming_feed(rid, source); @@ -383,7 +388,7 @@ async fn wasm_streaming_op_invocation_in_import() { "#).unwrap(); let promise = runtime.execute_script("main.js", - r#" + r#" // (module (import "env" "data" (global i64))) const bytes = new Uint8Array([0,97,115,109,1,0,0,0,2,13,1,3,101,110,118,4,100,97,116,97,3,126,0,0,8,4,110,97,109,101,2,1,0]); WebAssembly.instantiateStreaming(bytes, { @@ -694,13 +699,13 @@ fn test_has_tick_scheduled() { static NEXT_TICK: AtomicUsize = AtomicUsize::new(0); #[op2(fast)] - fn op_macrotask() -> Result<(), AnyError> { + fn op_macrotask() -> Result<(), OpError> { MACROTASK.fetch_add(1, Ordering::Relaxed); Ok(()) } #[op2(fast)] - fn op_next_tick() -> Result<(), AnyError> { + fn op_next_tick() -> Result<(), OpError> { NEXT_TICK.fetch_add(1, Ordering::Relaxed); Ok(()) } @@ -851,7 +856,7 @@ async fn test_promise_rejection_handler_generic( } } "# - .replace("__CASE__", case); + .replace("__CASE__", case); let future = if module { let id = runtime @@ -964,7 +969,7 @@ async fn test_dynamic_import_module_error_stack() { #[op2(async)] async fn op_async_error() -> Result<(), Error> { tokio::time::sleep(std::time::Duration::from_millis(1)).await; - Err(crate::error::type_error("foo")) + Err(crate::error::JsNativeError::type_error("foo")) } deno_core::extension!(test_ext, ops = [op_async_error]); let loader = StaticModuleLoader::new([ diff --git a/core/runtime/tests/mod.rs b/core/runtime/tests/mod.rs index 1d3103689..56bb8169f 100644 --- a/core/runtime/tests/mod.rs +++ b/core/runtime/tests/mod.rs @@ -1,5 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::AnyError; +use crate::error::OpError; use crate::op2; use crate::CrossIsolateStore; use crate::JsRuntime; @@ -36,7 +36,7 @@ async fn op_test( rc_op_state: Rc>, control: u8, #[buffer] buf: Option, -) -> Result { +) -> Result { let op_state_ = rc_op_state.borrow(); let test_state = op_state_.borrow::(); test_state.dispatch_count.fetch_add(1, Ordering::Relaxed); @@ -80,9 +80,6 @@ fn setup(mode: Mode) -> (JsRuntime, Arc) { ); let mut runtime = JsRuntime::new(RuntimeOptions { extensions: vec![test_ext::init_ops(mode, dispatch_count.clone())], - get_error_class_fn: Some(&|error| { - crate::error::get_custom_error_class(error).unwrap() - }), shared_array_buffer_store: Some(CrossIsolateStore::default()), ..Default::default() }); diff --git a/core/runtime/tests/ops.rs b/core/runtime/tests/ops.rs index f0c9be77e..e827ab97e 100644 --- a/core/runtime/tests/ops.rs +++ b/core/runtime/tests/ops.rs @@ -2,13 +2,13 @@ #![allow(clippy::print_stdout, clippy::print_stderr, clippy::unused_async)] -use crate::error::AnyError; +use crate::error::{OpError}; use crate::extensions::OpDecl; use crate::modules::StaticModuleLoader; use crate::runtime::tests::setup; use crate::runtime::tests::Mode; use crate::*; -use anyhow::bail; +use anyhow::{anyhow}; use anyhow::Error; use futures::Future; use pretty_assertions::assert_eq; @@ -535,9 +535,9 @@ pub async fn op_async() { #[op2(async)] #[allow(unreachable_code)] -pub fn op_async_impl_future_error() -> Result, AnyError> +pub fn op_async_impl_future_error() -> Result, OpError> { - bail!("dead"); + return Err(anyhow!("dead").into()); Ok(async {}) } @@ -548,16 +548,16 @@ pub async fn op_async_yield() { } #[op2(async)] -pub async fn op_async_yield_error() -> Result<(), AnyError> { +pub async fn op_async_yield_error() -> Result<(), OpError> { tokio::task::yield_now().await; println!("op_async_yield_error!"); - bail!("dead"); + Err(anyhow!("dead").into()) } #[op2(async)] -pub async fn op_async_error() -> Result<(), AnyError> { +pub async fn op_async_error() -> Result<(), OpError> { println!("op_async_error!"); - bail!("dead"); + Err(anyhow!("dead").into()) } #[op2(async(deferred), fast)] @@ -576,8 +576,8 @@ pub fn op_sync() { } #[op2(fast)] -pub fn op_sync_error() -> Result<(), AnyError> { - bail!("Always fails"); +pub fn op_sync_error() -> Result<(), OpError> { + Err(anyhow::anyhow!("Always fails").into()) } #[op2(fast)] diff --git a/dcore/src/inspector_server.rs b/dcore/src/inspector_server.rs index 3c7cb2eb3..5ae88911c 100644 --- a/dcore/src/inspector_server.rs +++ b/dcore/src/inspector_server.rs @@ -3,7 +3,6 @@ // Alias for the future `!` type. use core::convert::Infallible as Never; use deno_core::anyhow::Context; -use deno_core::error::AnyError; use deno_core::futures::channel::mpsc; use deno_core::futures::channel::mpsc::UnboundedReceiver; use deno_core::futures::channel::mpsc::UnboundedSender; @@ -45,7 +44,10 @@ pub struct InspectorServer { } impl InspectorServer { - pub fn new(host: SocketAddr, name: &'static str) -> Result { + pub fn new( + host: SocketAddr, + name: &'static str, + ) -> Result { let (register_inspector_tx, register_inspector_rx) = mpsc::unbounded::(); @@ -477,9 +479,9 @@ impl InspectorInfo { fn get_frontend_url(&self, host: &str) -> String { format!( - "devtools://devtools/bundled/js_app.html?ws={}/ws/{}&experiments=true&v8only=true", - host, &self.uuid - ) + "devtools://devtools/bundled/js_app.html?ws={}/ws/{}&experiments=true&v8only=true", + host, &self.uuid + ) } fn get_title(&self) -> String { diff --git a/ops/op2/dispatch_slow.rs b/ops/op2/dispatch_slow.rs index 31bdc0c3f..0c0ec5b3b 100644 --- a/ops/op2/dispatch_slow.rs +++ b/ops/op2/dispatch_slow.rs @@ -69,7 +69,7 @@ pub(crate) fn generate_dispatch_slow( generator_state.needs_opctx = true; let throw_exception = throw_exception(generator_state); // If the fast op returned an error, we must throw it rather than doing work. - output.extend(quote!{ + output.extend(quote! { // FASTCALL FALLBACK: This is where we pick up the errors for the slow-call error pickup // path. There is no code running between this and the other FASTCALL FALLBACK comment, // except some V8 code required to perform the fallback process. This is why the below call is safe. @@ -1005,14 +1005,13 @@ pub(crate) fn throw_exception( with_fn_args(generator_state) }; - gs_quote!(generator_state(scope, opctx) => { + gs_quote!(generator_state(scope) => { #maybe_scope #maybe_args #maybe_opctx let err = err.into(); let exception = deno_core::error::to_v8_error( &mut #scope, - #opctx.get_error_class_fn, &err, ); #scope.throw_exception(exception); diff --git a/ops/op2/signature.rs b/ops/op2/signature.rs index aa01f4b68..6aeb9e744 100644 --- a/ops/op2/signature.rs +++ b/ops/op2/signature.rs @@ -818,19 +818,25 @@ pub enum SignatureError { RetError(#[from] RetError), #[error("Only one lifetime is permitted")] TooManyLifetimes, - #[error("Generic '{0}' must have one and only bound (either and 'where T: Trait', or )")] + #[error("Generic '{0}' must have one and only bound (either and 'where T: Trait', or )" + )] GenericBoundCardinality(String), - #[error("Where clause predicate '{0}' (eg: where T: Trait) must appear in generics list (eg: )")] + #[error("Where clause predicate '{0}' (eg: where T: Trait) must appear in generics list (eg: )" + )] WherePredicateMustAppearInGenerics(String), - #[error("All generics must appear only once in the generics parameter list or where clause")] + #[error("All generics must appear only once in the generics parameter list or where clause" + )] DuplicateGeneric(String), #[error("Generic lifetime '{0}' may not have bounds (eg: <'a: 'b>)")] LifetimesMayNotHaveBounds(String), - #[error("Invalid generic: '{0}' Only simple generics bounds are allowed (eg: T: Trait)")] + #[error("Invalid generic: '{0}' Only simple generics bounds are allowed (eg: T: Trait)" + )] InvalidGeneric(String), - #[error("Invalid predicate: '{0}' Only simple where predicates are allowed (eg: T: Trait)")] + #[error("Invalid predicate: '{0}' Only simple where predicates are allowed (eg: T: Trait)" + )] InvalidWherePredicate(String), - #[error("State may be either a single OpState parameter, one mutable #[state], or multiple immultiple #[state]s")] + #[error("State may be either a single OpState parameter, one mutable #[state], or multiple immultiple #[state]s" + )] InvalidOpStateCombination, #[error("JsRuntimeState may only be used in one parameter")] InvalidMultipleJsRuntimeState, @@ -842,7 +848,8 @@ pub enum SignatureError { pub enum AttributeError { #[error("Unknown or invalid attribute '{0}'")] InvalidAttribute(String), - #[error("Invalid inner attribute (#![attr]) in this position. Use an equivalent outer attribute (#[attr]) on the function instead.")] + #[error("Invalid inner attribute (#![attr]) in this position. Use an equivalent outer attribute (#[attr]) on the function instead." + )] InvalidInnerAttribute, #[error("Too many attributes")] TooManyAttributes, @@ -884,7 +891,8 @@ pub enum ArgError { AttributeError(#[from] AttributeError), #[error("The type '{0}' is not allowed in this position")] NotAllowedInThisPosition(String), - #[error("Invalid deno_core:: prefix for type '{0}'. Try adding `use deno_core::{1}` at the top of the file and specifying `{2}` in this position.")] + #[error("Invalid deno_core:: prefix for type '{0}'. Try adding `use deno_core::{1}` at the top of the file and specifying `{2}` in this position." + )] InvalidDenoCorePrefix(String, String, String), #[error("Expected a reference. Use '#[cppgc] &{0}' instead.")] ExpectedCppGcReference(String), @@ -1329,7 +1337,7 @@ fn parse_type_path( CBare(TNumeric(numeric)) } else { std::panic::catch_unwind(|| { - rules!(tokens => { + rules!(tokens => { ( $( std :: str :: )? String ) => { Ok(CBare(TString(Strings::String))) } @@ -1395,7 +1403,7 @@ fn parse_type_path( Err(ArgError::InvalidTypePath(stringify_token(any))) } }) - }).map_err(|e| ArgError::InternalError(format!("parse_type_path {e:?}")))?? + }).map_err(|e| ArgError::InternalError(format!("parse_type_path {e:?}")))?? }; // Ensure that we have the correct reference state. This is a bit awkward but it's @@ -1917,19 +1925,19 @@ mod tests { (Numeric(__SMI__, None)) -> Result(Numeric(__SMI__, None)) ); test!( - fn op_option_numeric_result(state: &mut OpState) -> Result, AnyError>; + fn op_option_numeric_result(state: &mut OpState) -> Result, OpError>; (Ref(Mut, OpState)) -> Result(OptionNumeric(u32, None)) ); test!( - #[smi] fn op_option_numeric_smi_result(#[smi] a: Option) -> Result, AnyError>; + #[smi] fn op_option_numeric_smi_result(#[smi] a: Option) -> Result, OpError>; (OptionNumeric(__SMI__, None)) -> Result(OptionNumeric(__SMI__, None)) ); test!( - fn op_ffi_read_f64(state: &mut OpState, ptr: *mut c_void, #[bigint] offset: isize) -> Result; + fn op_ffi_read_f64(state: &mut OpState, ptr: *mut c_void, #[bigint] offset: isize) -> Result; (Ref(Mut, OpState), External(Ptr(Mut)), Numeric(isize, None)) -> Result(Numeric(f64, None)) ); test!( - #[number] fn op_64_bit_number(#[number] offset: isize) -> Result; + #[number] fn op_64_bit_number(#[number] offset: isize) -> Result; (Numeric(isize, Number)) -> Result(Numeric(u64, Number)) ); test!( @@ -2030,7 +2038,7 @@ mod tests { #[smi] rid: ResourceId ) -> Result< ExtremelyLongTypeNameThatForcesEverythingToWrapAndAddsCommas, - AnyError, + OpError, >; (RcRefCell(OpState), Numeric(__SMI__, None)) -> FutureResult(SerdeV8(ExtremelyLongTypeNameThatForcesEverythingToWrapAndAddsCommas)) ); diff --git a/ops/op2/test_cases/async/async_result_impl.rs b/ops/op2/test_cases/async/async_result_impl.rs index f07f1be9b..944819d02 100644 --- a/ops/op2/test_cases/async/async_result_impl.rs +++ b/ops/op2/test_cases/async/async_result_impl.rs @@ -2,12 +2,12 @@ #![deny(warnings)] deno_ops_compile_test_runner::prelude!(); -use deno_core::error::AnyError; +use deno_core::error::OpError; use std::future::Future; #[op2(async)] pub fn op_async_result_impl( x: i32, -) -> Result>, AnyError> { +) -> Result>, OpError> { Ok(async move { Ok(x) }) } diff --git a/ops/op2/test_cases/compiler_pass/async.rs b/ops/op2/test_cases/compiler_pass/async.rs index 9918fe257..a36cae351 100644 --- a/ops/op2/test_cases/compiler_pass/async.rs +++ b/ops/op2/test_cases/compiler_pass/async.rs @@ -2,7 +2,7 @@ #![deny(warnings)] deno_ops_compile_test_runner::prelude!(); -use deno_core::error::AnyError; +use deno_core::error::OpError; use deno_core::JsBuffer; use deno_core::OpState; use std::cell::RefCell; @@ -25,14 +25,14 @@ pub async fn op_async3(x: i32) -> std::io::Result { } #[op2(async)] -pub fn op_async4(x: i32) -> Result, AnyError> { +pub fn op_async4(x: i32) -> Result, OpError> { Ok(async move { x }) } #[op2(async)] pub fn op_async5( x: i32, -) -> Result>, AnyError> { +) -> Result>, OpError> { Ok(async move { Ok(x) }) } diff --git a/ops/op2/test_cases/sync/bool_result.rs b/ops/op2/test_cases/sync/bool_result.rs index 97c76b61f..c0b8fa72a 100644 --- a/ops/op2/test_cases/sync/bool_result.rs +++ b/ops/op2/test_cases/sync/bool_result.rs @@ -2,9 +2,9 @@ #![deny(warnings)] deno_ops_compile_test_runner::prelude!(); -use deno_core::error::AnyError; +use deno_core::error::OpError; #[op2(fast)] -pub fn op_bool(arg: bool) -> Result { +pub fn op_bool(arg: bool) -> Result { Ok(arg) } diff --git a/ops/op2/test_cases/sync/result_external.rs b/ops/op2/test_cases/sync/result_external.rs index 6566136c5..b8b138122 100644 --- a/ops/op2/test_cases/sync/result_external.rs +++ b/ops/op2/test_cases/sync/result_external.rs @@ -2,9 +2,9 @@ #![deny(warnings)] deno_ops_compile_test_runner::prelude!(); -use deno_core::error::AnyError; +use deno_core::error::OpError; #[op2(fast)] -pub fn op_external_with_result() -> Result<*mut std::ffi::c_void, AnyError> { +pub fn op_external_with_result() -> Result<*mut std::ffi::c_void, OpError> { Ok(0 as _) } diff --git a/ops/op2/test_cases/sync/result_primitive.rs b/ops/op2/test_cases/sync/result_primitive.rs index 5aaeb9757..eb1170c1a 100644 --- a/ops/op2/test_cases/sync/result_primitive.rs +++ b/ops/op2/test_cases/sync/result_primitive.rs @@ -2,9 +2,9 @@ #![deny(warnings)] deno_ops_compile_test_runner::prelude!(); -use deno_core::error::AnyError; +use deno_core::error::OpError; #[op2(fast)] -pub fn op_u32_with_result() -> Result { +pub fn op_u32_with_result() -> Result { Ok(0) } diff --git a/ops/op2/test_cases/sync/result_scope.rs b/ops/op2/test_cases/sync/result_scope.rs index b2b59b6b9..5e55aabd4 100644 --- a/ops/op2/test_cases/sync/result_scope.rs +++ b/ops/op2/test_cases/sync/result_scope.rs @@ -2,12 +2,12 @@ #![deny(warnings)] deno_ops_compile_test_runner::prelude!(); -use deno_core::error::AnyError; +use deno_core::error::OpError; use deno_core::v8; #[op2] pub fn op_void_with_result( _scope: &mut v8::HandleScope, -) -> Result<(), AnyError> { +) -> Result<(), OpError> { Ok(()) } diff --git a/ops/op2/test_cases_fail/lifetimes.rs b/ops/op2/test_cases_fail/lifetimes.rs index adb486371..e81f43663 100644 --- a/ops/op2/test_cases_fail/lifetimes.rs +++ b/ops/op2/test_cases_fail/lifetimes.rs @@ -1,7 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. #![deny(warnings)] deno_ops_compile_test_runner::prelude!(); -use deno_core::error::AnyError; use deno_core::GarbageCollected; use std::future::Future; diff --git a/testing/checkin/runner/mod.rs b/testing/checkin/runner/mod.rs index 37c5ae2a9..f17574e50 100644 --- a/testing/checkin/runner/mod.rs +++ b/testing/checkin/runner/mod.rs @@ -122,9 +122,6 @@ pub fn create_runtime_from_snapshot( extension_transpiler: Some(Rc::new(|specifier, source| { maybe_transpile_source(specifier, source) })), - get_error_class_fn: Some(&|error| { - deno_core::error::get_custom_error_class(error).unwrap_or("Error") - }), shared_array_buffer_store: Some(CrossIsolateStore::default()), custom_module_evaluation_cb: Some(Box::new(custom_module_evaluation_cb)), inspector, diff --git a/testing/checkin/runner/ops_error.rs b/testing/checkin/runner/ops_error.rs index 3dc74d486..2ffd40093 100644 --- a/testing/checkin/runner/ops_error.rs +++ b/testing/checkin/runner/ops_error.rs @@ -1,28 +1,27 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use anyhow::anyhow; use anyhow::Error; -use deno_core::error::custom_error; -use deno_core::error::type_error; +use deno_core::error::JsNativeError; use deno_core::op2; #[op2(async)] pub async fn op_async_throw_error_eager() -> Result<(), Error> { - Err(type_error("Error").into()) + Err(JsNativeError::type_error("Error").into()) } #[op2(async(deferred), fast)] pub async fn op_async_throw_error_deferred() -> Result<(), Error> { - Err(type_error("Error").into()) + Err(JsNativeError::type_error("Error").into()) } #[op2(async(lazy), fast)] pub async fn op_async_throw_error_lazy() -> Result<(), Error> { - Err(type_error("Error").into()) + Err(JsNativeError::type_error("Error").into()) } #[op2(fast)] pub fn op_error_custom_sync(#[string] message: String) -> Result<(), Error> { - Err(custom_error("BadResource", message).into()) + Err(JsNativeError::bad_resource(message).into()) } #[op2(fast)] diff --git a/testing/checkin/runner/ts_module_loader.rs b/testing/checkin/runner/ts_module_loader.rs index f9db85030..24159828b 100644 --- a/testing/checkin/runner/ts_module_loader.rs +++ b/testing/checkin/runner/ts_module_loader.rs @@ -10,7 +10,6 @@ use anyhow::Context; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; -use deno_core::error::AnyError; use deno_core::error::ModuleLoaderError; use deno_core::resolve_import; use deno_core::url::Url; @@ -114,7 +113,7 @@ impl ModuleLoader for TypescriptModuleLoader { scope_analysis: false, maybe_syntax: None, }) - .map_err(AnyError::from)?; + .map_err(anyhow::Error::from)?; let res = parsed .transpile( &deno_ast::TranspileOptions { @@ -129,7 +128,7 @@ impl ModuleLoader for TypescriptModuleLoader { ..Default::default() }, ) - .map_err(AnyError::from)?; + .map_err(anyhow::Error::from)?; let res = res.into_source(); let source_map = res.source_map.unwrap(); source_maps @@ -162,7 +161,7 @@ impl ModuleLoader for TypescriptModuleLoader { pub fn maybe_transpile_source( specifier: ModuleName, source: ModuleCodeString, -) -> Result<(ModuleCodeString, Option), AnyError> { +) -> Result<(ModuleCodeString, Option), anyhow::Error> { // Always transpile `checkin:` built-in modules, since they might be TypeScript. let media_type = if specifier.starts_with("checkin:") { MediaType::TypeScript From 58ebe993619c09195361dd1d9b18bbb869a2836f Mon Sep 17 00:00:00 2001 From: crowlkats Date: Thu, 22 Aug 2024 14:44:38 +0200 Subject: [PATCH 03/52] cleanup --- core/convert.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/core/convert.rs b/core/convert.rs index 6b5fc0c97..2d29ae78b 100644 --- a/core/convert.rs +++ b/core/convert.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::PubError; +use crate::error::JsNativeError; use crate::runtime::ops; use std::convert::Infallible; @@ -170,15 +170,15 @@ impl<'a, T: SmallInt> ToV8<'a> for Smi { } impl<'a, T: SmallInt> FromV8<'a> for Smi { - type Error = PubError; + type Error = JsNativeError; #[inline] fn from_v8( _scope: &mut v8::HandleScope<'a>, value: v8::Local<'a, v8::Value>, ) -> Result { - let v = crate::runtime::ops::to_i32_option(&value).ok_or_else(|| { - crate::error::JsNativeError::type_error(format!("Expected {}", T::NAME)) + let v = ops::to_i32_option(&value).ok_or_else(|| { + JsNativeError::type_error(format!("Expected {}", T::NAME)) })?; Ok(Smi(T::from_i32(v))) } @@ -240,16 +240,15 @@ impl<'a, T: Numeric> ToV8<'a> for Number { } impl<'a, T: Numeric> FromV8<'a> for Number { - type Error = PubError; + type Error = JsNativeError; #[inline] fn from_v8( _scope: &mut v8::HandleScope<'a>, value: v8::Local<'a, v8::Value>, ) -> Result { - T::from_value(&value).map(Number).ok_or_else(|| { - crate::error::JsNativeError::type_error(format!("Expected {}", T::NAME)) - .into() - }) + T::from_value(&value) + .map(Number) + .ok_or_else(|| JsNativeError::type_error(format!("Expected {}", T::NAME))) } } From baaae1319aae7ca90228e5ddfc282ced68e98167 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Thu, 22 Aug 2024 14:52:39 +0200 Subject: [PATCH 04/52] fix --- core/error.rs | 33 +++++++++++++++------------- core/runtime/op_driver/op_results.rs | 31 ++++++++++++++++---------- ops/op2/dispatch_slow.rs | 1 - 3 files changed, 38 insertions(+), 27 deletions(-) diff --git a/core/error.rs b/core/error.rs index ce0d4106f..70cf637f4 100644 --- a/core/error.rs +++ b/core/error.rs @@ -79,7 +79,7 @@ impl From for PubError { } } -pub trait JsErrorClass: std::any::Any + Debug + 'static { +pub trait JsErrorClass: Debug + 'static { fn get_class(&self) -> &'static str; fn get_message(&self) -> Cow<'static, str>; } @@ -126,13 +126,16 @@ impl JsErrorClass for std::io::Error { UnexpectedEof => "UnexpectedEof", Other => "Error", WouldBlock => "WouldBlock", - FilesystemLoop => "FilesystemLoop", - IsADirectory => "IsADirectory", - NetworkUnreachable => "NetworkUnreachable", - NotADirectory => "NotADirectory", - // Non-exhaustive enum - might add new variants - // in the future - _ => "Error", + kind => { + let kind_str = kind.to_string(); + match kind_str.as_str() { + "FilesystemLoop" => "FilesystemLoop", + "IsADirectory" => "IsADirectory", + "NetworkUnreachable" => "NetworkUnreachable", + "NotADirectory" => "NotADirectory", + _ => "Error", + } + } } } @@ -1527,7 +1530,7 @@ pub fn format_location(frame: &JsStackFrame) -> String { ErrorElement::EvalOrigin, frame.eval_origin.as_ref().unwrap(), ) - .to_string() + .to_string() + ", "); } result += &F::fmt_element(Anonymous, ""); @@ -1538,14 +1541,14 @@ pub fn format_location(frame: &JsStackFrame) -> String { ":{}", F::fmt_element(LineNumber, &line_number.to_string()) ) - .unwrap(); + .unwrap(); if let Some(column_number) = frame.column_number { write!( result, ":{}", F::fmt_element(ColumnNumber, &column_number.to_string()) ) - .unwrap(); + .unwrap(); } } result @@ -1689,10 +1692,10 @@ mod tests { for (input, expect) in cases { match expect { Some(( - expect_before, - (expect_file, expect_line, expect_col), - expect_after, - )) => { + expect_before, + (expect_file, expect_line, expect_col), + expect_after, + )) => { let (before, (file_name, line_number, column_number), after) = parse_eval_origin(input).unwrap(); assert_eq!(before, expect_before); diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index c128900e2..28a97c3a5 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -54,9 +54,9 @@ pub struct V8OpMappingContext {} pub type V8RetValMapper = for<'r> fn( - &mut v8::HandleScope<'r>, - R, - ) -> Result, serde_v8::Error>; + &mut v8::HandleScope<'r>, + R, +) -> Result, serde_v8::Error>; impl<'s> OpMappingContextLifetime<'s> for V8OpMappingContext { type Context = v8::HandleScope<'s>; @@ -135,11 +135,10 @@ pub struct PendingOpMappingInfo< >(pub PendingOpInfo, pub C::MappingFn); impl Copy - for PendingOpMappingInfo -{ -} +for PendingOpMappingInfo +{} impl Clone - for PendingOpMappingInfo +for PendingOpMappingInfo { #[inline(always)] fn clone(&self) -> Self { @@ -148,8 +147,8 @@ impl Clone } impl + 'static> - FutureContextMapper, PendingOpInfo, Result> - for PendingOpMappingInfo +FutureContextMapper, PendingOpInfo, Result> +for PendingOpMappingInfo { fn context(&self) -> PendingOpInfo { self.0 @@ -161,8 +160,8 @@ impl + 'static> } impl - FutureContextMapper, PendingOpInfo, R> - for PendingOpMappingInfo +FutureContextMapper, PendingOpInfo, R> +for PendingOpMappingInfo { fn context(&self) -> PendingOpInfo { self.0 @@ -265,6 +264,16 @@ pub struct OpError { error_code: Option<&'static str>, } +impl JsErrorClass for OpError { + fn get_class(&self) -> &'static str { + self.error.get_class() + } + + fn get_message(&self) -> std::borrow::Cow<'static, str> { + self.error.get_message() + } +} + impl From for OpError { fn from(err: T) -> Self { Self { diff --git a/ops/op2/dispatch_slow.rs b/ops/op2/dispatch_slow.rs index 0c0ec5b3b..f8f2f5a0f 100644 --- a/ops/op2/dispatch_slow.rs +++ b/ops/op2/dispatch_slow.rs @@ -1009,7 +1009,6 @@ pub(crate) fn throw_exception( #maybe_scope #maybe_args #maybe_opctx - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut #scope, &err, From 8afde02fc4aca835a4ae5c04bff0ab1012fc0edc Mon Sep 17 00:00:00 2001 From: crowlkats Date: Thu, 22 Aug 2024 14:53:00 +0200 Subject: [PATCH 05/52] fix --- core/runtime/op_driver/op_results.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index 28a97c3a5..c067f8df8 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -54,9 +54,9 @@ pub struct V8OpMappingContext {} pub type V8RetValMapper = for<'r> fn( - &mut v8::HandleScope<'r>, - R, -) -> Result, serde_v8::Error>; + &mut v8::HandleScope<'r>, + R, + ) -> Result, serde_v8::Error>; impl<'s> OpMappingContextLifetime<'s> for V8OpMappingContext { type Context = v8::HandleScope<'s>; @@ -135,10 +135,11 @@ pub struct PendingOpMappingInfo< >(pub PendingOpInfo, pub C::MappingFn); impl Copy -for PendingOpMappingInfo -{} + for PendingOpMappingInfo +{ +} impl Clone -for PendingOpMappingInfo + for PendingOpMappingInfo { #[inline(always)] fn clone(&self) -> Self { @@ -147,8 +148,8 @@ for PendingOpMappingInfo } impl + 'static> -FutureContextMapper, PendingOpInfo, Result> -for PendingOpMappingInfo + FutureContextMapper, PendingOpInfo, Result> + for PendingOpMappingInfo { fn context(&self) -> PendingOpInfo { self.0 @@ -160,8 +161,8 @@ for PendingOpMappingInfo } impl -FutureContextMapper, PendingOpInfo, R> -for PendingOpMappingInfo + FutureContextMapper, PendingOpInfo, R> + for PendingOpMappingInfo { fn context(&self) -> PendingOpInfo { self.0 From 2c2a538bc00927bd440de602f82670d2ffa0e1aa Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 23 Aug 2024 11:02:48 +0200 Subject: [PATCH 06/52] rework moduleerror --- core/async_cancel.rs | 32 +++++----- core/error.rs | 33 +++------- core/error_codes.rs | 2 +- core/examples/ts_module_loader.rs | 8 +-- core/extension_set.rs | 8 +-- core/inspector.rs | 4 +- core/io/resource.rs | 13 ++-- core/modules/loaders.rs | 12 ++-- core/modules/map.rs | 96 +++++++++++++--------------- core/modules/mod.rs | 36 +++++++++-- core/modules/recursive_load.rs | 10 +-- core/modules/tests.rs | 33 +++++----- core/ops_builtin_v8.rs | 5 +- core/runtime/bindings.rs | 8 +-- core/runtime/exception_state.rs | 4 +- core/runtime/jsrealm.rs | 12 ++-- core/runtime/jsruntime.rs | 96 ++++++++++++++-------------- core/runtime/op_driver/op_results.rs | 20 ++++-- core/runtime/ops.rs | 21 +++--- core/runtime/snapshot.rs | 4 +- core/runtime/tests/error.rs | 12 ++-- core/runtime/tests/misc.rs | 11 ++-- core/runtime/tests/ops.rs | 29 ++++----- core/runtime/tests/snapshot.rs | 9 ++- core/source_map.rs | 3 +- testing/checkin/runner/mod.rs | 9 ++- testing/checkin/runner/ops_error.rs | 19 +++--- testing/checkin/runner/ops_io.rs | 4 +- testing/checkin/runner/ops_worker.rs | 20 +++--- testing/checkin/runner/testing.rs | 7 +- 30 files changed, 290 insertions(+), 290 deletions(-) diff --git a/core/async_cancel.rs b/core/async_cancel.rs index 72d854845..fdcb038f3 100644 --- a/core/async_cancel.rs +++ b/core/async_cancel.rs @@ -107,7 +107,7 @@ pub struct TryCancelable { impl Future for TryCancelable where - F: Future>, + F: Future>, Canceled: Into, { type Output = F::Output; @@ -124,7 +124,7 @@ where impl FusedFuture for TryCancelable where - F: Future>, + F: Future>, Canceled: Into, { fn is_terminated(&self) -> bool { @@ -144,7 +144,7 @@ where impl Future for Abortable where - F: Future + Unpin, + F: Future + Unpin, { type Output = Result; @@ -171,7 +171,7 @@ where impl FusedFuture for Abortable where - F: Future> + Unpin, + F: Future> + Unpin, Canceled: Into, { fn is_terminated(&self) -> bool { @@ -222,8 +222,7 @@ impl CancelTryFuture for F where F: TryFuture, Canceled: Into, -{ -} +{} #[derive(Copy, Clone, Default, Debug, Eq, Hash, PartialEq)] pub struct Canceled; @@ -666,7 +665,6 @@ mod internal { #[cfg(test)] mod tests { use super::*; - use anyhow::Error; use futures::future::pending; use futures::future::poll_fn; use futures::future::ready; @@ -685,7 +683,7 @@ mod tests { fn box_fused<'a, F: FusedFuture + 'a>( future: F, - ) -> Pin + 'a>> { + ) -> Pin + 'a>> { Box::pin(future) } @@ -700,7 +698,7 @@ mod tests { Poll::Pending } }) - .await + .await } #[test] @@ -782,7 +780,7 @@ mod tests { // Cancel a spawned task before it actually runs. let cancel_handle = Rc::new(CancelHandle::new()); let future = spawn(async { panic!("the task should not be spawned") }) - .map_err(Error::from) + .map_err(anyhow::Error::from) .try_or_cancel(&cancel_handle); cancel_handle.cancel(); let error = future.await.unwrap_err(); @@ -884,7 +882,7 @@ mod tests { tokio::task::yield_now().await; 1_u8 }) - .or_abort(&cancel_handle); + .or_abort(&cancel_handle); cancel_handle.cancel(); for _ in 0..10 { @@ -919,8 +917,8 @@ mod tests { yield_now().await; unreachable!(); } - .or_cancel(&cancel_handle) - .await; + .or_cancel(&cancel_handle) + .await; assert_eq!(result.unwrap_err(), Canceled); }) } @@ -941,8 +939,8 @@ mod tests { pending!(); unreachable!(); } - .or_cancel(&cancel_handle) - .await; + .or_cancel(&cancel_handle) + .await; assert_eq!(result.unwrap_err(), Canceled); }); } @@ -962,8 +960,8 @@ mod tests { cancel_handle.cancel(); Ok::<_, io::Error>("done") } - .try_or_cancel(&cancel_handle) - .await; + .try_or_cancel(&cancel_handle) + .await; assert_eq!(result.unwrap(), "done"); }); } diff --git a/core/error.rs b/core/error.rs index 70cf637f4..b1d7d1b42 100644 --- a/core/error.rs +++ b/core/error.rs @@ -23,7 +23,7 @@ use crate::FastStaticString; pub type AnyError = anyhow::Error; #[derive(Debug, thiserror::Error)] -pub enum PubError { +pub enum CoreError { #[error("top level await is not allowed in extensions")] TLA(JsError), #[error(transparent)] @@ -52,10 +52,6 @@ pub enum PubError { ModuleLoader(Box), #[error("Could not execute {specifier}")] CouldNotExecute { error: Box, specifier: String }, - #[error( - "\"npm:\" specifiers are currently not supported in import.meta.resolve()" - )] - NpmMetaResolve, #[error(transparent)] JsNativeError(#[from] JsNativeError), #[error(transparent)] @@ -70,29 +66,22 @@ pub enum PubError { )] PendingPromiseResolution, #[error(transparent)] - Anyhow(anyhow::Error), + Module(super::modules::ModuleConcreteError), + #[error(transparent)] + Other(anyhow::Error), } -impl From for PubError { +impl From for CoreError { fn from(err: ModuleLoaderError) -> Self { - PubError::ModuleLoader(Box::new(err)) + CoreError::ModuleLoader(Box::new(err)) } } -pub trait JsErrorClass: Debug + 'static { +pub trait JsErrorClass: Display + Debug + Send + Sync + 'static { fn get_class(&self) -> &'static str; fn get_message(&self) -> Cow<'static, str>; } -pub fn get_error_class(error: &dyn std::any::Any) -> &'static str { - if let Some(error) = error.downcast_ref::() { - error.get_class() - } else { - // Default value when trait is not implemented - "Error" - } -} - impl JsErrorClass for serde_v8::Error { fn get_class(&self) -> &'static str { "TypeError" @@ -255,10 +244,6 @@ impl JsNativeError { } } -pub fn get_custom_error_class(error: &anyhow::Error) -> Option<&'static str> { - error.downcast_ref::().map(|e| e.class) -} - pub fn to_v8_error<'a>( scope: &mut v8::HandleScope<'a>, error: &impl JsErrorClass, @@ -899,7 +884,7 @@ impl Display for JsError { // values of type v8::Global. pub(crate) fn to_v8_type_error( scope: &mut v8::HandleScope, - err: PubError, + err: CoreError, ) -> v8::Global { let err_string = err.to_string(); let mut error_chain = vec![]; @@ -1064,7 +1049,7 @@ pub(crate) fn exception_to_err_result( exception: v8::Local, mut in_promise: bool, clear_error: bool, -) -> Result { +) -> Result { let state = JsRealm::exception_state_from_scope(scope); let mut was_terminating_execution = scope.is_execution_terminating(); diff --git a/core/error_codes.rs b/core/error_codes.rs index d96ea42de..87fd39bd9 100644 --- a/core/error_codes.rs +++ b/core/error_codes.rs @@ -3,7 +3,7 @@ pub fn get_error_code( err: &impl crate::error::JsErrorClass, ) -> Option<&'static str> { - (&err as &dyn std::any::Any) + (err as &dyn std::any::Any) .downcast_ref::() .map(|e| match e.raw_os_error() { Some(code) => get_os_error_code(code), diff --git a/core/examples/ts_module_loader.rs b/core/examples/ts_module_loader.rs index 8f0fa6c91..d13dd1874 100644 --- a/core/examples/ts_module_loader.rs +++ b/core/examples/ts_module_loader.rs @@ -11,10 +11,10 @@ use std::rc::Rc; use anyhow::anyhow; use anyhow::bail; use anyhow::Context; -use anyhow::Error; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; +use deno_core::error::ModuleLoaderError; use deno_core::resolve_import; use deno_core::resolve_path; use deno_core::JsRuntime; @@ -43,7 +43,7 @@ impl ModuleLoader for TypescriptModuleLoader { specifier: &str, referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { Ok(resolve_import(specifier, referrer)?) } @@ -58,7 +58,7 @@ impl ModuleLoader for TypescriptModuleLoader { fn load( source_maps: SourceMapStore, module_specifier: &ModuleSpecifier, - ) -> Result { + ) -> Result { let path = module_specifier .to_file_path() .map_err(|_| anyhow!("Only file:// URLs are supported."))?; @@ -128,7 +128,7 @@ impl ModuleLoader for TypescriptModuleLoader { } } -fn main() -> Result<(), Error> { +fn main() -> Result<(), anyhow::Error> { let args: Vec = std::env::args().collect(); if args.len() < 2 { println!("Usage: target/examples/debug/ts_module_loader "); diff --git a/core/extension_set.rs b/core/extension_set.rs index dbb6a1390..b5139bc7e 100644 --- a/core/extension_set.rs +++ b/core/extension_set.rs @@ -1,5 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::PubError; +use crate::error::CoreError; use crate::extensions::Extension; use crate::extensions::ExtensionSourceType; use crate::extensions::GlobalObjectMiddlewareFn; @@ -239,14 +239,14 @@ fn load( transpiler: Option<&ExtensionTranspiler>, source: &ExtensionFileSource, load_callback: &mut impl FnMut(&ExtensionFileSource), -) -> Result<(ModuleCodeString, Option), PubError> { +) -> Result<(ModuleCodeString, Option), CoreError> { load_callback(source); let mut source_code = source.load()?; let mut source_map = None; if let Some(transpiler) = transpiler { (source_code, source_map) = transpiler(ModuleName::from_static(source.specifier), source_code) - .map_err(PubError::ExtensionTranspiler)?; + .map_err(CoreError::ExtensionTranspiler)?; } let mut maybe_source_map = None; if let Some(source_map) = source_map { @@ -259,7 +259,7 @@ pub fn into_sources_and_source_maps( transpiler: Option<&ExtensionTranspiler>, extensions: &[Extension], mut load_callback: impl FnMut(&ExtensionFileSource), -) -> Result { +) -> Result { let mut sources = LoadedSources::default(); for extension in extensions { diff --git a/core/inspector.rs b/core/inspector.rs index 75e7b8518..6757c09a8 100644 --- a/core/inspector.rs +++ b/core/inspector.rs @@ -4,7 +4,7 @@ //! //! -use crate::error::PubError; +use crate::error::CoreError; use crate::futures::channel::mpsc; use crate::futures::channel::mpsc::UnboundedReceiver; use crate::futures::channel::mpsc::UnboundedSender; @@ -766,7 +766,7 @@ impl LocalInspectorSession { &mut self, method: &str, params: Option, - ) -> Result { + ) -> Result { let id = self.next_message_id; self.next_message_id += 1; diff --git a/core/io/resource.rs b/core/io/resource.rs index 7c02a9f42..c390c267b 100644 --- a/core/io/resource.rs +++ b/core/io/resource.rs @@ -6,7 +6,6 @@ // resources. Resources may or may not correspond to a real operating system // file descriptor (hence the different name). -use crate::error::AnyError; use crate::error::JsNativeError; use crate::io::AsyncResult; use crate::io::BufMutView; @@ -110,7 +109,10 @@ pub trait Resource: Any + 'static { } /// Write an error state to this resource, if the resource supports it. - fn write_error(self: Rc, _error: AnyError) -> AsyncResult<()> { + fn write_error( + self: Rc, + _error: crate::error::AnyError, + ) -> AsyncResult<()> { Box::pin(futures::future::err(JsNativeError::not_supported().into())) } @@ -158,13 +160,16 @@ pub trait Resource: Any + 'static { fn read_byob_sync( self: Rc, data: &mut [u8], - ) -> Result { + ) -> Result { _ = data; Err(JsNativeError::not_supported().into()) } /// The same as [`write()`][Resource::write], but synchronous. - fn write_sync(self: Rc, data: &[u8]) -> Result { + fn write_sync( + self: Rc, + data: &[u8], + ) -> Result { _ = data; Err(JsNativeError::not_supported().into()) } diff --git a/core/modules/loaders.rs b/core/modules/loaders.rs index 01b81e87b..23cc52a89 100644 --- a/core/modules/loaders.rs +++ b/core/modules/loaders.rs @@ -14,7 +14,7 @@ use crate::resolve_import; use crate::ModuleSourceCode; use anyhow::Context; -use deno_core::error::PubError; +use deno_core::error::CoreError; use futures::future::FutureExt; use std::cell::RefCell; use std::collections::HashMap; @@ -50,18 +50,18 @@ pub enum ModuleLoaderError { #[error(transparent)] Resolution(#[from] crate::ModuleResolutionError), #[error(transparent)] - Other(#[from] PubError), + Other(#[from] CoreError), } impl From for ModuleLoaderError { fn from(err: anyhow::Error) -> Self { - ModuleLoaderError::Other(PubError::Anyhow(err)) + ModuleLoaderError::Other(CoreError::Other(err)) } } impl From for ModuleLoaderError { fn from(err: std::io::Error) -> Self { - ModuleLoaderError::Other(PubError::Io(err)) + ModuleLoaderError::Other(CoreError::Io(err)) } } @@ -213,12 +213,12 @@ impl ExtModuleLoader { } } - pub fn finalize(self) -> Result<(), PubError> { + pub fn finalize(self) -> Result<(), CoreError> { let sources = self.sources.take(); let unused_modules: Vec<_> = sources.iter().collect(); if !unused_modules.is_empty() { - return Err(PubError::UnusedModules( + return Err(CoreError::UnusedModules( unused_modules .into_iter() .map(|(name, _)| name.to_string()) diff --git a/core/modules/map.rs b/core/modules/map.rs index f2cb4e20d..1f2e0f346 100644 --- a/core/modules/map.rs +++ b/core/modules/map.rs @@ -1,7 +1,7 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use super::module_map_data::ModuleMapSnapshotData; -use super::IntoModuleCodeString; use super::IntoModuleName; +use super::{IntoModuleCodeString, ModuleConcreteError}; use crate::ascii_str; use crate::error::exception_to_err_result; use crate::error::throw_type_error; @@ -44,7 +44,7 @@ use super::module_map_data::ModuleMapData; use super::CustomModuleEvaluationKind; use super::LazyEsmModuleLoader; use super::RequestedModuleType; -use deno_core::error::PubError; +use deno_core::error::CoreError; use std::borrow::Cow; use std::cell::Cell; use std::cell::RefCell; @@ -57,7 +57,7 @@ use std::task::Poll; use tokio::sync::oneshot; type PrepareLoadFuture = - dyn Future)>; + dyn Future)>; type CodeCacheReadyFuture = dyn Future; @@ -65,7 +65,7 @@ use super::ImportMetaResolveCallback; struct ModEvaluate { module_map: Rc, - sender: Option>>, + sender: Option>>, module: Option>, notify: Vec>, } @@ -165,7 +165,7 @@ impl ModuleMap { pub(crate) fn check_all_modules_evaluated( &self, scope: &mut v8::HandleScope, - ) -> Result<(), PubError> { + ) -> Result<(), CoreError> { let mut not_evaluated = vec![]; let data = self.data.borrow(); @@ -185,7 +185,7 @@ impl ModuleMap { } if !not_evaluated.is_empty() { - return Err(PubError::NonEvaluatedModules(not_evaluated)); + return Err(CoreError::NonEvaluatedModules(not_evaluated)); } Ok(()) @@ -377,12 +377,7 @@ impl ModuleMap { )? } ModuleType::Wasm => { - return Err(ModuleError::Other( - JsNativeError::generic( - "Importing Wasm modules is currently not supported.", - ) - .into(), - )); + return Err(ModuleError::Concrete(ModuleConcreteError::WasmUnsupported)) } ModuleType::Json => { let code = ModuleSource::get_string_source(code); @@ -394,12 +389,8 @@ impl ModuleMap { state.custom_module_evaluation_cb.as_ref(); let Some(custom_evaluation_cb) = custom_module_evaluation_cb else { - return Err(ModuleError::Other( - JsNativeError::generic(format!( - "Importing '{}' modules is not supported", - module_type - )) - .into(), + return Err(ModuleError::Concrete( + ModuleConcreteError::UnsupportedKind(module_type.to_string()), )); }; @@ -413,7 +404,7 @@ impl ModuleMap { &module_url_found, code, ) - .map_err(|e| ModuleError::Other(PubError::Anyhow(e)))?; + .map_err(|e| ModuleError::Core(CoreError::Other(e)))?; match module_evaluation_kind { // Simple case, we just got a single value so we create a regular @@ -426,7 +417,7 @@ impl ModuleMap { module_url_found, ModuleType::Other(module_type.clone()), exports, - )? + ) } // Complex case - besides a synthetic module, we will create a new @@ -444,7 +435,7 @@ impl ModuleMap { url1, synthetic_module_type, exports, - )?; + ); let (code_cache_info, url2) = if let Some(code_cache) = code_cache { let (url1, url2) = url2.into_cheap_copy(); @@ -489,7 +480,7 @@ impl ModuleMap { name: impl IntoModuleName, module_type: ModuleType, exports: Vec<(FastStaticString, v8::Local)>, - ) -> Result { + ) -> ModuleId { let name = name.into_module_name(); let name_str = name.v8_string(scope); @@ -533,7 +524,7 @@ impl ModuleMap { // Synthetic modules have no imports so their instantation must never fail. self.instantiate_module(scope, id).unwrap(); - Ok(id) + id } // TODO(bartlomieju): remove this method or rename it to `new_js_module`. @@ -586,11 +577,12 @@ impl ModuleMap { let data = self.data.borrow(); if let Some(main_module) = data.main_module_id { let main_name = self.data.borrow().get_name_by_id(main_module).unwrap(); - return Err(ModuleError::Other(JsNativeError::generic( - format!("Trying to create \"main\" module ({:?}), when one already exists ({:?})", - name, - main_name, - )).into())); + return Err(ModuleError::Concrete( + ModuleConcreteError::MainModuleAlreadyExists { + main_module: main_name.to_string(), + new_module: name.to_string(), + }, + )); } } @@ -653,11 +645,8 @@ impl ModuleMap { let unbound_module_script = module.get_unbound_module_script(tc_scope); let code_cache = unbound_module_script.create_code_cache().ok_or_else(|| { - ModuleError::Other( - JsNativeError::generic( - "Unable to get code cache from unbound module script", - ) - .into(), + ModuleError::Concrete( + ModuleConcreteError::UnboundModuleScriptCodeCache, ) })?; let fut = @@ -716,7 +705,7 @@ impl ModuleMap { }, ) { Ok(s) => s, - Err(e) => return Err(ModuleError::Other(e)), + Err(e) => return Err(ModuleError::Core(e)), }; let requested_module_type = get_requested_module_type_from_attributes(&attributes); @@ -765,7 +754,7 @@ impl ModuleMap { } }; let exports = vec![(ascii_str!("default"), parsed_json)]; - self.new_synthetic_module(tc_scope, name, ModuleType::Json, exports) + Ok(self.new_synthetic_module(tc_scope, name, ModuleType::Json, exports)) } pub(crate) fn instantiate_module( @@ -858,7 +847,7 @@ impl ModuleMap { specifier: &str, referrer: &str, kind: ResolutionKind, - ) -> Result { + ) -> Result { if specifier.starts_with("ext:") && !referrer.starts_with("ext:") && !referrer.starts_with("node:") @@ -922,7 +911,7 @@ impl ModuleMap { pub(crate) async fn load_main( module_map_rc: Rc, specifier: impl AsRef, - ) -> Result { + ) -> Result { let load = RecursiveModuleLoad::main(specifier.as_ref(), module_map_rc.clone()); load.prepare().await?; @@ -932,7 +921,7 @@ impl ModuleMap { pub(crate) async fn load_side( module_map_rc: Rc, specifier: impl AsRef, - ) -> Result { + ) -> Result { let load = RecursiveModuleLoad::side(specifier.as_ref(), module_map_rc.clone()); load.prepare().await?; @@ -997,7 +986,7 @@ impl ModuleMap { self: &Rc, scope: &mut v8::HandleScope, id: ModuleId, - ) -> impl Future> + Unpin { + ) -> impl Future> + Unpin { let tc_scope = &mut v8::TryCatch::new(scope); let module = self @@ -1020,7 +1009,7 @@ impl ModuleMap { let (sender, receiver) = oneshot::channel(); let receiver = receiver - .map(|res| res.unwrap_or_else(|_| Err(PubError::ExecutionTerminated))); + .map(|res| res.unwrap_or_else(|_| Err(CoreError::ExecutionTerminated))); let Some(value) = module.evaluate(tc_scope) else { if tc_scope.has_terminated() || tc_scope.is_execution_terminating() { @@ -1168,7 +1157,7 @@ impl ModuleMap { self: &Rc, scope: &mut v8::HandleScope, id: ModuleId, - ) -> Result<(), PubError> { + ) -> Result<(), CoreError> { let mut receiver = self.mod_evaluate(scope, id); // After evaluate_pending_module, if the module isn't fully evaluated @@ -1176,7 +1165,7 @@ impl ModuleMap { // uses TLA. match receiver.poll_unpin(&mut Context::from_waker(noop_waker_ref())) { Poll::Ready(result) => { - result.map_err(|e| PubError::CouldNotExecute { + result.map_err(|e| CoreError::CouldNotExecute { error: Box::new(e), specifier: self.get_name_by_id(id).unwrap(), })?; @@ -1187,7 +1176,7 @@ impl ModuleMap { assert!(!messages.is_empty()); let msg = v8::Local::new(scope, &messages[0]); let js_error = JsError::from_v8_message(scope, msg); - return Err(PubError::TLA(js_error)); + return Err(CoreError::TLA(js_error)); } } @@ -1199,7 +1188,7 @@ impl ModuleMap { scope: &mut v8::HandleScope, load_id: ModuleLoadId, id: ModuleId, - ) -> Result<(), PubError> { + ) -> Result<(), CoreError> { let module_handle = self.get_handle(id).expect("ModuleInfo not found"); let status = { @@ -1391,7 +1380,7 @@ impl ModuleMap { &self, cx: &mut Context, scope: &mut v8::HandleScope, - ) -> Result<(), PubError> { + ) -> Result<(), CoreError> { let mut has_evaluated = true; // TODO(mmastrac): We register this waker unconditionally because we occasionally need to re-run @@ -1442,7 +1431,7 @@ impl ModuleMap { &self, cx: &mut Context, scope: &mut v8::HandleScope, - ) -> Poll> { + ) -> Poll> { if !self.preparing_dynamic_imports_pending.get() { return Poll::Ready(Ok(())); } @@ -1486,7 +1475,7 @@ impl ModuleMap { &self, cx: &mut Context, scope: &mut v8::HandleScope, - ) -> Poll> { + ) -> Poll> { if !self.pending_dynamic_imports_pending.get() { return Poll::Ready(Ok(())); } @@ -1523,7 +1512,10 @@ impl ModuleMap { Err(err) => { let exception = match err { ModuleError::Exception(e) => e, - ModuleError::Other(e) => to_v8_type_error(scope, e), + ModuleError::Core(e) => to_v8_type_error(scope, e), + ModuleError::Concrete(e) => { + to_v8_type_error(scope, CoreError::Module(e)) + } }; self.dynamic_import_reject(scope, dyn_import_id, exception) } @@ -1568,7 +1560,7 @@ impl ModuleMap { fn poll_code_cache_ready( &self, cx: &mut Context, - ) -> Poll> { + ) -> Poll> { if !self.pending_code_cache_ready.get() { return Poll::Ready(Ok(())); } @@ -1596,7 +1588,7 @@ impl ModuleMap { &self, scope: &mut v8::HandleScope, module_id: ModuleId, - ) -> Result, PubError> { + ) -> Result, CoreError> { let module_handle = self .data .borrow() @@ -1694,7 +1686,7 @@ impl ModuleMap { module_specifier: &str, source_code: ModuleCodeString, code_cache_info: Option, - ) -> Result, PubError> { + ) -> Result, CoreError> { let specifier = ModuleSpecifier::parse(module_specifier)?; let mod_id = self .new_es_module( @@ -1755,7 +1747,7 @@ impl ModuleMap { &self, scope: &mut v8::HandleScope, module_specifier: &str, - ) -> Result, PubError> { + ) -> Result, CoreError> { let lazy_esm_sources = self.data.borrow().lazy_esm_sources.clone(); let loader = LazyEsmModuleLoader::new(lazy_esm_sources); diff --git a/core/modules/mod.rs b/core/modules/mod.rs index 6bd8543dc..edc33c51e 100644 --- a/core/modules/mod.rs +++ b/core/modules/mod.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::error::exception_to_err_result; -use crate::error::PubError; +use crate::error::CoreError; use crate::fast_string::FastString; use crate::module_specifier::ModuleSpecifier; use crate::FastStaticString; @@ -623,10 +623,37 @@ pub(crate) struct ModuleInfo { pub module_type: ModuleType, } +#[derive(Debug, thiserror::Error)] +pub enum ModuleConcreteError { + #[error("Trying to create \"main\" module ({new_module:?}), when one already exists ({main_module:?})" + )] + MainModuleAlreadyExists { + main_module: String, + new_module: String, + }, + #[error("Unable to get code cache from unbound module script")] + UnboundModuleScriptCodeCache, + #[error("Importing Wasm modules is currently not supported")] + WasmUnsupported, + #[error("Importing '{0}' modules is not supported")] + UnsupportedKind(String), +} + +impl super::error::JsErrorClass for ModuleConcreteError { + fn get_class(&self) -> &'static str { + "Error" + } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } +} + #[derive(Debug)] pub enum ModuleError { Exception(v8::Global), - Other(PubError), + Concrete(ModuleConcreteError), + Core(CoreError), } impl ModuleError { @@ -635,14 +662,15 @@ impl ModuleError { scope: &mut v8::HandleScope, in_promise: bool, clear_error: bool, - ) -> PubError { + ) -> CoreError { match self { ModuleError::Exception(exception) => { let exception = v8::Local::new(scope, exception); exception_to_err_result::<()>(scope, exception, in_promise, clear_error) .unwrap_err() } - ModuleError::Other(error) => error, + ModuleError::Core(error) => error, + ModuleError::Concrete(error) => CoreError::Module(error), } } } diff --git a/core/modules/recursive_load.rs b/core/modules/recursive_load.rs index ca443159f..2eb399d88 100644 --- a/core/modules/recursive_load.rs +++ b/core/modules/recursive_load.rs @@ -1,5 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::PubError; +use crate::error::CoreError; use crate::module_specifier::ModuleSpecifier; use crate::modules::map::ModuleMap; use crate::modules::ModuleError; @@ -127,7 +127,7 @@ impl RecursiveModuleLoad { load } - fn resolve_root(&self) -> Result { + fn resolve_root(&self) -> Result { match self.init { LoadInit::Main(ref specifier) => { self @@ -145,7 +145,7 @@ impl RecursiveModuleLoad { } } - pub(crate) async fn prepare(&self) -> Result<(), PubError> { + pub(crate) async fn prepare(&self) -> Result<(), CoreError> { let (module_specifier, maybe_referrer) = match self.init { LoadInit::Main(ref specifier) => { let spec = self.module_map_rc.resolve( @@ -176,7 +176,7 @@ impl RecursiveModuleLoad { .loader .prepare_load(&module_specifier, maybe_referrer, self.is_dynamic_import()) .await - .map_err(|e| PubError::ModuleLoader(Box::new(e))) + .map_err(|e| e.into()) } fn is_currently_loading_main_module(&self) -> bool { @@ -300,7 +300,7 @@ impl RecursiveModuleLoad { } impl Stream for RecursiveModuleLoad { - type Item = Result<(ModuleRequest, ModuleSource), PubError>; + type Item = Result<(ModuleRequest, ModuleSource), CoreError>; fn poll_next( self: Pin<&mut Self>, diff --git a/core/modules/tests.rs b/core/modules/tests.rs index 8f7d3a191..a5c083333 100644 --- a/core/modules/tests.rs +++ b/core/modules/tests.rs @@ -29,7 +29,6 @@ use crate::ModuleType; use crate::ResolutionKind; use crate::RuntimeOptions; use anyhow::bail; -use anyhow::Error; use deno_ops::op2; use futures::future::poll_fn; use futures::future::FutureExt; @@ -210,7 +209,7 @@ struct DelayedSourceCodeFuture { } impl Future for DelayedSourceCodeFuture { - type Output = Result; + type Output = Result; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { let inner = self.get_mut(); @@ -257,7 +256,7 @@ impl ModuleLoader for MockLoader { specifier: &str, referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { let referrer = if referrer == "." { "file:///" } else { @@ -780,7 +779,7 @@ fn test_custom_module_type_default() { }; match err { - ModuleError::Other(err) => { + ModuleError::Core(err) => { assert_eq!( err.to_string(), "Importing 'bytes' modules is not supported" @@ -797,12 +796,12 @@ fn test_custom_module_type_callback_synthetic() { module_type: Cow<'_, str>, _module_name: &FastString, module_code: ModuleSourceCode, - ) -> Result { + ) -> Result { if module_type != "bytes" { - return Err(JsNativeError::generic(format!( - "Can't load '{}' module", - module_type - ))); + return Err( + JsNativeError::generic(format!("Can't load '{}' module", module_type)) + .into(), + ); } let buf = match module_code { @@ -848,7 +847,7 @@ fn test_custom_module_type_callback_synthetic() { }; match err { - ModuleError::Other(err) => { + ModuleError::Core(err) => { assert_eq!(err.to_string(), "Can't load 'foo' module"); } _ => unreachable!(), @@ -881,12 +880,12 @@ fn test_custom_module_type_callback_computed() { module_type: Cow<'_, str>, module_name: &FastString, module_code: ModuleSourceCode, - ) -> Result { + ) -> Result { if module_type != "foobar" { - return Err(JsNativeError::generic(format!( - "Can't load '{}' module", - module_type - ))); + return Err( + JsNativeError::generic(format!("Can't load '{}' module", module_type)) + .into(), + ); } let buf = match module_code { @@ -1604,7 +1603,7 @@ async fn no_duplicate_loads() { specifier: &str, referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { let referrer = if referrer == "." { "file:///" } else { @@ -1675,7 +1674,7 @@ async fn import_meta_resolve_cb() { _loader: &dyn ModuleLoader, specifier: String, _referrer: String, - ) -> Result { + ) -> Result { if specifier == "foo" { return Ok(ModuleSpecifier::parse("foo:bar").unwrap()); } diff --git a/core/ops_builtin_v8.rs b/core/ops_builtin_v8.rs index a545b7bcd..834f82a36 100644 --- a/core/ops_builtin_v8.rs +++ b/core/ops_builtin_v8.rs @@ -3,7 +3,6 @@ use crate::error::is_instance_of_error; use crate::error::JsError; use crate::error::JsNativeError; use crate::error::OpError; -use crate::error::PubError; use crate::modules::script_origin; use crate::op2; use crate::ops_builtin::WasmStreamingResource; @@ -444,7 +443,7 @@ impl<'a> v8::ValueSerializerImpl for SerializeDeserialize<'a> { return; }; } - let error = v8::Exception::CustomError::type_error(scope, message); + let error = v8::Exception::type_error(scope, message); scope.throw_exception(error); } @@ -949,7 +948,7 @@ pub fn op_memory_usage(scope: &mut v8::HandleScope) -> MemoryUsage { pub fn op_set_wasm_streaming_callback( scope: &mut v8::HandleScope, #[global] cb: v8::Global, -) -> Result<(), PubError> { +) -> Result<(), OpError> { let context_state_rc = JsRealm::state_from_scope(scope); // The callback to pass to the v8 API has to be a unit type, so it can't // borrow or move any local variables. Therefore, we're storing the JS diff --git a/core/runtime/bindings.rs b/core/runtime/bindings.rs index 2e4c218a1..2da2618fe 100644 --- a/core/runtime/bindings.rs +++ b/core/runtime/bindings.rs @@ -13,8 +13,8 @@ use crate::error::callsite_fns; use crate::error::has_call_site; use crate::error::is_instance_of_error; use crate::error::throw_type_error; +use crate::error::CoreError; use crate::error::JsStackFrame; -use crate::error::PubError; use crate::extension_set::LoadedSources; use crate::modules::get_requested_module_type_from_attributes; use crate::modules::parse_import_attributes; @@ -306,7 +306,7 @@ pub(crate) fn initialize_deno_core_namespace<'s>( /// to function properly pub(crate) fn initialize_primordials_and_infra( scope: &mut v8::HandleScope, -) -> Result<(), PubError> { +) -> Result<(), CoreError> { for source_file in &CONTEXT_SETUP_SOURCES { let name = source_file.specifier.v8_string(scope); let source = source_file.source.v8_string(scope); @@ -314,10 +314,10 @@ pub(crate) fn initialize_primordials_and_infra( let origin = crate::modules::script_origin(scope, name, false, None); // TODO(bartlomieju): these two calls will panic if there's any problem in the JS code let script = v8::Script::compile(scope, source, Some(&origin)) - .ok_or_else(|| PubError::Parse(source_file.specifier))?; + .ok_or_else(|| CoreError::Parse(source_file.specifier))?; script .run(scope) - .ok_or_else(|| PubError::Execute(source_file.specifier))?; + .ok_or_else(|| CoreError::Execute(source_file.specifier))?; } Ok(()) diff --git a/core/runtime/exception_state.rs b/core/runtime/exception_state.rs index 270e57696..5247acbf8 100644 --- a/core/runtime/exception_state.rs +++ b/core/runtime/exception_state.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::error::exception_to_err_result; -use crate::error::PubError; +use crate::error::CoreError; use std::cell::Cell; use std::cell::RefCell; use std::collections::VecDeque; @@ -70,7 +70,7 @@ impl ExceptionState { pub(crate) fn check_exception_condition( &self, scope: &mut v8::HandleScope, - ) -> Result<(), PubError> { + ) -> Result<(), CoreError> { if self.has_dispatched_exception() { let undefined = v8::undefined(scope); exception_to_err_result( diff --git a/core/runtime/jsrealm.rs b/core/runtime/jsrealm.rs index c356b3baf..359f7349a 100644 --- a/core/runtime/jsrealm.rs +++ b/core/runtime/jsrealm.rs @@ -3,7 +3,7 @@ use super::exception_state::ExceptionState; #[cfg(test)] use super::op_driver::OpDriver; use crate::error::exception_to_err_result; -use crate::error::PubError; +use crate::error::CoreError; use crate::module_specifier::ModuleSpecifier; use crate::modules::script_origin; use crate::modules::IntoModuleCodeString; @@ -305,7 +305,7 @@ impl JsRealm { isolate: &mut v8::Isolate, name: impl IntoModuleName, source_code: impl IntoModuleCodeString, - ) -> Result, PubError> { + ) -> Result, CoreError> { let scope = &mut self.0.handle_scope(isolate); let source = source_code.into_module_code().v8_string(scope); @@ -343,7 +343,7 @@ impl JsRealm { &self, isolate: &mut v8::Isolate, module_id: ModuleId, - ) -> Result, PubError> { + ) -> Result, CoreError> { self .0 .module_map() @@ -379,7 +379,7 @@ impl JsRealm { isolate: &mut v8::Isolate, specifier: &ModuleSpecifier, code: Option, - ) -> Result { + ) -> Result { let module_map_rc = self.0.module_map(); if let Some(code) = code { let scope = &mut self.handle_scope(isolate); @@ -424,7 +424,7 @@ impl JsRealm { isolate: &mut v8::Isolate, specifier: &ModuleSpecifier, code: Option, - ) -> Result { + ) -> Result { let module_map_rc = self.0.module_map(); if let Some(code) = code { let specifier = specifier.to_owned(); @@ -467,7 +467,7 @@ impl JsRealm { isolate: &mut v8::Isolate, module_specifier: ModuleName, code: ModuleCodeString, - ) -> Result, PubError> { + ) -> Result, CoreError> { let module_map_rc = self.0.module_map(); let scope = &mut self.handle_scope(isolate); module_map_rc.lazy_load_es_module_with_code( diff --git a/core/runtime/jsruntime.rs b/core/runtime/jsruntime.rs index 9a0ab01a5..29cde8450 100644 --- a/core/runtime/jsruntime.rs +++ b/core/runtime/jsruntime.rs @@ -14,8 +14,8 @@ use super::SnapshottedData; use crate::ascii_str; use crate::ascii_str_include; use crate::error::exception_to_err_result; +use crate::error::CoreError; use crate::error::JsError; -use crate::error::PubError; use crate::extension_set; use crate::extension_set::LoadedSources; use crate::extensions::GlobalObjectMiddlewareFn; @@ -266,7 +266,7 @@ impl InitMode { #[derive(Default)] struct PromiseFuture { - resolved: Cell, PubError>>>, + resolved: Cell, CoreError>>>, waker: Cell>, } @@ -274,7 +274,7 @@ struct PromiseFuture { struct RcPromiseFuture(Rc); impl RcPromiseFuture { - pub fn new(res: Result, PubError>) -> Self { + pub fn new(res: Result, CoreError>) -> Self { Self(Rc::new(PromiseFuture { resolved: Some(res).into(), ..Default::default() @@ -283,7 +283,7 @@ impl RcPromiseFuture { } impl Future for RcPromiseFuture { - type Output = Result, PubError>; + type Output = Result, CoreError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.get_mut(); if let Some(resolved) = this.0.resolved.take() { @@ -727,7 +727,7 @@ impl JsRuntime { /// Only constructor, configuration is done through `options`. /// Returns an error if the runtime cannot be initialized. - pub fn try_new(mut options: RuntimeOptions) -> Result { + pub fn try_new(mut options: RuntimeOptions) -> Result { setup::init_v8( options.v8_platform.take(), cfg!(test), @@ -774,7 +774,7 @@ impl JsRuntime { fn new_inner( mut options: RuntimeOptions, will_snapshot: bool, - ) -> Result { + ) -> Result { let init_mode = InitMode::from_options(&options); let mut extensions = std::mem::take(&mut options.extensions); let mut isolate_allocations = IsolateAllocations::default(); @@ -1230,14 +1230,12 @@ impl JsRuntime { scope, global, ); - let mod_id = module_map - .new_synthetic_module( - scope, - VIRTUAL_OPS_MODULE_NAME, - crate::ModuleType::JavaScript, - synthetic_module_exports, - ) - .unwrap(); + let mod_id = module_map.new_synthetic_module( + scope, + VIRTUAL_OPS_MODULE_NAME, + crate::ModuleType::JavaScript, + synthetic_module_exports, + ); module_map.mod_evaluate_sync(scope, mod_id).unwrap(); } @@ -1252,7 +1250,7 @@ impl JsRuntime { realm: &JsRealm, module_map: &Rc, files_loaded: &mut Vec<&'static str>, - ) -> Result<(), PubError> { + ) -> Result<(), CoreError> { let scope = &mut realm.handle_scope(self.v8_isolate()); for source_file in &BUILTIN_SOURCES { @@ -1261,10 +1259,10 @@ impl JsRuntime { let origin = script_origin(scope, name, false, None); let script = v8::Script::compile(scope, source, Some(&origin)) - .ok_or_else(|| PubError::Parse(source_file.specifier))?; + .ok_or_else(|| CoreError::Parse(source_file.specifier))?; script .run(scope) - .ok_or_else(|| PubError::Execute(source_file.specifier))?; + .ok_or_else(|| CoreError::Execute(source_file.specifier))?; } for file_source in &BUILTIN_ES_MODULES { @@ -1286,7 +1284,7 @@ impl JsRuntime { realm: &JsRealm, module_map: &Rc, loaded_sources: LoadedSources, - ) -> Result<(), PubError> { + ) -> Result<(), CoreError> { // First, add all the lazy ESM for source in loaded_sources.lazy_esm { module_map.add_lazy_loaded_esm_source(source.specifier, source.code); @@ -1324,7 +1322,7 @@ impl JsRuntime { let Some(mod_id) = module_map.get_id(&specifier, RequestedModuleType::None) else { - return Err(PubError::MissingFromModuleMap(specifier.to_string())); + return Err(CoreError::MissingFromModuleMap(specifier.to_string())); }; let isolate = self.v8_isolate(); @@ -1354,7 +1352,7 @@ impl JsRuntime { realm: &JsRealm, module_map: &Rc, loaded_sources: LoadedSources, - ) -> Result<(), PubError> { + ) -> Result<(), CoreError> { futures::executor::block_on(self.init_extension_js_inner( realm, module_map, @@ -1486,7 +1484,7 @@ impl JsRuntime { &mut self, name: &'static str, source_code: impl IntoModuleCodeString, - ) -> Result, PubError> { + ) -> Result, CoreError> { let isolate = &mut self.inner.v8_isolate; self.inner.main_realm.execute_script( isolate, @@ -1505,7 +1503,7 @@ impl JsRuntime { pub fn call( &mut self, function: &v8::Global, - ) -> impl Future, PubError>> { + ) -> impl Future, CoreError>> { self.call_with_args(function, &[]) } @@ -1519,7 +1517,7 @@ impl JsRuntime { pub fn scoped_call( scope: &mut v8::HandleScope, function: &v8::Global, - ) -> impl Future, PubError>> { + ) -> impl Future, CoreError>> { Self::scoped_call_with_args(scope, function, &[]) } @@ -1534,7 +1532,7 @@ impl JsRuntime { &mut self, function: &v8::Global, args: &[v8::Global], - ) -> impl Future, PubError>> { + ) -> impl Future, CoreError>> { let scope = &mut self.handle_scope(); Self::scoped_call_with_args(scope, function, args) } @@ -1550,7 +1548,7 @@ impl JsRuntime { scope: &mut v8::HandleScope, function: &v8::Global, args: &[v8::Global], - ) -> impl Future, PubError>> { + ) -> impl Future, CoreError>> { let scope = &mut v8::TryCatch::new(scope); let cb = function.open(scope); let this = v8::undefined(scope).into(); @@ -1592,7 +1590,7 @@ impl JsRuntime { pub async fn call_and_await( &mut self, function: &v8::Global, - ) -> Result, PubError> { + ) -> Result, CoreError> { let call = self.call(function); self .with_event_loop_promise(call, PollEventLoopOptions::default()) @@ -1607,7 +1605,7 @@ impl JsRuntime { &mut self, function: &v8::Global, args: &[v8::Global], - ) -> Result, PubError> { + ) -> Result, CoreError> { let call = self.call_with_args(function, args); self .with_event_loop_promise(call, PollEventLoopOptions::default()) @@ -1621,7 +1619,7 @@ impl JsRuntime { pub fn get_module_namespace( &mut self, module_id: ModuleId, - ) -> Result, PubError> { + ) -> Result, CoreError> { let isolate = &mut self.inner.v8_isolate; self .inner @@ -1668,7 +1666,7 @@ impl JsRuntime { fn pump_v8_message_loop( &mut self, scope: &mut v8::HandleScope, - ) -> Result<(), PubError> { + ) -> Result<(), CoreError> { while v8::Platform::pump_message_loop( &v8::V8::get_current_platform(), scope, @@ -1715,7 +1713,7 @@ impl JsRuntime { pub fn resolve( &mut self, promise: v8::Global, - ) -> impl Future, PubError>> { + ) -> impl Future, CoreError>> { let scope = &mut self.handle_scope(); Self::scoped_resolve(scope, promise) } @@ -1727,7 +1725,7 @@ impl JsRuntime { pub fn scoped_resolve( scope: &mut v8::HandleScope, promise: v8::Global, - ) -> impl Future, PubError>> { + ) -> impl Future, CoreError>> { let promise = v8::Local::new(scope, promise); if !promise.is_promise() { return RcPromiseFuture::new(Ok(v8::Global::new(scope, promise))); @@ -1744,7 +1742,7 @@ impl JsRuntime { pub async fn resolve_value( &mut self, global: v8::Global, - ) -> Result, PubError> { + ) -> Result, CoreError> { let resolve = self.resolve(global); self .with_event_loop_promise(resolve, PollEventLoopOptions::default()) @@ -1782,7 +1780,7 @@ impl JsRuntime { pub async fn run_event_loop( &mut self, poll_options: PollEventLoopOptions, - ) -> Result<(), PubError> { + ) -> Result<(), CoreError> { poll_fn(|cx| self.poll_event_loop(cx, poll_options)).await } @@ -1794,9 +1792,9 @@ impl JsRuntime { &mut self, mut fut: impl Future> + Unpin + 'fut, poll_options: PollEventLoopOptions, - ) -> Result + ) -> Result where - PubError: From, + CoreError: From, { // Manually implement tokio::select poll_fn(|cx| { @@ -1808,7 +1806,7 @@ impl JsRuntime { if let Poll::Ready(t) = fut.poll_unpin(cx) { return Poll::Ready(t.map_err(|e| e.into())); } - return Poll::Ready(Err(PubError::PendingPromiseResolution)); + return Poll::Ready(Err(CoreError::PendingPromiseResolution)); } Poll::Pending }) @@ -1825,9 +1823,9 @@ impl JsRuntime { &mut self, mut fut: impl Future> + Unpin + 'fut, poll_options: PollEventLoopOptions, - ) -> Result + ) -> Result where - PubError: From, + CoreError: From, { // Manually implement tokio::select poll_fn(|cx| { @@ -1853,7 +1851,7 @@ impl JsRuntime { &mut self, cx: &mut Context, poll_options: PollEventLoopOptions, - ) -> Poll> { + ) -> Poll> { // SAFETY: We know this isolate is valid and non-null at this time let mut isolate_scope = v8::HandleScope::new(unsafe { &mut *self.v8_isolate_ptr() }); @@ -1868,7 +1866,7 @@ impl JsRuntime { cx: &mut Context, scope: &mut v8::HandleScope, poll_options: PollEventLoopOptions, - ) -> Poll> { + ) -> Poll> { let has_inspector = self.inner.state.has_inspector.get(); self.inner.state.waker.register(cx.waker()); @@ -1995,7 +1993,7 @@ impl JsRuntime { fn find_and_report_stalled_level_await_in_any_realm( scope: &mut v8::HandleScope, inner_realm: &JsRealmInner, -) -> PubError { +) -> CoreError { let module_map = inner_realm.module_map(); let messages = module_map.find_stalled_top_level_await(scope); @@ -2063,7 +2061,7 @@ impl JsRuntimeForSnapshot { /// Try to create a new runtime, returning an error if the process fails. pub fn try_new( mut options: RuntimeOptions, - ) -> Result { + ) -> Result { setup::init_v8( options.v8_platform.take(), true, @@ -2319,7 +2317,7 @@ impl JsRuntime { pub fn mod_evaluate( &mut self, id: ModuleId, - ) -> impl Future> { + ) -> impl Future> { let isolate = &mut self.inner.v8_isolate; let realm = &self.inner.main_realm; let scope = &mut realm.handle_scope(isolate); @@ -2342,7 +2340,7 @@ impl JsRuntime { &mut self, specifier: &ModuleSpecifier, code: impl IntoModuleCodeString, - ) -> Result { + ) -> Result { let isolate = &mut self.inner.v8_isolate; self .inner @@ -2366,7 +2364,7 @@ impl JsRuntime { pub async fn load_main_es_module( &mut self, specifier: &ModuleSpecifier, - ) -> Result { + ) -> Result { let isolate = &mut self.inner.v8_isolate; self .inner @@ -2392,7 +2390,7 @@ impl JsRuntime { &mut self, specifier: &ModuleSpecifier, code: impl IntoModuleCodeString, - ) -> Result { + ) -> Result { let isolate = &mut self.inner.v8_isolate; self .inner @@ -2416,7 +2414,7 @@ impl JsRuntime { pub async fn load_side_es_module( &mut self, specifier: &ModuleSpecifier, - ) -> Result { + ) -> Result { let isolate = &mut self.inner.v8_isolate; self .inner @@ -2436,7 +2434,7 @@ impl JsRuntime { &mut self, specifier: impl IntoModuleName, code: impl IntoModuleCodeString, - ) -> Result, PubError> { + ) -> Result, CoreError> { let isolate = &mut self.inner.v8_isolate; self.inner.main_realm.lazy_load_es_module_with_code( isolate, @@ -2450,7 +2448,7 @@ impl JsRuntime { scope: &mut v8::HandleScope, context_state: &ContextState, exception_state: &ExceptionState, - ) -> Result { + ) -> Result { let mut dispatched_ops = false; // Poll any pending task spawner tasks. Note that we need to poll separately because otherwise diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index c067f8df8..20a3d7fa6 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -265,6 +265,17 @@ pub struct OpError { error_code: Option<&'static str>, } +impl std::fmt::Display for OpError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}: {}", + self.error.get_class(), + self.error.get_message() + ) + } +} + impl JsErrorClass for OpError { fn get_class(&self) -> &'static str { self.error.get_class() @@ -287,7 +298,7 @@ impl From for OpError { impl From for OpError { fn from(err: anyhow::Error) -> Self { match err.downcast::() { - Ok(err) => err.into(), + Ok(err) => OpError::from(err), Err(_) => todo!(), } } @@ -298,12 +309,9 @@ impl Serialize for OpError { where S: serde::Serializer, { - let class_name = self.error.get_class(); - let message = self.error.get_message(); - let mut serde_state = serializer.serialize_struct("OpError", 3)?; - serde_state.serialize_field("$err_class_name", class_name)?; - serde_state.serialize_field("message", &message)?; + serde_state.serialize_field("$err_class_name", self.error.get_class())?; + serde_state.serialize_field("message", &self.error.get_message())?; serde_state.serialize_field("code", &self.error_code)?; serde_state.end() } diff --git a/core/runtime/ops.rs b/core/runtime/ops.rs index a919f60c2..e0d710280 100644 --- a/core/runtime/ops.rs +++ b/core/runtime/ops.rs @@ -531,8 +531,7 @@ mod tests { use crate::OpState; use crate::RuntimeOptions; use crate::ToV8; - use anyhow::bail; - use anyhow::Error; + use anyhow::anyhow; use bytes::BytesMut; use futures::Future; use serde::Deserialize; @@ -2154,9 +2153,9 @@ mod tests { } #[op2(async)] - pub async fn op_async_sleep_error() -> Result<(), Error> { + pub async fn op_async_sleep_error() -> Result<(), OpError> { tokio::time::sleep(Duration::from_millis(500)).await; - bail!("whoops") + Err(anyhow!("whoops").into()) } #[tokio::test] @@ -2172,13 +2171,13 @@ mod tests { } #[op2(async(deferred), fast)] - pub async fn op_async_deferred_success() -> Result { + pub async fn op_async_deferred_success() -> Result { Ok(42) } #[op2(async(deferred), fast)] - pub async fn op_async_deferred_error() -> Result<(), Error> { - bail!("whoops") + pub async fn op_async_deferred_error() -> Result<(), OpError> { + Err(anyhow!("whoops").into()) } #[tokio::test] @@ -2200,13 +2199,13 @@ mod tests { } #[op2(async(lazy), fast)] - pub async fn op_async_lazy_success() -> Result { + pub async fn op_async_lazy_success() -> Result { Ok(42) } #[op2(async(lazy), fast)] - pub async fn op_async_lazy_error() -> Result<(), Error> { - bail!("whoops") + pub async fn op_async_lazy_error() -> Result<(), OpError> { + Err(anyhow!("whoops").into()) } #[tokio::test] @@ -2231,7 +2230,7 @@ mod tests { #[op2(async)] pub fn op_async_result_impl( mode: u8, - ) -> Result>, Error> { + ) -> Result>, OpError> { if mode == 0 { return Err(JsNativeError::generic("early exit").into()); } diff --git a/core/runtime/snapshot.rs b/core/runtime/snapshot.rs index 7d0f0c03c..d0188d1f8 100644 --- a/core/runtime/snapshot.rs +++ b/core/runtime/snapshot.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::PubError; +use crate::error::CoreError; use crate::modules::ModuleMapSnapshotData; use crate::Extension; use crate::JsRuntimeForSnapshot; @@ -129,7 +129,7 @@ pub struct CreateSnapshotOutput { pub fn create_snapshot( create_snapshot_options: CreateSnapshotOptions, warmup_script: Option<&'static str>, -) -> Result { +) -> Result { let mut mark = Instant::now(); #[allow(clippy::print_stdout)] { diff --git a/core/runtime/tests/error.rs b/core/runtime/tests/error.rs index b5cd32e7b..e320abf85 100644 --- a/core/runtime/tests/error.rs +++ b/core/runtime/tests/error.rs @@ -1,22 +1,18 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::custom_error; use crate::error::JsError; +use crate::error::JsNativeError; +use crate::error::OpError; use crate::op2; use crate::JsRuntime; use crate::RuntimeOptions; -use anyhow::Error; use futures::future::poll_fn; use std::task::Poll; #[tokio::test] async fn test_error_builder() { #[op2(fast)] - fn op_err() -> Result<(), Error> { - Err(custom_error("DOMExceptionOperationError", "abc")) - } - - pub fn get_error_class_name(_: &Error) -> &'static str { - "DOMExceptionOperationError" + fn op_err() -> Result<(), OpError> { + Err(JsNativeError::new("DOMExceptionOperationError", "abc").into()) } deno_core::extension!(test_ext, ops = [op_err]); diff --git a/core/runtime/tests/misc.rs b/core/runtime/tests/misc.rs index 996dc6d74..942fb5709 100644 --- a/core/runtime/tests/misc.rs +++ b/core/runtime/tests/misc.rs @@ -5,7 +5,6 @@ use crate::modules::StaticModuleLoader; use crate::runtime::tests::setup; use crate::runtime::tests::Mode; use crate::*; -use anyhow::Error; use cooked_waker::IntoWaker; use cooked_waker::Wake; use cooked_waker::WakeRef; @@ -86,7 +85,7 @@ async fn test_wakers_for_async_ops() { static STATE: AtomicI8 = AtomicI8::new(0); #[op2(async)] - async fn op_async_sleep() -> Result<(), Error> { + async fn op_async_sleep() -> Result<(), OpError> { STATE.store(1, Ordering::SeqCst); tokio::time::sleep(std::time::Duration::from_millis(1)).await; STATE.store(2, Ordering::SeqCst); @@ -649,7 +648,7 @@ fn test_is_proxy() { #[tokio::test] async fn test_set_macrotask_callback_set_next_tick_callback() { #[op2(async)] - async fn op_async_sleep() -> Result<(), Error> { + async fn op_async_sleep() -> Result<(), OpError> { // Future must be Poll::Pending on first call tokio::time::sleep(std::time::Duration::from_millis(1)).await; Ok(()) @@ -967,9 +966,9 @@ async fn test_stalled_tla() { #[tokio::test] async fn test_dynamic_import_module_error_stack() { #[op2(async)] - async fn op_async_error() -> Result<(), Error> { + async fn op_async_error() -> Result<(), OpError> { tokio::time::sleep(std::time::Duration::from_millis(1)).await; - Err(crate::error::JsNativeError::type_error("foo")) + Err(error::JsNativeError::type_error("foo").into()) } deno_core::extension!(test_ext, ops = [op_async_error]); let loader = StaticModuleLoader::new([ @@ -1193,7 +1192,7 @@ async fn task_spawner_cross_thread_blocking() { #[tokio::test] async fn terminate_execution_run_event_loop_js() { #[op2(async)] - async fn op_async_sleep() -> Result<(), Error> { + async fn op_async_sleep() -> Result<(), OpError> { tokio::time::sleep(std::time::Duration::from_millis(100)).await; Ok(()) } diff --git a/core/runtime/tests/ops.rs b/core/runtime/tests/ops.rs index e827ab97e..752725ef7 100644 --- a/core/runtime/tests/ops.rs +++ b/core/runtime/tests/ops.rs @@ -2,14 +2,13 @@ #![allow(clippy::print_stdout, clippy::print_stderr, clippy::unused_async)] -use crate::error::{OpError}; +use crate::error::OpError; use crate::extensions::OpDecl; use crate::modules::StaticModuleLoader; use crate::runtime::tests::setup; use crate::runtime::tests::Mode; use crate::*; -use anyhow::{anyhow}; -use anyhow::Error; +use anyhow::anyhow; use futures::Future; use pretty_assertions::assert_eq; use std::cell::RefCell; @@ -25,7 +24,7 @@ async fn test_async_opstate_borrow() { #[op2(async)] async fn op_async_borrow( op_state: Rc>, - ) -> Result<(), Error> { + ) -> Result<(), OpError> { let n = { let op_state = op_state.borrow(); let inner_state = op_state.borrow::(); @@ -63,7 +62,7 @@ async fn test_sync_op_serialize_object_with_numbers_as_keys() { #[op2] fn op_sync_serialize_object_with_numbers_as_keys( #[serde] value: serde_json::Value, - ) -> Result<(), Error> { + ) -> Result<(), OpError> { assert_eq!( value.to_string(), r#"{"lines":{"100":{"unit":"m"},"200":{"unit":"cm"}}}"# @@ -105,7 +104,7 @@ async fn test_async_op_serialize_object_with_numbers_as_keys() { #[op2(async)] async fn op_async_serialize_object_with_numbers_as_keys( #[serde] value: serde_json::Value, - ) -> Result<(), Error> { + ) -> Result<(), OpError> { assert_eq!( value.to_string(), r#"{"lines":{"100":{"unit":"m"},"200":{"unit":"cm"}}}"# @@ -147,7 +146,7 @@ async fn test_async_op_serialize_object_with_numbers_as_keys() { fn test_op_return_serde_v8_error() { #[op2] #[serde] - fn op_err() -> Result, anyhow::Error> { + fn op_err() -> Result, OpError> { Ok([(1, 2), (3, 4)].into_iter().collect()) // Maps can't have non-string keys in serde_v8 } @@ -173,7 +172,7 @@ fn test_op_high_arity() { #[number] x2: i64, #[number] x3: i64, #[number] x4: i64, - ) -> Result { + ) -> Result { Ok(x1 + x2 + x3 + x4) } @@ -193,7 +192,7 @@ fn test_op_high_arity() { fn test_op_disabled() { #[op2(fast)] #[number] - fn op_foo() -> Result { + fn op_foo() -> Result { Ok(42) } @@ -216,7 +215,7 @@ fn test_op_disabled() { #[test] fn test_op_detached_buffer() { #[op2] - fn op_sum_take(#[buffer(detach)] b: JsBuffer) -> Result { + fn op_sum_take(#[buffer(detach)] b: JsBuffer) -> Result { Ok(b.as_ref().iter().clone().map(|x| *x as u32).sum()) } @@ -224,7 +223,7 @@ fn test_op_detached_buffer() { #[buffer] fn op_boomerang( #[buffer(detach)] b: JsBuffer, - ) -> Result { + ) -> Result { Ok(b) } @@ -298,14 +297,14 @@ fn duplicate_op_names() { #[op2] #[string] - pub fn op_test() -> Result { + pub fn op_test() -> Result { Ok(String::from("Test")) } } #[op2] #[string] - pub fn op_test() -> Result { + pub fn op_test() -> Result { Ok(String::from("Test")) } @@ -320,13 +319,13 @@ fn duplicate_op_names() { fn ops_in_js_have_proper_names() { #[op2] #[string] - fn op_test_sync() -> Result { + fn op_test_sync() -> Result { Ok(String::from("Test")) } #[op2(async)] #[string] - async fn op_test_async() -> Result { + async fn op_test_async() -> Result { Ok(String::from("Test")) } diff --git a/core/runtime/tests/snapshot.rs b/core/runtime/tests/snapshot.rs index a7f0ce487..a33a8171a 100644 --- a/core/runtime/tests/snapshot.rs +++ b/core/runtime/tests/snapshot.rs @@ -1,16 +1,15 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +use self::runtime::create_snapshot; +use self::runtime::CreateSnapshotOptions; +use crate::error::OpError; use crate::modules::ModuleInfo; use crate::modules::RequestedModuleType; use crate::runtime::NO_OF_BUILTIN_MODULES; use crate::*; -use anyhow::Error; use std::borrow::Cow; use std::cell::RefCell; use std::rc::Rc; -use self::runtime::create_snapshot; -use self::runtime::CreateSnapshotOptions; - #[test] fn will_snapshot() { let snapshot = { @@ -233,7 +232,7 @@ fn es_snapshot() { #[op2] #[string] - fn op_test() -> Result { + fn op_test() -> Result { Ok(String::from("test")) } let mut runtime = JsRuntimeForSnapshot::new(RuntimeOptions { diff --git a/core/source_map.rs b/core/source_map.rs index 316eac77d..4a84fa669 100644 --- a/core/source_map.rs +++ b/core/source_map.rs @@ -165,7 +165,6 @@ impl SourceMapper { #[cfg(test)] mod tests { - use anyhow::Error; use url::Url; use super::*; @@ -191,7 +190,7 @@ mod tests { _specifier: &str, _referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { unreachable!() } diff --git a/testing/checkin/runner/mod.rs b/testing/checkin/runner/mod.rs index f17574e50..d91cb679b 100644 --- a/testing/checkin/runner/mod.rs +++ b/testing/checkin/runner/mod.rs @@ -5,7 +5,6 @@ use self::ops_worker::WorkerHostSide; use self::ts_module_loader::maybe_transpile_source; use anyhow::anyhow; use anyhow::Context; -use anyhow::Error; use deno_core::v8; use deno_core::CrossIsolateStore; use deno_core::CustomModuleEvaluationKind; @@ -135,7 +134,7 @@ pub fn create_runtime_from_snapshot( runtime } -fn run_async(f: impl Future>) { +fn run_async(f: impl Future>) { let tokio = tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -167,7 +166,7 @@ fn custom_module_evaluation_cb( module_type: Cow<'_, str>, module_name: &FastString, code: ModuleSourceCode, -) -> Result { +) -> Result { match &*module_type { "bytes" => bytes_module(scope, code), "text" => text_module(scope, module_name, code), @@ -182,7 +181,7 @@ fn custom_module_evaluation_cb( fn bytes_module( scope: &mut v8::HandleScope, code: ModuleSourceCode, -) -> Result { +) -> Result { // FsModuleLoader always returns bytes. let ModuleSourceCode::Bytes(buf) = code else { unreachable!() @@ -203,7 +202,7 @@ fn text_module( scope: &mut v8::HandleScope, module_name: &FastString, code: ModuleSourceCode, -) -> Result { +) -> Result { // FsModuleLoader always returns bytes. let ModuleSourceCode::Bytes(buf) = code else { unreachable!() diff --git a/testing/checkin/runner/ops_error.rs b/testing/checkin/runner/ops_error.rs index 2ffd40093..ec5050604 100644 --- a/testing/checkin/runner/ops_error.rs +++ b/testing/checkin/runner/ops_error.rs @@ -1,26 +1,27 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use anyhow::anyhow; -use anyhow::Error; use deno_core::error::JsNativeError; +use deno_core::error::OpError; use deno_core::op2; +use deno_core::Op; #[op2(async)] -pub async fn op_async_throw_error_eager() -> Result<(), Error> { +pub async fn op_async_throw_error_eager() -> Result<(), OpError> { Err(JsNativeError::type_error("Error").into()) } #[op2(async(deferred), fast)] -pub async fn op_async_throw_error_deferred() -> Result<(), Error> { +pub async fn op_async_throw_error_deferred() -> Result<(), OpError> { Err(JsNativeError::type_error("Error").into()) } #[op2(async(lazy), fast)] -pub async fn op_async_throw_error_lazy() -> Result<(), Error> { +pub async fn op_async_throw_error_lazy() -> Result<(), OpError> { Err(JsNativeError::type_error("Error").into()) } #[op2(fast)] -pub fn op_error_custom_sync(#[string] message: String) -> Result<(), Error> { +pub fn op_error_custom_sync(#[string] message: String) -> Result<(), OpError> { Err(JsNativeError::bad_resource(message).into()) } @@ -28,14 +29,14 @@ pub fn op_error_custom_sync(#[string] message: String) -> Result<(), Error> { pub fn op_error_context_sync( #[string] message: String, #[string] context: String, -) -> Result<(), Error> { - Err(anyhow!(message).context(context)) +) -> Result<(), OpError> { + Err(anyhow!(message).context(context).into()) } #[op2(async)] pub async fn op_error_context_async( #[string] message: String, #[string] context: String, -) -> Result<(), Error> { - Err(anyhow!(message).context(context)) +) -> Result<(), OpError> { + Err(anyhow!(message).context(context).into()) } diff --git a/testing/checkin/runner/ops_io.rs b/testing/checkin/runner/ops_io.rs index 6bd53a11c..a4a3770b6 100644 --- a/testing/checkin/runner/ops_io.rs +++ b/testing/checkin/runner/ops_io.rs @@ -1,5 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use anyhow::Error; +use deno_core::error::OpError; use deno_core::op2; use deno_core::AsyncRefCell; use deno_core::BufView; @@ -92,7 +92,7 @@ impl Resource for FileResource { pub async fn op_file_open( #[string] path: String, op_state: Rc>, -) -> Result { +) -> Result { let tokio_file = tokio::fs::OpenOptions::new() .read(true) .write(false) diff --git a/testing/checkin/runner/ops_worker.rs b/testing/checkin/runner/ops_worker.rs index 4d0fbedf0..d1274268b 100644 --- a/testing/checkin/runner/ops_worker.rs +++ b/testing/checkin/runner/ops_worker.rs @@ -1,7 +1,9 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +use super::create_runtime; +use super::run_async; +use super::Output; use anyhow::anyhow; -use anyhow::bail; -use anyhow::Error; +use deno_core::error::OpError; use deno_core::op2; use deno_core::url::Url; use deno_core::v8::IsolateHandle; @@ -21,10 +23,6 @@ use tokio::sync::mpsc::UnboundedSender; use tokio::sync::watch; use tokio::sync::Mutex; -use super::create_runtime; -use super::run_async; -use super::Output; - /// Our cppgc object. pub struct WorkerControl { worker_channel: WorkerChannel, @@ -95,7 +93,7 @@ pub fn op_worker_spawn( #[state] output: &Output, #[string] base_url: String, #[string] main_script: String, -) -> Result { +) -> Result { let output = output.clone(); let close_watcher = this_worker.close_watcher.clone(); let (init_send, init_recv) = channel(); @@ -126,7 +124,7 @@ async fn run_worker_task( base_url: String, main_script: String, mut shutdown_rx: UnboundedReceiver<()>, -) -> Result<(), Error> { +) -> Result<(), OpError> { let url = Url::try_from(base_url.as_str())?.join(&main_script)?; let module = runtime.load_main_es_module(&url).await?; let f = runtime.mod_evaluate(module); @@ -160,7 +158,7 @@ async fn run_worker_task( pub fn op_worker_send( #[cppgc] worker: &WorkerControl, #[string] message: String, -) -> Result<(), Error> { +) -> Result<(), OpError> { worker.worker_channel.tx.send(message)?; Ok(()) } @@ -175,14 +173,14 @@ pub async fn op_worker_recv(#[cppgc] worker: &WorkerControl) -> Option { #[cppgc] pub fn op_worker_parent( state: Rc>, -) -> Result { +) -> Result { let state = state.borrow_mut(); let worker: &Worker = state.borrow(); let (Some(worker_channel), Some(close_watcher)) = ( worker.parent_channel.lock().unwrap().take(), worker.parent_close_watcher.lock().unwrap().take(), ) else { - bail!("No parent worker is available") + return Err(anyhow!("No parent worker is available").into()); }; Ok(WorkerControl { worker_channel, diff --git a/testing/checkin/runner/testing.rs b/testing/checkin/runner/testing.rs index 6665744c4..f1a6a56be 100644 --- a/testing/checkin/runner/testing.rs +++ b/testing/checkin/runner/testing.rs @@ -1,6 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use anyhow::bail; -use anyhow::Error; use deno_core::op2; use deno_core::url::Url; use deno_core::v8; @@ -57,7 +56,7 @@ pub fn run_integration_test(test: &str) { async fn run_integration_test_task( mut runtime: JsRuntime, test: String, -) -> Result<(), Error> { +) -> Result<(), anyhow::Error> { let test_dir = get_test_dir(&["integration", &test]); let url = get_test_url(&test_dir, &test)?; let module = runtime.load_main_es_module(&url).await?; @@ -107,7 +106,7 @@ pub fn run_unit_test(test: &str) { async fn run_unit_test_task( mut runtime: JsRuntime, test: String, -) -> Result<(), Error> { +) -> Result<(), anyhow::Error> { let test_dir = get_test_dir(&["unit"]); let url = get_test_url(&test_dir, &test)?; let module = runtime.load_main_es_module(&url).await?; @@ -144,7 +143,7 @@ fn get_test_dir(dirs: &[&str]) -> PathBuf { test_dir.to_owned() } -fn get_test_url(test_dir: &Path, test: &str) -> Result { +fn get_test_url(test_dir: &Path, test: &str) -> Result { let mut path = None; for extension in ["ts", "js", "nocompile"] { let test_path = test_dir.join(format!("{test}.{extension}")); From e947204a96afe90f7fb386babe15db63065bcb3b Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 23 Aug 2024 15:26:19 +0200 Subject: [PATCH 07/52] fixes --- core/async_cancel.rs | 29 +++---- core/error.rs | 116 +++++++++++++++++++++------ core/lib.rs | 1 + core/module_specifier.rs | 5 -- core/modules/loaders.rs | 22 ++++- core/modules/map.rs | 10 +-- core/modules/mod.rs | 4 - core/runtime/op_driver/op_results.rs | 9 --- core/runtime/tests/ops.rs | 4 +- 9 files changed, 129 insertions(+), 71 deletions(-) diff --git a/core/async_cancel.rs b/core/async_cancel.rs index fdcb038f3..c54150a9f 100644 --- a/core/async_cancel.rs +++ b/core/async_cancel.rs @@ -107,7 +107,7 @@ pub struct TryCancelable { impl Future for TryCancelable where - F: Future>, + F: Future>, Canceled: Into, { type Output = F::Output; @@ -124,7 +124,7 @@ where impl FusedFuture for TryCancelable where - F: Future>, + F: Future>, Canceled: Into, { fn is_terminated(&self) -> bool { @@ -144,7 +144,7 @@ where impl Future for Abortable where - F: Future + Unpin, + F: Future + Unpin, { type Output = Result; @@ -171,7 +171,7 @@ where impl FusedFuture for Abortable where - F: Future> + Unpin, + F: Future> + Unpin, Canceled: Into, { fn is_terminated(&self) -> bool { @@ -222,7 +222,8 @@ impl CancelTryFuture for F where F: TryFuture, Canceled: Into, -{} +{ +} #[derive(Copy, Clone, Default, Debug, Eq, Hash, PartialEq)] pub struct Canceled; @@ -683,7 +684,7 @@ mod tests { fn box_fused<'a, F: FusedFuture + 'a>( future: F, - ) -> Pin + 'a>> { + ) -> Pin + 'a>> { Box::pin(future) } @@ -698,7 +699,7 @@ mod tests { Poll::Pending } }) - .await + .await } #[test] @@ -882,7 +883,7 @@ mod tests { tokio::task::yield_now().await; 1_u8 }) - .or_abort(&cancel_handle); + .or_abort(&cancel_handle); cancel_handle.cancel(); for _ in 0..10 { @@ -917,8 +918,8 @@ mod tests { yield_now().await; unreachable!(); } - .or_cancel(&cancel_handle) - .await; + .or_cancel(&cancel_handle) + .await; assert_eq!(result.unwrap_err(), Canceled); }) } @@ -939,8 +940,8 @@ mod tests { pending!(); unreachable!(); } - .or_cancel(&cancel_handle) - .await; + .or_cancel(&cancel_handle) + .await; assert_eq!(result.unwrap_err(), Canceled); }); } @@ -960,8 +961,8 @@ mod tests { cancel_handle.cancel(); Ok::<_, io::Error>("done") } - .try_or_cancel(&cancel_handle) - .await; + .try_or_cancel(&cancel_handle) + .await; assert_eq!(result.unwrap(), "done"); }); } diff --git a/core/error.rs b/core/error.rs index b1d7d1b42..4ab195532 100644 --- a/core/error.rs +++ b/core/error.rs @@ -46,12 +46,16 @@ pub enum CoreError { .0.iter().map(|s| format!(" - {}\n", s)).collect::>().join("") )] NonEvaluatedModules(Vec), - #[error("not present in the module map")] + #[error("{0} not present in the module map")] MissingFromModuleMap(String), #[error(transparent)] ModuleLoader(Box), #[error("Could not execute {specifier}")] - CouldNotExecute { error: Box, specifier: String }, + CouldNotExecute { + #[source] + error: Box, + specifier: String, + }, #[error(transparent)] JsNativeError(#[from] JsNativeError), #[error(transparent)] @@ -62,12 +66,17 @@ pub enum CoreError { "Cannot evaluate module, because JavaScript execution has been terminated" )] ExecutionTerminated, - #[error("Promise resolution is still pending but the event loop has already resolved." + #[error("Promise resolution is still pending but the event loop has already resolved" )] PendingPromiseResolution, + #[error("Cannot evaluate dynamically imported module, because JavaScript execution has been terminated" + )] + EvaluateDynamicImportedModule, #[error(transparent)] Module(super::modules::ModuleConcreteError), #[error(transparent)] + DataError(#[from] v8::DataError), + #[error(transparent)] Other(anyhow::Error), } @@ -79,16 +88,82 @@ impl From for CoreError { pub trait JsErrorClass: Display + Debug + Send + Sync + 'static { fn get_class(&self) -> &'static str; - fn get_message(&self) -> Cow<'static, str>; + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } } -impl JsErrorClass for serde_v8::Error { +impl JsErrorClass for anyhow::Error { fn get_class(&self) -> &'static str { - "TypeError" + match self.downcast_ref::<&dyn JsErrorClass>() { + Some(err) => err.get_class(), + None => "Error", + } } fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() + match self.downcast_ref::<&dyn JsErrorClass>() { + Some(err) => err.get_message(), + None => self.to_string().into(), + } + } +} + +impl JsErrorClass for CoreError { + fn get_class(&self) -> &'static str { + match self { + CoreError::TLA(_) => todo!(), + CoreError::Js(_) => todo!(), + CoreError::Io(err) => err.get_class(), + CoreError::ExtensionTranspiler(err) => err.get_class(), + CoreError::Parse(_) => "Error", + CoreError::Execute(_) => "Error", + CoreError::UnusedModules(_) => "Error", + CoreError::NonEvaluatedModules(_) => "Error", + CoreError::MissingFromModuleMap(_) => "Error", + CoreError::ModuleLoader(err) => err.get_class(), + CoreError::CouldNotExecute { error, .. } => error.get_class(), + CoreError::JsNativeError(err) => err.get_class(), + CoreError::Url(err) => err.get_class(), + CoreError::FutureCanceled(_) => "Interrupted", + CoreError::ExecutionTerminated => "Error", + CoreError::PendingPromiseResolution => "Error", + CoreError::EvaluateDynamicImportedModule => "Error", + CoreError::Module(err) => err.get_class(), + CoreError::DataError(err) => err.get_class(), + CoreError::Other(err) => err.get_class(), + } + } + + fn get_message(&self) -> Cow<'static, str> { + match self { + CoreError::TLA(_) => todo!(), + CoreError::Js(_) => todo!(), + CoreError::Io(err) => err.get_message(), + CoreError::ExtensionTranspiler(err) => err.get_message(), + CoreError::ModuleLoader(err) => err.get_message(), + CoreError::CouldNotExecute { error, .. } => error.get_message(), + CoreError::JsNativeError(err) => err.get_message(), + CoreError::Url(err) => err.get_message(), + CoreError::Module(err) => err.get_message(), + CoreError::DataError(err) => err.get_message(), + CoreError::Other(err) => err.get_message(), + CoreError::Parse(_) + | CoreError::Execute(_) + | CoreError::UnusedModules(_) + | CoreError::NonEvaluatedModules(_) + | CoreError::MissingFromModuleMap(_) + | CoreError::FutureCanceled(_) + | CoreError::ExecutionTerminated + | CoreError::PendingPromiseResolution + | CoreError::EvaluateDynamicImportedModule => self.to_string().into(), + } + } +} + +impl JsErrorClass for serde_v8::Error { + fn get_class(&self) -> &'static str { + "TypeError" } } @@ -127,19 +202,20 @@ impl JsErrorClass for std::io::Error { } } } +} - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() +impl JsErrorClass for std::env::VarError { + fn get_class(&self) -> &'static str { + match self { + std::env::VarError::NotPresent => "NotFound", + std::env::VarError::NotUnicode(..) => "InvalidData", + } } } impl JsErrorClass for v8::DataError { fn get_class(&self) -> &'static str { - todo!() - } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() + "Error" } } @@ -159,26 +235,14 @@ impl JsErrorClass for serde_json::Error { Category::Eof => "UnexpectedEof", } } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } } impl JsErrorClass for url::ParseError { fn get_class(&self) -> &'static str { "URIError" } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } } -/// A simple error type that lets the creator specify both the error message and -/// the error class name. This type is private; externally it only ever appears -/// wrapped in an `anyhow::Error`. To retrieve the error class name from a wrapped -/// `CustomError`, use the function `get_custom_error_class()`. #[derive(Debug, thiserror::Error)] #[error("{class}: {message}")] pub struct JsNativeError { diff --git a/core/lib.rs b/core/lib.rs index a08f23d50..5c62c4c8d 100644 --- a/core/lib.rs +++ b/core/lib.rs @@ -3,6 +3,7 @@ #![deny(clippy::print_stderr)] #![deny(clippy::print_stdout)] #![deny(clippy::unused_async)] +#![deny(clippy::unnecessary_wraps)] pub mod arena; mod async_cancel; diff --git a/core/module_specifier.rs b/core/module_specifier.rs index 4179dcff7..0802ad8c4 100644 --- a/core/module_specifier.rs +++ b/core/module_specifier.rs @@ -1,7 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::normalize_path; -use std::borrow::Cow; use std::path::Path; use std::path::PathBuf; use url::ParseError; @@ -30,10 +29,6 @@ impl super::error::JsErrorClass for ModuleResolutionError { fn get_class(&self) -> &'static str { "URIError" } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } } use ModuleResolutionError::*; diff --git a/core/modules/loaders.rs b/core/modules/loaders.rs index 23cc52a89..60aefda68 100644 --- a/core/modules/loaders.rs +++ b/core/modules/loaders.rs @@ -1,4 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +use crate::error::JsErrorClass; use crate::error::JsNativeError; use crate::extensions::ExtensionFileSource; use crate::module_specifier::ModuleSpecifier; @@ -50,18 +51,33 @@ pub enum ModuleLoaderError { #[error(transparent)] Resolution(#[from] crate::ModuleResolutionError), #[error(transparent)] - Other(#[from] CoreError), + Core(#[from] CoreError), +} + +impl JsErrorClass for ModuleLoaderError { + fn get_class(&self) -> &'static str { + match self { + ModuleLoaderError::SpecifierExcludedFromSnapshot(_) => "Error", + ModuleLoaderError::SpecifierMissingLazyLoadable(_) => "Error", + ModuleLoaderError::NpmUnsupportedMetaResolve => "Error", + ModuleLoaderError::JsonMissingAttribute => "Error", + ModuleLoaderError::NotFound => "Error", + ModuleLoaderError::Unsupported { .. } => "Error", + ModuleLoaderError::Resolution(err) => err.get_class(), + ModuleLoaderError::Core(err) => err.get_class(), + } + } } impl From for ModuleLoaderError { fn from(err: anyhow::Error) -> Self { - ModuleLoaderError::Other(CoreError::Other(err)) + ModuleLoaderError::Core(CoreError::Other(err)) } } impl From for ModuleLoaderError { fn from(err: std::io::Error) -> Self { - ModuleLoaderError::Other(CoreError::Io(err)) + ModuleLoaderError::Core(CoreError::Io(err)) } } diff --git a/core/modules/map.rs b/core/modules/map.rs index 1f2e0f346..aaef43b6d 100644 --- a/core/modules/map.rs +++ b/core/modules/map.rs @@ -1262,9 +1262,7 @@ impl ModuleMap { .push(dyn_import_mod_evaluate); self.pending_dyn_mod_evaluations_pending.set(true); } else if tc_scope.has_terminated() || tc_scope.is_execution_terminating() { - return Err( - JsNativeError::generic("Cannot evaluate dynamically imported module, because JavaScript execution has been terminated.").into() - ); + return Err(CoreError::EvaluateDynamicImportedModule); } else { assert_eq!(status, v8::ModuleStatus::Errored); } @@ -1607,10 +1605,8 @@ impl ModuleMap { v8::ModuleStatus::Instantiated | v8::ModuleStatus::Evaluated )); - let module_namespace: v8::Local = v8::Local::try_from( - module.get_module_namespace(), - ) - .map_err(|err: v8::DataError| JsNativeError::generic(err.to_string()))?; + let module_namespace: v8::Local = + v8::Local::try_from(module.get_module_namespace())?; Ok(v8::Global::new(scope, module_namespace)) } diff --git a/core/modules/mod.rs b/core/modules/mod.rs index edc33c51e..4924bc9f8 100644 --- a/core/modules/mod.rs +++ b/core/modules/mod.rs @@ -643,10 +643,6 @@ impl super::error::JsErrorClass for ModuleConcreteError { fn get_class(&self) -> &'static str { "Error" } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } } #[derive(Debug)] diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index 20a3d7fa6..28bb84cf4 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -295,15 +295,6 @@ impl From for OpError { } } -impl From for OpError { - fn from(err: anyhow::Error) -> Self { - match err.downcast::() { - Ok(err) => OpError::from(err), - Err(_) => todo!(), - } - } -} - impl Serialize for OpError { fn serialize(&self, serializer: S) -> Result where diff --git a/core/runtime/tests/ops.rs b/core/runtime/tests/ops.rs index 752725ef7..ae813af95 100644 --- a/core/runtime/tests/ops.rs +++ b/core/runtime/tests/ops.rs @@ -221,9 +221,7 @@ fn test_op_detached_buffer() { #[op2] #[buffer] - fn op_boomerang( - #[buffer(detach)] b: JsBuffer, - ) -> Result { + fn op_boomerang(#[buffer(detach)] b: JsBuffer) -> Result { Ok(b) } From 6380ef92f180727f96910c17f10390f7fc6f0e7c Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sat, 24 Aug 2024 06:37:50 +0200 Subject: [PATCH 08/52] fixes --- core/convert.rs | 5 ++- core/error.rs | 50 +++++------------------ core/io/mod.rs | 1 + core/io/resource_table.rs | 61 +++++++++++++++++++---------- testing/checkin/runner/ops_error.rs | 3 +- 5 files changed, 56 insertions(+), 64 deletions(-) diff --git a/core/convert.rs b/core/convert.rs index 2d29ae78b..7f514bb06 100644 --- a/core/convert.rs +++ b/core/convert.rs @@ -87,15 +87,16 @@ pub trait ToV8<'a> { /// /// ```ignore /// use deno_core::FromV8; +/// use deno_core::error::JsNativeError; /// use deno_core::convert::Smi; /// use deno_core::op2; /// /// struct Foo(i32); /// /// impl<'a> FromV8<'a> for Foo { -/// // This conversion can fail, so we use `deno_core::error::StdAnyError` as the error type. +/// // This conversion can fail, so we use `JsNativeError` as the error type. /// // Any error type that implements `std::error::Error` can be used here. -/// type Error = deno_core::error::StdAnyError; +/// type Error = JsNativeError; /// /// fn from_v8(scope: &mut v8::HandleScope<'a>, value: v8::Local<'a, v8::Value>) -> Result { /// /// We expect this value to be a `v8::Integer`, so we use the [`Smi`][deno_core::convert::Smi] wrapper type to convert it. diff --git a/core/error.rs b/core/error.rs index 4ab195532..b8e252b75 100644 --- a/core/error.rs +++ b/core/error.rs @@ -10,6 +10,7 @@ use std::fmt::Formatter; use std::fmt::Write as _; use thiserror::__private::AsDynError; +pub use crate::io::ResourceError; pub use crate::modules::ModuleLoaderError; use crate::runtime::v8_static_strings; use crate::runtime::JsRealm; @@ -116,22 +117,22 @@ impl JsErrorClass for CoreError { CoreError::Js(_) => todo!(), CoreError::Io(err) => err.get_class(), CoreError::ExtensionTranspiler(err) => err.get_class(), - CoreError::Parse(_) => "Error", - CoreError::Execute(_) => "Error", - CoreError::UnusedModules(_) => "Error", - CoreError::NonEvaluatedModules(_) => "Error", - CoreError::MissingFromModuleMap(_) => "Error", CoreError::ModuleLoader(err) => err.get_class(), CoreError::CouldNotExecute { error, .. } => error.get_class(), CoreError::JsNativeError(err) => err.get_class(), CoreError::Url(err) => err.get_class(), - CoreError::FutureCanceled(_) => "Interrupted", - CoreError::ExecutionTerminated => "Error", - CoreError::PendingPromiseResolution => "Error", - CoreError::EvaluateDynamicImportedModule => "Error", CoreError::Module(err) => err.get_class(), CoreError::DataError(err) => err.get_class(), CoreError::Other(err) => err.get_class(), + CoreError::FutureCanceled(_) => "Interrupted", + CoreError::Parse(_) + | CoreError::Execute(_) + | CoreError::UnusedModules(_) + | CoreError::NonEvaluatedModules(_) + | CoreError::MissingFromModuleMap(_) + | CoreError::ExecutionTerminated + | CoreError::PendingPromiseResolution + | CoreError::EvaluateDynamicImportedModule => "Error", } } @@ -283,26 +284,7 @@ impl JsNativeError { Self::new("RangeError", message) } - pub fn reference_error( - message: impl Into>, - ) -> JsNativeError { - Self::new("RangeError", message) - } - - pub fn uri_error(message: impl Into>) -> JsNativeError { - Self::new("URIError", message) - } - // Non-standard errors - - pub fn bad_resource(message: impl Into>) -> JsNativeError { - Self::new("BadResource", message) - } - - pub fn bad_resource_id() -> JsNativeError { - Self::bad_resource("Bad resource ID") - } - pub fn not_supported() -> JsNativeError { Self::new("NotSupported", "The operation is not supported") } @@ -1673,18 +1655,6 @@ pub fn format_frame(frame: &JsStackFrame) -> String { mod tests { use super::*; - #[test] - fn test_bad_resource() { - let err = JsNativeError::bad_resource("Resource has been closed"); - assert_eq!(err.to_string(), "Resource has been closed"); - } - - #[test] - fn test_bad_resource_id() { - let err = JsNativeError::bad_resource_id(); - assert_eq!(err.to_string(), "Bad resource ID"); - } - #[test] fn test_format_file_name() { let file_name = format_file_name("data:,Hello%2C%20World%21"); diff --git a/core/io/mod.rs b/core/io/mod.rs index bb32b3367..510f89154 100644 --- a/core/io/mod.rs +++ b/core/io/mod.rs @@ -23,6 +23,7 @@ pub use resource::Resource; pub use resource_handle::ResourceHandle; pub use resource_handle::ResourceHandleFd; pub use resource_handle::ResourceHandleSocket; +pub use resource_table::ResourceError; pub use resource_table::ResourceId; pub use resource_table::ResourceTable; diff --git a/core/io/resource_table.rs b/core/io/resource_table.rs index 08f246d5d..aea4d771c 100644 --- a/core/io/resource_table.rs +++ b/core/io/resource_table.rs @@ -3,7 +3,6 @@ use super::Resource; use super::ResourceHandle; use super::ResourceHandleFd; use super::ResourceHandleSocket; -use crate::error::JsNativeError; use std::borrow::Cow; use std::collections::BTreeMap; use std::rc::Rc; @@ -81,24 +80,24 @@ impl ResourceTable { pub fn get( &self, rid: ResourceId, - ) -> Result, JsNativeError> { + ) -> Result, ResourceError> { self .index .get(&rid) .and_then(|rc| rc.downcast_rc::()) .cloned() - .ok_or_else(JsNativeError::bad_resource_id) + .ok_or_else(|| ResourceError::BadResourceId) } pub fn get_any( &self, rid: ResourceId, - ) -> Result, JsNativeError> { + ) -> Result, ResourceError> { self .index .get(&rid) .cloned() - .ok_or_else(JsNativeError::bad_resource_id) + .ok_or_else(|| ResourceError::BadResourceId) } /// Replaces a resource with a new resource. @@ -124,7 +123,7 @@ impl ResourceTable { pub fn take( &mut self, rid: ResourceId, - ) -> Result, JsNativeError> { + ) -> Result, ResourceError> { let resource = self.get::(rid)?; self.index.remove(&rid); Ok(resource) @@ -141,11 +140,11 @@ impl ResourceTable { pub fn take_any( &mut self, rid: ResourceId, - ) -> Result, JsNativeError> { + ) -> Result, ResourceError> { self .index .remove(&rid) - .ok_or_else(JsNativeError::bad_resource_id) + .ok_or_else(|| ResourceError::BadResourceId) } /// Removes the resource with the given `rid` from the resource table. If the @@ -155,11 +154,11 @@ impl ResourceTable { /// may implement the `close()` method to perform clean-ups such as canceling /// ops. #[deprecated = "This method may deadlock. Use take() and close() instead."] - pub fn close(&mut self, rid: ResourceId) -> Result<(), JsNativeError> { + pub fn close(&mut self, rid: ResourceId) -> Result<(), ResourceError> { self .index .remove(&rid) - .ok_or_else(JsNativeError::bad_resource_id) + .ok_or_else(|| ResourceError::BadResourceId) .map(|resource| resource.close()) } @@ -187,15 +186,15 @@ impl ResourceTable { pub fn get_fd( &self, rid: ResourceId, - ) -> Result { + ) -> Result { let Some(handle) = self.get_any(rid)?.backing_handle() else { - return Err(JsNativeError::bad_resource_id()); + return Err(ResourceError::BadResourceId); }; let Some(fd) = handle.as_fd_like() else { - return Err(JsNativeError::bad_resource_id()); + return Err(ResourceError::BadResourceId); }; if !handle.is_valid() { - return Err(JsNativeError::reference_error("null or invalid handle")); + return Err(ResourceError::Reference); } Ok(fd) } @@ -205,15 +204,15 @@ impl ResourceTable { pub fn get_socket( &self, rid: ResourceId, - ) -> Result { + ) -> Result { let Some(handle) = self.get_any(rid)?.backing_handle() else { - return Err(JsNativeError::bad_resource_id()); + return Err(ResourceError::BadResourceId); }; let Some(socket) = handle.as_socket_like() else { - return Err(JsNativeError::bad_resource_id()); + return Err(ResourceError::BadResourceId); }; if !handle.is_valid() { - return Err(JsNativeError::reference_error("null or invalid handle")); + return Err(ResourceError::Reference); } Ok(socket) } @@ -223,13 +222,33 @@ impl ResourceTable { pub fn get_handle( &self, rid: ResourceId, - ) -> Result { + ) -> Result { let Some(handle) = self.get_any(rid)?.backing_handle() else { - return Err(JsNativeError::bad_resource_id()); + return Err(ResourceError::BadResourceId); }; if !handle.is_valid() { - return Err(JsNativeError::reference_error("null or invalid handle")); + return Err(ResourceError::Reference); } Ok(handle) } } + +#[derive(Debug, thiserror::Error)] +pub enum ResourceError { + #[error("null or invalid handle")] + Reference, + #[error("Bad resource ID")] + BadResourceId, + #[error("{0}")] + Other(String), +} + +impl crate::error::JsErrorClass for ResourceError { + fn get_class(&self) -> &'static str { + match self { + ResourceError::Reference => "ReferenceError", + ResourceError::BadResourceId => "BadResource", + ResourceError::Other(_) => "BadResource", + } + } +} diff --git a/testing/checkin/runner/ops_error.rs b/testing/checkin/runner/ops_error.rs index ec5050604..838b7cc5a 100644 --- a/testing/checkin/runner/ops_error.rs +++ b/testing/checkin/runner/ops_error.rs @@ -2,6 +2,7 @@ use anyhow::anyhow; use deno_core::error::JsNativeError; use deno_core::error::OpError; +use deno_core::error::ResourceError; use deno_core::op2; use deno_core::Op; @@ -22,7 +23,7 @@ pub async fn op_async_throw_error_lazy() -> Result<(), OpError> { #[op2(fast)] pub fn op_error_custom_sync(#[string] message: String) -> Result<(), OpError> { - Err(JsNativeError::bad_resource(message).into()) + Err(ResourceError::Other(message).into()) } #[op2(fast)] From b44cac1e77d6f0cbb62a8e67e55d8399d488f85a Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sat, 24 Aug 2024 21:46:15 +0200 Subject: [PATCH 09/52] fixes --- core/error.rs | 37 +++++++++++++++++-- core/examples/op2.rs | 9 +++-- core/examples/ts_module_loader.rs | 40 +++++++++++--------- core/modules/tests.rs | 33 +++++++++-------- core/runtime/jsruntime.rs | 55 +++++++++++++++------------- core/runtime/op_driver/mod.rs | 1 + core/runtime/op_driver/op_results.rs | 30 ++++++++++----- core/runtime/ops.rs | 6 ++- core/runtime/tests/error.rs | 7 ++-- core/runtime/tests/jsrealm.rs | 11 ++++-- core/runtime/tests/misc.rs | 33 ++++++++++++----- core/runtime/tests/snapshot.rs | 2 +- core/source_map.rs | 3 +- ops/op2/dispatch_slow.rs | 2 +- testing/checkin/runner/ops_error.rs | 1 - testing/checkin/runner/ops_worker.rs | 2 +- 16 files changed, 173 insertions(+), 99 deletions(-) diff --git a/core/error.rs b/core/error.rs index b8e252b75..2deb07e89 100644 --- a/core/error.rs +++ b/core/error.rs @@ -1,8 +1,10 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. pub use super::runtime::op_driver::OpError; +pub use super::runtime::op_driver::OpErrorWrapper; use std::borrow::Cow; use std::collections::HashSet; +use std::error::Error; use std::fmt; use std::fmt::Debug; use std::fmt::Display; @@ -25,8 +27,8 @@ pub type AnyError = anyhow::Error; #[derive(Debug, thiserror::Error)] pub enum CoreError { - #[error("top level await is not allowed in extensions")] - TLA(JsError), + #[error("Top-level await is not allowed in extensions")] + TLA(#[source] JsError), #[error(transparent)] Js(#[from] JsError), #[error(transparent)] @@ -81,6 +83,21 @@ pub enum CoreError { Other(anyhow::Error), } +impl CoreError { + pub fn print_with_cause(&self) -> String { + let mut err_message = self.to_string(); + + if let Some(source) = self.source() { + err_message.push_str(&format!( + "\n\nCaused by:\n {}", + source.to_string().replace("\n", "\n ") + )); + } + + err_message + } +} + impl From for CoreError { fn from(err: ModuleLoaderError) -> Self { CoreError::ModuleLoader(Box::new(err)) @@ -214,12 +231,26 @@ impl JsErrorClass for std::env::VarError { } } +impl JsErrorClass for std::sync::mpsc::RecvError { + fn get_class(&self) -> &'static str { + "Error" + } +} + impl JsErrorClass for v8::DataError { fn get_class(&self) -> &'static str { "Error" } } +impl JsErrorClass + for tokio::sync::mpsc::error::SendError +{ + fn get_class(&self) -> &'static str { + "Error" + } +} + impl JsErrorClass for serde_json::Error { fn get_class(&self) -> &'static str { use serde::de::StdError; @@ -245,7 +276,7 @@ impl JsErrorClass for url::ParseError { } #[derive(Debug, thiserror::Error)] -#[error("{class}: {message}")] +#[error("{message}")] // TODO: {class}: {message} pub struct JsNativeError { pub class: &'static str, message: Cow<'static, str>, diff --git a/core/examples/op2.rs b/core/examples/op2.rs index d91d0a259..7209e05ff 100644 --- a/core/examples/op2.rs +++ b/core/examples/op2.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use anyhow::Context; -use deno_core::anyhow::Error; +use deno_core::error::OpError; use deno_core::*; use std::rc::Rc; @@ -8,7 +8,7 @@ use std::rc::Rc; fn op_use_state( state: &mut OpState, #[global] callback: v8::Global, -) -> Result<(), Error> { +) -> Result<(), OpError> { state.put(callback); Ok(()) } @@ -21,7 +21,7 @@ extension!( docs = "A small example demonstrating op2 usage.", "Contains one op." ); -fn main() -> Result<(), Error> { +fn main() -> Result<(), anyhow::Error> { let module_name = "test.js"; let module_code = " op2_sample.use_state(() => { @@ -49,7 +49,8 @@ fn main() -> Result<(), Error> { let result = js_runtime.mod_evaluate(mod_id); js_runtime.run_event_loop(Default::default()).await?; - result.await + result.await?; + Ok::<(), anyhow::Error>(()) }; tokio::runtime::Builder::new_current_thread() diff --git a/core/examples/ts_module_loader.rs b/core/examples/ts_module_loader.rs index d13dd1874..e56259b1a 100644 --- a/core/examples/ts_module_loader.rs +++ b/core/examples/ts_module_loader.rs @@ -9,7 +9,6 @@ use std::collections::HashMap; use std::rc::Rc; use anyhow::anyhow; -use anyhow::bail; use anyhow::Context; use deno_ast::MediaType; use deno_ast::ParseParams; @@ -43,7 +42,7 @@ impl ModuleLoader for TypescriptModuleLoader { specifier: &str, referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { Ok(resolve_import(specifier, referrer)?) } @@ -77,7 +76,11 @@ impl ModuleLoader for TypescriptModuleLoader { | MediaType::Dcts | MediaType::Tsx => (ModuleType::JavaScript, true), MediaType::Json => (ModuleType::Json, false), - _ => bail!("Unknown extension {:?}", path.extension()), + _ => { + return Err( + anyhow!("Unknown extension {:?}", path.extension()).into(), + ) + } }; let code = std::fs::read_to_string(&path)?; @@ -89,20 +92,23 @@ impl ModuleLoader for TypescriptModuleLoader { capture_tokens: false, scope_analysis: false, maybe_syntax: None, - })?; - let res = parsed.transpile( - &deno_ast::TranspileOptions { - imports_not_used_as_values: - deno_ast::ImportsNotUsedAsValues::Remove, - use_decorators_proposal: true, - ..Default::default() - }, - &deno_ast::EmitOptions { - source_map: SourceMapOption::Separate, - inline_sources: true, - ..Default::default() - }, - )?; + }) + .map_err(anyhow::Error::new)?; + let res = parsed + .transpile( + &deno_ast::TranspileOptions { + imports_not_used_as_values: + deno_ast::ImportsNotUsedAsValues::Remove, + use_decorators_proposal: true, + ..Default::default() + }, + &deno_ast::EmitOptions { + source_map: SourceMapOption::Separate, + inline_sources: true, + ..Default::default() + }, + ) + .map_err(anyhow::Error::new)?; let res = res.into_source(); let source_map = res.source_map.unwrap(); source_maps diff --git a/core/modules/tests.rs b/core/modules/tests.rs index a5c083333..b62d3ffd4 100644 --- a/core/modules/tests.rs +++ b/core/modules/tests.rs @@ -3,12 +3,11 @@ #![allow(clippy::print_stderr)] use crate::ascii_str; -use crate::error::exception_to_err_result; use crate::error::JsNativeError; +use crate::error::{exception_to_err_result, CoreError}; use crate::modules::loaders::ModuleLoadEventCounts; use crate::modules::loaders::TestingModuleLoader; use crate::modules::loaders::*; -use crate::modules::CustomModuleEvaluationKind; use crate::modules::IntoModuleName; use crate::modules::ModuleCodeBytes; use crate::modules::ModuleError; @@ -17,6 +16,7 @@ use crate::modules::ModuleRequest; use crate::modules::ModuleSourceCode; use crate::modules::RequestedModuleType; use crate::modules::SourceCodeCacheInfo; +use crate::modules::{CustomModuleEvaluationKind, ModuleConcreteError}; use crate::resolve_import; use crate::resolve_url; use crate::runtime::JsRuntime; @@ -28,7 +28,7 @@ use crate::ModuleSpecifier; use crate::ModuleType; use crate::ResolutionKind; use crate::RuntimeOptions; -use anyhow::bail; +use anyhow::anyhow; use deno_ops::op2; use futures::future::poll_fn; use futures::future::FutureExt; @@ -209,7 +209,7 @@ struct DelayedSourceCodeFuture { } impl Future for DelayedSourceCodeFuture { - type Output = Result; + type Output = Result; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { let inner = self.get_mut(); @@ -245,7 +245,7 @@ impl Future for DelayedSourceCodeFuture { }), ))) } - None => Poll::Ready(Err(MockError::LoadErr.into())), + None => Poll::Ready(Err(anyhow::Error::new(MockError::LoadErr).into())), } } } @@ -265,13 +265,13 @@ impl ModuleLoader for MockLoader { let output_specifier = match resolve_import(specifier, referrer) { Ok(specifier) => specifier, - Err(..) => return Err(MockError::ResolveErr.into()), + Err(..) => return Err(anyhow::Error::new(MockError::ResolveErr).into()), }; if mock_source_code(output_specifier.as_ref()).is_some() { Ok(output_specifier) } else { - Err(MockError::ResolveErr.into()) + Err(anyhow::Error::new(MockError::ResolveErr).into()) } } @@ -779,11 +779,8 @@ fn test_custom_module_type_default() { }; match err { - ModuleError::Core(err) => { - assert_eq!( - err.to_string(), - "Importing 'bytes' modules is not supported" - ); + ModuleError::Concrete(ModuleConcreteError::UnsupportedKind(kind)) => { + assert_eq!(kind, "bytes"); } _ => unreachable!(), }; @@ -1341,7 +1338,13 @@ async fn loader_disappears_after_error() { let spec = resolve_url("file:///bad_import.js").unwrap(); let result = runtime.load_main_es_module(&spec).await; - let err = result.unwrap_err(); + + let CoreError::ModuleLoader(err) = dbg!(result).unwrap_err() else { + unreachable!(); + }; + let ModuleLoaderError::Core(CoreError::Other(err)) = *err else { + unreachable!(); + }; assert_eq!( err.downcast_ref::().unwrap(), &MockError::ResolveErr @@ -1674,7 +1677,7 @@ async fn import_meta_resolve_cb() { _loader: &dyn ModuleLoader, specifier: String, _referrer: String, - ) -> Result { + ) -> Result { if specifier == "foo" { return Ok(ModuleSpecifier::parse("foo:bar").unwrap()); } @@ -1683,7 +1686,7 @@ async fn import_meta_resolve_cb() { return Ok(ModuleSpecifier::parse("file:///mod.js").unwrap()); } - bail!("unexpected") + Err(anyhow!("unexpected").into()) } let mut runtime = JsRuntime::new(RuntimeOptions { diff --git a/core/runtime/jsruntime.rs b/core/runtime/jsruntime.rs index 29cde8450..28d62ca16 100644 --- a/core/runtime/jsruntime.rs +++ b/core/runtime/jsruntime.rs @@ -87,10 +87,10 @@ pub type WaitForInspectorDisconnectCallback = Box; const STATE_DATA_OFFSET: u32 = 0; pub type ExtensionTranspiler = - dyn Fn( - ModuleName, - ModuleCodeString, - ) -> Result<(ModuleCodeString, Option), anyhow::Error>; +dyn Fn( + ModuleName, + ModuleCodeString, +) -> Result<(ModuleCodeString, Option), anyhow::Error>; /// Objects that need to live as long as the isolate #[derive(Default)] @@ -410,7 +410,7 @@ impl Clone for CrossIsolateStore { } pub type SharedArrayBufferStore = - CrossIsolateStore>; +CrossIsolateStore>; pub type CompiledWasmModuleStore = CrossIsolateStore; @@ -720,7 +720,10 @@ impl JsRuntime { match Self::try_new(options) { Ok(runtime) => runtime, Err(err) => { - panic!("Failed to initialize a JsRuntime: {:?}", err); + panic!( + "Failed to initialize a JsRuntime: {}", + err.print_with_cause() + ); } } } @@ -1367,7 +1370,7 @@ impl JsRuntime { code: &str, ) -> Option> where - v8::Local<'s, T>: TryFrom, Error = v8::DataError>, + v8::Local<'s, T>: TryFrom, Error=v8::DataError>, { let scope = &mut v8::EscapableHandleScope::new(scope); let source = v8::String::new(scope, code).unwrap(); @@ -1503,7 +1506,7 @@ impl JsRuntime { pub fn call( &mut self, function: &v8::Global, - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { self.call_with_args(function, &[]) } @@ -1517,7 +1520,7 @@ impl JsRuntime { pub fn scoped_call( scope: &mut v8::HandleScope, function: &v8::Global, - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { Self::scoped_call_with_args(scope, function, &[]) } @@ -1532,7 +1535,7 @@ impl JsRuntime { &mut self, function: &v8::Global, args: &[v8::Global], - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { let scope = &mut self.handle_scope(); Self::scoped_call_with_args(scope, function, args) } @@ -1548,7 +1551,7 @@ impl JsRuntime { scope: &mut v8::HandleScope, function: &v8::Global, args: &[v8::Global], - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { let scope = &mut v8::TryCatch::new(scope); let cb = function.open(scope); let this = v8::undefined(scope).into(); @@ -1713,7 +1716,7 @@ impl JsRuntime { pub fn resolve( &mut self, promise: v8::Global, - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { let scope = &mut self.handle_scope(); Self::scoped_resolve(scope, promise) } @@ -1725,7 +1728,7 @@ impl JsRuntime { pub fn scoped_resolve( scope: &mut v8::HandleScope, promise: v8::Global, - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { let promise = v8::Local::new(scope, promise); if !promise.is_promise() { return RcPromiseFuture::new(Ok(v8::Global::new(scope, promise))); @@ -1787,10 +1790,10 @@ impl JsRuntime { /// A utility function that run provided future concurrently with the event loop. /// /// If the event loop resolves while polling the future, it return an error with the text - /// `Promise resolution is still pending but the event loop has already resolved.` + /// `Promise resolution is still pending but the event loop has already resolved` pub async fn with_event_loop_promise<'fut, T, E>( &mut self, - mut fut: impl Future> + Unpin + 'fut, + mut fut: impl Future> + Unpin + 'fut, poll_options: PollEventLoopOptions, ) -> Result where @@ -1810,7 +1813,7 @@ impl JsRuntime { } Poll::Pending }) - .await + .await } /// A utility function that run provided future concurrently with the event loop. @@ -1821,7 +1824,7 @@ impl JsRuntime { /// Useful for interacting with local inspector session. pub async fn with_event_loop_future<'fut, T, E>( &mut self, - mut fut: impl Future> + Unpin + 'fut, + mut fut: impl Future> + Unpin + 'fut, poll_options: PollEventLoopOptions, ) -> Result where @@ -1840,7 +1843,7 @@ impl JsRuntime { } Poll::Pending }) - .await + .await } /// Runs a single tick of event loop @@ -2130,7 +2133,7 @@ impl JsRuntimeForSnapshot { .borrow() .clone() } - .map(|cb| data_store.register(cb)); + .map(|cb| data_store.register(cb)); let snapshotted_data = SnapshottedData { module_map_data, @@ -2200,10 +2203,10 @@ impl EventLoopPendingState { .borrow() .is_empty() || !state - .exception_state - .pending_handled_promise_rejections - .borrow() - .is_empty(); + .exception_state + .pending_handled_promise_rejections + .borrow() + .is_empty(); let has_pending_refed_ops = has_pending_tasks || has_pending_refed_timers || num_pending_ops > num_unrefed_ops; @@ -2317,7 +2320,7 @@ impl JsRuntime { pub fn mod_evaluate( &mut self, id: ModuleId, - ) -> impl Future> { + ) -> impl Future> { let isolate = &mut self.inner.v8_isolate; let realm = &self.inner.main_realm; let scope = &mut realm.handle_scope(isolate); @@ -2591,11 +2594,11 @@ impl JsRuntime { .complete(RuntimeActivityType::Timer, timers[i].0 as _); } // depth, id, function - let value = v8::Integer::new(scope, timers[i].1 .1 as _); + let value = v8::Integer::new(scope, timers[i].1.1 as _); arr.set_index(scope, (i * 3) as _, value.into()); let value = v8::Number::new(scope, timers[i].0 as _); arr.set_index(scope, (i * 3 + 1) as _, value.into()); - let value = v8::Local::new(scope, timers[i].1 .0.clone()); + let value = v8::Local::new(scope, timers[i].1.0.clone()); arr.set_index(scope, (i * 3 + 2) as _, value.into()); } arr.into() diff --git a/core/runtime/op_driver/mod.rs b/core/runtime/op_driver/mod.rs index 16c3c89a3..2e5ab89ed 100644 --- a/core/runtime/op_driver/mod.rs +++ b/core/runtime/op_driver/mod.rs @@ -15,6 +15,7 @@ mod op_results; pub use futures_unordered_driver::FuturesUnorderedDriver; pub use self::op_results::OpError; +pub use self::op_results::OpErrorWrapper; pub use self::op_results::OpMappingContext; pub use self::op_results::OpResult; use self::op_results::PendingOpInfo; diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index 28bb84cf4..e3817e599 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -276,16 +276,6 @@ impl std::fmt::Display for OpError { } } -impl JsErrorClass for OpError { - fn get_class(&self) -> &'static str { - self.error.get_class() - } - - fn get_message(&self) -> std::borrow::Cow<'static, str> { - self.error.get_message() - } -} - impl From for OpError { fn from(err: T) -> Self { Self { @@ -307,3 +297,23 @@ impl Serialize for OpError { serde_state.end() } } + +/// Wrapper type to avoid circular trait implementation error due to From implementation +#[derive(Debug)] +pub struct OpErrorWrapper(pub OpError); + +impl std::fmt::Display for OpErrorWrapper { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} + +impl JsErrorClass for OpErrorWrapper { + fn get_class(&self) -> &'static str { + self.0.error.get_class() + } + + fn get_message(&self) -> std::borrow::Cow<'static, str> { + self.0.error.get_message() + } +} diff --git a/core/runtime/ops.rs b/core/runtime/ops.rs index e0d710280..5e6082719 100644 --- a/core/runtime/ops.rs +++ b/core/runtime/ops.rs @@ -518,7 +518,7 @@ pub fn to_v8_slice_any( mod tests { use crate::convert::Number; use crate::convert::Smi; - use crate::error::JsError; + use crate::error::CoreError; use crate::error::JsNativeError; use crate::error::OpError; use crate::external; @@ -917,7 +917,9 @@ mod tests { "op_test_result_void_switch();", ) .expect_err("Expected this to fail"); - let js_err = err.downcast::().unwrap(); + let CoreError::Js(js_err) = err.downcast::().unwrap() else { + unreachable!(); + }; assert_eq!(js_err.message, Some("failed!!!".into())); assert_eq!(RETURN_COUNT.with(|count| count.get()), 5001); Ok(()) diff --git a/core/runtime/tests/error.rs b/core/runtime/tests/error.rs index e320abf85..1c4bdb291 100644 --- a/core/runtime/tests/error.rs +++ b/core/runtime/tests/error.rs @@ -1,5 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::JsError; +use crate::error::CoreError; use crate::error::JsNativeError; use crate::error::OpError; use crate::op2; @@ -41,8 +41,9 @@ fn syntax_error() { let mut runtime = JsRuntime::new(Default::default()); let src = "hocuspocus("; let r = runtime.execute_script("i.js", src); - let e = r.unwrap_err(); - let js_error = e.downcast::().unwrap(); + let CoreError::Js(js_error) = r.unwrap_err() else { + unreachable!() + }; let frame = js_error.frames.first().unwrap(); assert_eq!(frame.column_number, Some(12)); } diff --git a/core/runtime/tests/jsrealm.rs b/core/runtime/tests/jsrealm.rs index f77aa1290..30e4370da 100644 --- a/core/runtime/tests/jsrealm.rs +++ b/core/runtime/tests/jsrealm.rs @@ -1,5 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error; +use crate::error::CoreError; use crate::modules::StaticModuleLoader; use crate::op2; use crate::JsRuntime; @@ -42,8 +42,9 @@ fn test_set_format_exception_callback_realms() { format!("throw new Error('{realm_name}');"), ); assert!(result.is_err()); - - let error = result.unwrap_err().downcast::().unwrap(); + let CoreError::Js(error) = result.unwrap_err() else { + unreachable!() + }; assert_eq!( error.exception_message, format!("{realm_name} / Error: {realm_name}") @@ -63,7 +64,9 @@ fn test_set_format_exception_callback_realms() { let result = futures::executor::block_on(runtime.run_event_loop(Default::default())); assert!(result.is_err()); - let error = result.unwrap_err().downcast::().unwrap(); + let CoreError::Js(error) = result.unwrap_err() else { + unreachable!() + }; assert_eq!( error.exception_message, format!("Uncaught (in promise) {realm_name} / Error: {realm_name}") diff --git a/core/runtime/tests/misc.rs b/core/runtime/tests/misc.rs index 942fb5709..c5a1da80f 100644 --- a/core/runtime/tests/misc.rs +++ b/core/runtime/tests/misc.rs @@ -1,5 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::JsError; +use crate::error::CoreError; use crate::error::OpError; use crate::modules::StaticModuleLoader; use crate::runtime::tests::setup; @@ -150,7 +150,7 @@ async fn test_wakers_for_async_ops() { Err("Error: fail\n at a.js:1:16") )] #[case("new Promise(resolve => {})", - Err("Promise resolution is still pending but the event loop has already resolved." + Err("Promise resolution is still pending but the event loop has already resolved" ) )] #[tokio::test] @@ -265,7 +265,7 @@ async fn test_resolve_value_generic( Ok(None) => { let error_string = result_global.unwrap_err().to_string(); assert_eq!( - "Promise resolution is still pending but the event loop has already resolved.", + "Promise resolution is still pending but the event loop has already resolved", error_string, ); } @@ -283,7 +283,10 @@ async fn test_resolve_value_generic( value.to_rust_string_lossy(scope) ); }; - assert_eq!(e, err.downcast::().unwrap().exception_message); + let CoreError::Js(js_err) = err else { + unreachable!() + }; + assert_eq!(e, js_err.exception_message); } } } @@ -507,9 +510,12 @@ fn test_heap_limits() { r#"let s = ""; while(true) { s += "Hello"; }"#, ) .expect_err("script should fail"); + let CoreError::Js(js_err) = err else { + unreachable!() + }; assert_eq!( "Uncaught Error: execution terminated", - err.downcast::().unwrap().exception_message + js_err.exception_message ); assert!(callback_invoke_count.load(Ordering::SeqCst) > 0) } @@ -556,9 +562,12 @@ fn test_heap_limit_cb_multiple() { r#"let s = ""; while(true) { s += "Hello"; }"#, ) .expect_err("script should fail"); + let CoreError::Js(js_err) = err else { + unreachable!() + }; assert_eq!( "Uncaught Error: execution terminated", - err.downcast::().unwrap().exception_message + js_err.exception_message ); assert_eq!(0, callback_invoke_count_first.load(Ordering::SeqCst)); assert!(callback_invoke_count_second.load(Ordering::SeqCst) > 0); @@ -874,7 +883,7 @@ async fn test_promise_rejection_handler_generic( let res = runtime.run_event_loop(Default::default()).await; if let Some(error) = error { let err = res.expect_err("Expected a failure"); - let Ok(js_error) = err.downcast::() else { + let CoreError::Js(js_error) = err else { panic!("Expected a JsError"); }; assert_eq!(js_error.exception_message, error); @@ -948,7 +957,9 @@ async fn test_stalled_tla() { .run_event_loop(Default::default()) .await .unwrap_err(); - let js_error = error.downcast::().unwrap(); + let CoreError::Js(js_error) = error else { + unreachable!() + }; assert_eq!( &js_error.exception_message, "Top-level await promise never resolved" @@ -998,10 +1009,12 @@ async fn test_dynamic_import_module_error_stack() { .run_event_loop(Default::default()) .await .unwrap_err(); - let js_error = error.downcast::().unwrap(); + let CoreError::Js(js_error) = error else { + unreachable!() + }; assert_eq!( js_error.to_string(), - "Error: foo + "TypeError: foo at async file:///import.js:1:43" ); } diff --git a/core/runtime/tests/snapshot.rs b/core/runtime/tests/snapshot.rs index a33a8171a..a38835563 100644 --- a/core/runtime/tests/snapshot.rs +++ b/core/runtime/tests/snapshot.rs @@ -370,7 +370,7 @@ pub(crate) fn es_snapshot_without_runtime_module_loader() { let dyn_import_result = futures::executor::block_on(runtime.resolve_value(dyn_import_promise)); assert_eq!( - dyn_import_result.err().unwrap().to_string().as_str(), + dbg!(dyn_import_result.err().unwrap()).to_string().as_str(), r#"Uncaught (in promise) TypeError: Importing ext: modules is only allowed from ext: and node: modules. Tried to import ext:module_snapshot/test.js from (no referrer)"# ); diff --git a/core/source_map.rs b/core/source_map.rs index 4a84fa669..b5084d82b 100644 --- a/core/source_map.rs +++ b/core/source_map.rs @@ -169,6 +169,7 @@ mod tests { use super::*; use crate::ascii_str; + use crate::error::ModuleLoaderError; use crate::ModuleCodeString; use crate::ModuleLoadResponse; use crate::ModuleSpecifier; @@ -190,7 +191,7 @@ mod tests { _specifier: &str, _referrer: &str, _kind: ResolutionKind, - ) -> Result { + ) -> Result { unreachable!() } diff --git a/ops/op2/dispatch_slow.rs b/ops/op2/dispatch_slow.rs index f8f2f5a0f..6969f8678 100644 --- a/ops/op2/dispatch_slow.rs +++ b/ops/op2/dispatch_slow.rs @@ -1011,7 +1011,7 @@ pub(crate) fn throw_exception( #maybe_opctx let exception = deno_core::error::to_v8_error( &mut #scope, - &err, + &deno_core::error::OpErrorWrapper(err), ); #scope.throw_exception(exception); return 1; diff --git a/testing/checkin/runner/ops_error.rs b/testing/checkin/runner/ops_error.rs index 838b7cc5a..96cac4fd8 100644 --- a/testing/checkin/runner/ops_error.rs +++ b/testing/checkin/runner/ops_error.rs @@ -4,7 +4,6 @@ use deno_core::error::JsNativeError; use deno_core::error::OpError; use deno_core::error::ResourceError; use deno_core::op2; -use deno_core::Op; #[op2(async)] pub async fn op_async_throw_error_eager() -> Result<(), OpError> { diff --git a/testing/checkin/runner/ops_worker.rs b/testing/checkin/runner/ops_worker.rs index d1274268b..108227628 100644 --- a/testing/checkin/runner/ops_worker.rs +++ b/testing/checkin/runner/ops_worker.rs @@ -124,7 +124,7 @@ async fn run_worker_task( base_url: String, main_script: String, mut shutdown_rx: UnboundedReceiver<()>, -) -> Result<(), OpError> { +) -> Result<(), anyhow::Error> { let url = Url::try_from(base_url.as_str())?.join(&main_script)?; let module = runtime.load_main_es_module(&url).await?; let f = runtime.mod_evaluate(module); From 537f821e4b3a77a362f5aced864005dbd6450528 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 26 Aug 2024 13:54:01 +0200 Subject: [PATCH 10/52] fixes --- core/error.rs | 207 ++++++++++++------ core/io/resource_table.rs | 3 + core/lib.rs | 1 - core/modules/map.rs | 26 +-- core/modules/tests.rs | 6 +- core/ops_builtin_v8.rs | 3 +- core/runtime/bindings.rs | 11 +- core/runtime/tests/snapshot.rs | 2 +- ops/op2/dispatch_fast.rs | 6 +- ops/op2/dispatch_slow.rs | 2 +- .../async/async_arg_return_result.out | 4 +- ops/op2/test_cases/async/async_opstate.out | 4 +- ops/op2/test_cases/async/async_result.out | 4 +- .../test_cases/async/async_result_impl.out | 10 +- ops/op2/test_cases/async/async_result_smi.out | 4 +- ops/op2/test_cases/sync/bool_result.out | 10 +- ops/op2/test_cases/sync/result_external.out | 10 +- ops/op2/test_cases/sync/result_primitive.out | 10 +- ops/op2/test_cases/sync/result_scope.out | 10 +- ops/op2/test_cases/sync/result_void.out | 8 +- testing/checkin/runner/ops_error.rs | 2 +- 21 files changed, 195 insertions(+), 148 deletions(-) diff --git a/core/error.rs b/core/error.rs index cf57cd183..84b0da446 100644 --- a/core/error.rs +++ b/core/error.rs @@ -2,6 +2,14 @@ pub use super::runtime::op_driver::OpError; pub use super::runtime::op_driver::OpErrorWrapper; +pub use crate::io::ResourceError; +pub use crate::modules::ModuleLoaderError; +use crate::runtime::v8_static_strings; +use crate::runtime::JsRealm; +use crate::runtime::JsRuntime; +use crate::source_map::SourceMapApplication; +use crate::url::Url; +use crate::FastStaticString; use std::borrow::Cow; use std::collections::HashSet; use std::error::Error; @@ -12,15 +20,6 @@ use std::fmt::Formatter; use std::fmt::Write as _; use thiserror::__private::AsDynError; -pub use crate::io::ResourceError; -pub use crate::modules::ModuleLoaderError; -use crate::runtime::v8_static_strings; -use crate::runtime::JsRealm; -use crate::runtime::JsRuntime; -use crate::source_map::SourceMapApplication; -use crate::url::Url; -use crate::FastStaticString; - /// A generic wrapper that can encapsulate any concrete error type. // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. pub type AnyError = anyhow::Error; @@ -60,7 +59,7 @@ pub enum CoreError { specifier: String, }, #[error(transparent)] - JsNativeError(#[from] JsNativeError), + JsNative(#[from] JsNativeError), #[error(transparent)] Url(#[from] url::ParseError), #[error(transparent)] @@ -80,7 +79,7 @@ pub enum CoreError { #[error(transparent)] DataError(#[from] v8::DataError), #[error(transparent)] - Other(anyhow::Error), + Other(#[from] anyhow::Error), } impl CoreError { @@ -96,6 +95,42 @@ impl CoreError { err_message } + + pub fn to_v8_error( + &self, + scope: &mut v8::HandleScope, + ) -> v8::Global { + let err_string = self.get_message().to_string(); + let mut error_chain = vec![]; + let mut intermediary_error = Some(self.as_dyn_error()); + + while let Some(err) = intermediary_error { + if let Some(source) = err.source() { + let source_str = source.to_string(); + if source_str != err_string { + error_chain.push(source_str); + } + + intermediary_error = Some(source); + } else { + intermediary_error = None; + } + } + + let message = if !error_chain.is_empty() { + format!( + "{}\n Caused by:\n {}", + err_string, + error_chain.join("\n ") + ) + } else { + err_string + }; + + let exception = + js_class_and_message_to_exception(scope, self.get_class(), &message); + v8::Global::new(scope, exception) + } } impl From for CoreError { @@ -109,6 +144,30 @@ pub trait JsErrorClass: Display + Debug + Send + Sync + 'static { fn get_message(&self) -> Cow<'static, str> { self.to_string().into() } + + fn throw(&self, scope: &mut v8::HandleScope) { + let exception = js_class_and_message_to_exception( + scope, + self.get_class(), + &self.get_message(), + ); + scope.throw_exception(exception); + } +} + +fn js_class_and_message_to_exception<'s>( + scope: &mut v8::HandleScope<'s>, + class: &str, + message: &str, +) -> v8::Local<'s, v8::Value> { + let message = v8::String::new(scope, message).unwrap(); + match class { + "TypeError" => v8::Exception::type_error(scope, message), + "RangeError" => v8::Exception::range_error(scope, message), + "ReferenceError" => v8::Exception::reference_error(scope, message), + "SyntaxError" => v8::Exception::syntax_error(scope, message), + "Error" | _ => v8::Exception::error(scope, message), + } } impl JsErrorClass for anyhow::Error { @@ -122,7 +181,7 @@ impl JsErrorClass for anyhow::Error { fn get_message(&self) -> Cow<'static, str> { match self.downcast_ref::<&dyn JsErrorClass>() { Some(err) => err.get_message(), - None => self.to_string().into(), + None => format!("{:#}", self).into(), } } } @@ -130,13 +189,14 @@ impl JsErrorClass for anyhow::Error { impl JsErrorClass for CoreError { fn get_class(&self) -> &'static str { match self { - CoreError::TLA(_) => todo!(), - CoreError::Js(_) => todo!(), + CoreError::TLA(js_error) | CoreError::Js(js_error) => { + unreachable!("JsError's should not be reachable: {}", js_error) + } CoreError::Io(err) => err.get_class(), CoreError::ExtensionTranspiler(err) => err.get_class(), CoreError::ModuleLoader(err) => err.get_class(), CoreError::CouldNotExecute { error, .. } => error.get_class(), - CoreError::JsNativeError(err) => err.get_class(), + CoreError::JsNative(err) => err.get_class(), CoreError::Url(err) => err.get_class(), CoreError::Module(err) => err.get_class(), CoreError::DataError(err) => err.get_class(), @@ -155,13 +215,14 @@ impl JsErrorClass for CoreError { fn get_message(&self) -> Cow<'static, str> { match self { - CoreError::TLA(_) => todo!(), - CoreError::Js(_) => todo!(), + CoreError::TLA(js_error) | CoreError::Js(js_error) => { + unreachable!("JsError's should not be reachable: {}", js_error) + } CoreError::Io(err) => err.get_message(), CoreError::ExtensionTranspiler(err) => err.get_message(), CoreError::ModuleLoader(err) => err.get_message(), CoreError::CouldNotExecute { error, .. } => error.get_message(), - CoreError::JsNativeError(err) => err.get_message(), + CoreError::JsNative(err) => err.get_message(), CoreError::Url(err) => err.get_message(), CoreError::Module(err) => err.get_message(), CoreError::DataError(err) => err.get_message(), @@ -239,7 +300,7 @@ impl JsErrorClass for std::sync::mpsc::RecvError { impl JsErrorClass for v8::DataError { fn get_class(&self) -> &'static str { - "Error" + "TypeError" } } @@ -276,7 +337,7 @@ impl JsErrorClass for url::ParseError { } #[derive(Debug, thiserror::Error)] -#[error("{message}")] // TODO: {class}: {message} +#[error("{class}: {message}")] pub struct JsNativeError { pub class: &'static str, message: Cow<'static, str>, @@ -315,12 +376,74 @@ impl JsNativeError { Self::new("RangeError", message) } + pub fn uri_error(message: impl Into>) -> JsNativeError { + Self::new("URIError", message) + } + // Non-standard errors pub fn not_supported() -> JsNativeError { Self::new("NotSupported", "The operation is not supported") } } +#[macro_export] +macro_rules! js_error_wrapper { + ($err_path:path, $err_name:ident, $js_err_type:tt) => { + deno_core::js_error_wrapper!($err_path, $err_name, |_| $js_err_type); + }; + ($err_path:path, $err_name:ident, |$inner:ident| $js_err_type:tt) => { + #[derive(Debug)] + pub struct $err_name(pub $err_path); + impl From<$err_path> for $err_name { + fn from(err: $err_path) -> Self { + Self(err) + } + } + impl std::error::Error for $err_name { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.0.source() + } + } + impl deno_core::error::JsErrorClass for $err_name { + fn get_class(&self) -> &'static str { + let $inner = &self.0; + $js_err_type + } + + fn get_message(&self) -> Cow<'static, str> { + self.0.to_string().into() + } + } + }; +} + +/// A wrapper around `anyhow::Error` that implements `std::error::Error` +#[repr(transparent)] +pub struct StdAnyError(pub anyhow::Error); +impl std::fmt::Debug for StdAnyError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self.0) + } +} + +impl std::fmt::Display for StdAnyError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +impl std::error::Error for StdAnyError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.0.source() + } +} + +impl From for StdAnyError { + fn from(err: anyhow::Error) -> Self { + Self(err) + } +} + pub fn to_v8_error<'a>( scope: &mut v8::HandleScope<'a>, error: &impl JsErrorClass, @@ -961,44 +1084,6 @@ impl Display for JsError { } } -// TODO(piscisaureus): rusty_v8 should implement the Error trait on -// values of type v8::Global. -pub(crate) fn to_v8_type_error( - scope: &mut v8::HandleScope, - err: CoreError, -) -> v8::Global { - let err_string = err.to_string(); - let mut error_chain = vec![]; - let mut intermediary_error = Some(err.as_dyn_error()); - - while let Some(err) = intermediary_error { - if let Some(source) = err.source() { - let source_str = source.to_string(); - if source_str != err_string { - error_chain.push(source_str); - } - - intermediary_error = Some(source); - } else { - intermediary_error = None; - } - } - - let message = if !error_chain.is_empty() { - format!( - "{}\n Caused by:\n {}", - err_string, - error_chain.join("\n ") - ) - } else { - err_string - }; - - let message = v8::String::new(scope, &message).unwrap(); - let exception = v8::Exception::type_error(scope, message); - v8::Global::new(scope, exception) -} - /// Implements `value instanceof primordials.Error` in JS. Similar to /// `Value::is_native_error()` but more closely matches the semantics /// of `instanceof`. `Value::is_native_error()` also checks for static class @@ -1182,12 +1267,6 @@ pub(crate) fn exception_to_err_result( Err(js_error.into()) } -pub fn throw_type_error(scope: &mut v8::HandleScope, message: impl AsRef) { - let message = v8::String::new(scope, message.as_ref()).unwrap(); - let exception = v8::Exception::type_error(scope, message); - scope.throw_exception(exception); -} - v8_static_strings::v8_static_strings! { ERROR = "Error", GET_FILE_NAME = "getFileName", diff --git a/core/io/resource_table.rs b/core/io/resource_table.rs index aea4d771c..4a3a200fd 100644 --- a/core/io/resource_table.rs +++ b/core/io/resource_table.rs @@ -239,6 +239,8 @@ pub enum ResourceError { Reference, #[error("Bad resource ID")] BadResourceId, + #[error("Resource is unavailable because it is in use by a promise")] + Unavailable, #[error("{0}")] Other(String), } @@ -248,6 +250,7 @@ impl crate::error::JsErrorClass for ResourceError { match self { ResourceError::Reference => "ReferenceError", ResourceError::BadResourceId => "BadResource", + ResourceError::Unavailable => "Busy", ResourceError::Other(_) => "BadResource", } } diff --git a/core/lib.rs b/core/lib.rs index e9d6fa787..a62837c9f 100644 --- a/core/lib.rs +++ b/core/lib.rs @@ -172,7 +172,6 @@ extern crate self as deno_core; pub mod _ops { pub use super::cppgc::make_cppgc_object; pub use super::cppgc::try_unwrap_cppgc_object; - pub use super::error::throw_type_error; pub use super::extensions::Op; pub use super::extensions::OpDecl; #[cfg(debug_assertions)] diff --git a/core/modules/map.rs b/core/modules/map.rs index aaef43b6d..e43103211 100644 --- a/core/modules/map.rs +++ b/core/modules/map.rs @@ -1,12 +1,12 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use super::module_map_data::ModuleMapSnapshotData; +use super::IntoModuleCodeString; use super::IntoModuleName; -use super::{IntoModuleCodeString, ModuleConcreteError}; +use super::ModuleConcreteError; use crate::ascii_str; use crate::error::exception_to_err_result; -use crate::error::throw_type_error; -use crate::error::to_v8_type_error; use crate::error::JsError; +use crate::error::JsErrorClass; use crate::error::JsNativeError; use crate::modules::get_requested_module_type_from_attributes; use crate::modules::parse_import_attributes; @@ -832,10 +832,10 @@ impl ModuleMap { return Some(module); } - let msg = format!( + JsNativeError::type_error(format!( r#"Cannot resolve module "{specifier_str}" from "{referrer_name}""# - ); - throw_type_error(scope, msg); + )) + .throw(scope); None } @@ -861,7 +861,7 @@ impl ModuleMap { referrer }; let msg = format!("Importing ext: modules is only allowed from ext: and node: modules. Tried to import {} from {}", specifier, referrer); - return Err(JsNativeError::generic(msg).into()); + return Err(JsNativeError::type_error(msg).into()); } self @@ -883,7 +883,7 @@ impl ModuleMap { match self.resolve(specifier, referrer, ResolutionKind::Import) { Ok(s) => s, Err(e) => { - throw_type_error(scope, e.to_string()); + e.throw(scope); return None; } }; @@ -1453,7 +1453,7 @@ impl ModuleMap { self.pending_dynamic_imports_pending.set(true); } Err(err) => { - let exception = to_v8_type_error(scope, err); + let exception = err.to_v8_error(scope); self.dynamic_import_reject(scope, dyn_import_id, exception); } } @@ -1510,9 +1510,9 @@ impl ModuleMap { Err(err) => { let exception = match err { ModuleError::Exception(e) => e, - ModuleError::Core(e) => to_v8_type_error(scope, e), + ModuleError::Core(e) => e.to_v8_error(scope), ModuleError::Concrete(e) => { - to_v8_type_error(scope, CoreError::Module(e)) + CoreError::Module(e).to_v8_error(scope) } }; self.dynamic_import_reject(scope, dyn_import_id, exception) @@ -1520,10 +1520,10 @@ impl ModuleMap { } } Err(err) => { - // A non-javascript error occurred; this could be due to a an invalid + // A non-javascript error occurred; this could be due to an invalid // module specifier, or a problem with the source map, or a failure // to fetch the module source code. - let exception = to_v8_type_error(scope, err); + let exception = err.to_v8_error(scope); self.dynamic_import_reject(scope, dyn_import_id, exception); } } diff --git a/core/modules/tests.rs b/core/modules/tests.rs index b62d3ffd4..407d1e4e4 100644 --- a/core/modules/tests.rs +++ b/core/modules/tests.rs @@ -845,7 +845,7 @@ fn test_custom_module_type_callback_synthetic() { match err { ModuleError::Core(err) => { - assert_eq!(err.to_string(), "Can't load 'foo' module"); + assert_eq!(err.to_string(), "Error: Can't load 'foo' module"); } _ => unreachable!(), }; @@ -1339,7 +1339,7 @@ async fn loader_disappears_after_error() { let spec = resolve_url("file:///bad_import.js").unwrap(); let result = runtime.load_main_es_module(&spec).await; - let CoreError::ModuleLoader(err) = dbg!(result).unwrap_err() else { + let CoreError::ModuleLoader(err) = result.unwrap_err() else { unreachable!(); }; let ModuleLoaderError::Core(CoreError::Other(err)) = *err else { @@ -1702,7 +1702,7 @@ async fn import_meta_resolve_cb() { try { import.meta.resolve("boom!"); } catch (e) { - if (!(e instanceof TypeError)) throw new Error("c"); + if (!(e instanceof Error)) throw new Error("c"); caught = true; } if (!caught) throw new Error("d"); diff --git a/core/ops_builtin_v8.rs b/core/ops_builtin_v8.rs index 2c5edf0a7..4976f8fcc 100644 --- a/core/ops_builtin_v8.rs +++ b/core/ops_builtin_v8.rs @@ -808,8 +808,7 @@ pub fn op_set_promise_hooks( .enumerate() .filter(|(_, hook)| !hook.is_undefined()) .try_fold([None; 4], |mut v8_fns, (i, hook)| { - let v8_fn = v8::Local::::try_from(hook) - .map_err(|err| JsNativeError::type_error(err.to_string()))?; + let v8_fn = v8::Local::::try_from(hook)?; v8_fns[i] = Some(v8_fn); Ok::<_, OpError>(v8_fns) })?; diff --git a/core/runtime/bindings.rs b/core/runtime/bindings.rs index e16d25190..a06653235 100644 --- a/core/runtime/bindings.rs +++ b/core/runtime/bindings.rs @@ -12,8 +12,9 @@ use crate::cppgc::cppgc_template_constructor; use crate::error::callsite_fns; use crate::error::has_call_site; use crate::error::is_instance_of_error; -use crate::error::throw_type_error; use crate::error::CoreError; +use crate::error::JsErrorClass; +use crate::error::JsNativeError; use crate::error::JsStackFrame; use crate::extension_set::LoadedSources; use crate::modules::get_requested_module_type_from_attributes; @@ -596,12 +597,12 @@ fn import_meta_resolve( mut rv: v8::ReturnValue, ) { if args.length() > 1 { - return throw_type_error(scope, "Invalid arguments"); + return JsNativeError::type_error("Invalid arguments").throw(scope); } let maybe_arg_str = args.get(0).to_string(scope); if maybe_arg_str.is_none() { - return throw_type_error(scope, "Invalid arguments"); + return JsNativeError::type_error("Invalid arguments").throw(scope); } let specifier = maybe_arg_str.unwrap(); let referrer = { @@ -624,7 +625,7 @@ fn import_meta_resolve( rv.set(resolved_val); } Err(err) => { - throw_type_error(scope, err.to_string()); + err.throw(scope); } }; } @@ -724,7 +725,7 @@ fn call_console( || !args.get(0).is_function() || !args.get(1).is_function() { - return throw_type_error(scope, "Invalid arguments"); + return JsNativeError::type_error("Invalid arguments").throw(scope); } let mut call_args = vec![]; diff --git a/core/runtime/tests/snapshot.rs b/core/runtime/tests/snapshot.rs index a38835563..a33a8171a 100644 --- a/core/runtime/tests/snapshot.rs +++ b/core/runtime/tests/snapshot.rs @@ -370,7 +370,7 @@ pub(crate) fn es_snapshot_without_runtime_module_loader() { let dyn_import_result = futures::executor::block_on(runtime.resolve_value(dyn_import_promise)); assert_eq!( - dbg!(dyn_import_result.err().unwrap()).to_string().as_str(), + dyn_import_result.err().unwrap().to_string().as_str(), r#"Uncaught (in promise) TypeError: Importing ext: modules is only allowed from ext: and node: modules. Tried to import ext:module_snapshot/test.js from (no referrer)"# ); diff --git a/ops/op2/dispatch_fast.rs b/ops/op2/dispatch_fast.rs index 26e8d575e..32de34b91 100644 --- a/ops/op2/dispatch_fast.rs +++ b/ops/op2/dispatch_fast.rs @@ -336,16 +336,14 @@ pub(crate) fn generate_fast_result_early_exit( ) -> TokenStream { generator_state.needs_opctx = true; let create_scope = create_scope(generator_state); - gs_quote!(generator_state(opctx, result) => { + gs_quote!(generator_state(result) => { let #result = match #result { Ok(#result) => #result, Err(err) => { - let err = err.into(); let mut scope = #create_scope; let exception = deno_core::error::to_v8_error( &mut scope, - #opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); // SAFETY: All fast return types have zero as a valid value diff --git a/ops/op2/dispatch_slow.rs b/ops/op2/dispatch_slow.rs index 56a02b84c..f119314b6 100644 --- a/ops/op2/dispatch_slow.rs +++ b/ops/op2/dispatch_slow.rs @@ -985,7 +985,7 @@ pub(crate) fn throw_exception( #maybe_opctx let exception = deno_core::error::to_v8_error( &mut #scope, - &deno_core::error::OpErrorWrapper(err), + &deno_core::error::OpErrorWrapper(err.into()), ); #scope.throw_exception(exception); return 1; diff --git a/ops/op2/test_cases/async/async_arg_return_result.out b/ops/op2/test_cases/async/async_arg_return_result.out index 14a5ceec4..f9456dfec 100644 --- a/ops/op2/test_cases/async/async_arg_return_result.out +++ b/ops/op2/test_cases/async/async_arg_return_result.out @@ -78,11 +78,9 @@ pub const fn op_async() -> ::deno_core::_ops::OpDecl { let mut scope = unsafe { deno_core::v8::CallbackScope::new(info) }; - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return 1; diff --git a/ops/op2/test_cases/async/async_opstate.out b/ops/op2/test_cases/async/async_opstate.out index e662b7c20..77b1378a6 100644 --- a/ops/op2/test_cases/async/async_opstate.out +++ b/ops/op2/test_cases/async/async_opstate.out @@ -66,11 +66,9 @@ pub const fn op_async_opstate() -> ::deno_core::_ops::OpDecl { let mut scope = unsafe { deno_core::v8::CallbackScope::new(info) }; - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return 1; diff --git a/ops/op2/test_cases/async/async_result.out b/ops/op2/test_cases/async/async_result.out index 6be9fc12b..9b06c3af1 100644 --- a/ops/op2/test_cases/async/async_result.out +++ b/ops/op2/test_cases/async/async_result.out @@ -62,11 +62,9 @@ pub const fn op_async() -> ::deno_core::_ops::OpDecl { let mut scope = unsafe { deno_core::v8::CallbackScope::new(info) }; - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return 1; diff --git a/ops/op2/test_cases/async/async_result_impl.out b/ops/op2/test_cases/async/async_result_impl.out index fa7c79d93..61ece8984 100644 --- a/ops/op2/test_cases/async/async_result_impl.out +++ b/ops/op2/test_cases/async/async_result_impl.out @@ -64,11 +64,9 @@ pub const fn op_async_result_impl() -> ::deno_core::_ops::OpDecl { Ok(result) => result, Err(err) => { let mut scope = unsafe { deno_core::v8::CallbackScope::new(info) }; - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return 1; @@ -92,11 +90,9 @@ pub const fn op_async_result_impl() -> ::deno_core::_ops::OpDecl { let mut scope = unsafe { deno_core::v8::CallbackScope::new(info) }; - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return 1; @@ -145,7 +141,7 @@ pub const fn op_async_result_impl() -> ::deno_core::_ops::OpDecl { #[inline(always)] pub fn call( x: i32, - ) -> Result>, AnyError> { + ) -> Result>, OpError> { Ok(async move { Ok(x) }) } } diff --git a/ops/op2/test_cases/async/async_result_smi.out b/ops/op2/test_cases/async/async_result_smi.out index 6200ff48d..a96184d54 100644 --- a/ops/op2/test_cases/async/async_result_smi.out +++ b/ops/op2/test_cases/async/async_result_smi.out @@ -94,11 +94,9 @@ pub const fn op_async() -> ::deno_core::_ops::OpDecl { let mut scope = unsafe { deno_core::v8::CallbackScope::new(info) }; - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return 1; diff --git a/ops/op2/test_cases/sync/bool_result.out b/ops/op2/test_cases/sync/bool_result.out index e08a5db9a..a508aa14a 100644 --- a/ops/op2/test_cases/sync/bool_result.out +++ b/ops/op2/test_cases/sync/bool_result.out @@ -109,14 +109,12 @@ pub const fn op_bool() -> ::deno_core::_ops::OpDecl { let result = match result { Ok(result) => result, Err(err) => { - let err = err.into(); let mut scope = unsafe { deno_core::v8::CallbackScope::new(&*fast_api_callback_options) }; let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return unsafe { std::mem::zeroed() }; @@ -151,11 +149,9 @@ pub const fn op_bool() -> ::deno_core::_ops::OpDecl { >::cast_unchecked(args.data()) .value() as *const deno_core::_ops::OpCtx) }; - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return 1; @@ -200,7 +196,7 @@ pub const fn op_bool() -> ::deno_core::_ops::OpDecl { } impl op_bool { #[inline(always)] - pub fn call(arg: bool) -> Result { + pub fn call(arg: bool) -> Result { Ok(arg) } } diff --git a/ops/op2/test_cases/sync/result_external.out b/ops/op2/test_cases/sync/result_external.out index 9318f950e..7055807cc 100644 --- a/ops/op2/test_cases/sync/result_external.out +++ b/ops/op2/test_cases/sync/result_external.out @@ -96,14 +96,12 @@ pub const fn op_external_with_result() -> ::deno_core::_ops::OpDecl { let result = match result { Ok(result) => result, Err(err) => { - let err = err.into(); let mut scope = unsafe { deno_core::v8::CallbackScope::new(&*fast_api_callback_options) }; let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return unsafe { std::mem::zeroed() }; @@ -136,11 +134,9 @@ pub const fn op_external_with_result() -> ::deno_core::_ops::OpDecl { >::cast_unchecked(args.data()) .value() as *const deno_core::_ops::OpCtx) }; - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return 1; @@ -185,7 +181,7 @@ pub const fn op_external_with_result() -> ::deno_core::_ops::OpDecl { } impl op_external_with_result { #[inline(always)] - pub fn call() -> Result<*mut std::ffi::c_void, AnyError> { + pub fn call() -> Result<*mut std::ffi::c_void, OpError> { Ok(0 as _) } } diff --git a/ops/op2/test_cases/sync/result_primitive.out b/ops/op2/test_cases/sync/result_primitive.out index b5ccc7560..84656b6d5 100644 --- a/ops/op2/test_cases/sync/result_primitive.out +++ b/ops/op2/test_cases/sync/result_primitive.out @@ -96,14 +96,12 @@ pub const fn op_u32_with_result() -> ::deno_core::_ops::OpDecl { let result = match result { Ok(result) => result, Err(err) => { - let err = err.into(); let mut scope = unsafe { deno_core::v8::CallbackScope::new(&*fast_api_callback_options) }; let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return unsafe { std::mem::zeroed() }; @@ -134,11 +132,9 @@ pub const fn op_u32_with_result() -> ::deno_core::_ops::OpDecl { >::cast_unchecked(args.data()) .value() as *const deno_core::_ops::OpCtx) }; - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return 1; @@ -183,7 +179,7 @@ pub const fn op_u32_with_result() -> ::deno_core::_ops::OpDecl { } impl op_u32_with_result { #[inline(always)] - pub fn call() -> Result { + pub fn call() -> Result { Ok(0) } } diff --git a/ops/op2/test_cases/sync/result_scope.out b/ops/op2/test_cases/sync/result_scope.out index 9871e4e3c..b79a59c39 100644 --- a/ops/op2/test_cases/sync/result_scope.out +++ b/ops/op2/test_cases/sync/result_scope.out @@ -102,14 +102,12 @@ pub const fn op_void_with_result() -> ::deno_core::_ops::OpDecl { let result = match result { Ok(result) => result, Err(err) => { - let err = err.into(); let mut scope = unsafe { deno_core::v8::CallbackScope::new(&*fast_api_callback_options) }; let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return unsafe { std::mem::zeroed() }; @@ -143,11 +141,9 @@ pub const fn op_void_with_result() -> ::deno_core::_ops::OpDecl { >::cast_unchecked(args.data()) .value() as *const deno_core::_ops::OpCtx) }; - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return 1; @@ -192,7 +188,7 @@ pub const fn op_void_with_result() -> ::deno_core::_ops::OpDecl { } impl op_void_with_result { #[inline(always)] - pub fn call(_scope: &mut v8::HandleScope) -> Result<(), AnyError> { + pub fn call(_scope: &mut v8::HandleScope) -> Result<(), OpError> { Ok(()) } } diff --git a/ops/op2/test_cases/sync/result_void.out b/ops/op2/test_cases/sync/result_void.out index 0f0d3f8b8..f7b535a8a 100644 --- a/ops/op2/test_cases/sync/result_void.out +++ b/ops/op2/test_cases/sync/result_void.out @@ -96,14 +96,12 @@ pub const fn op_void_with_result() -> ::deno_core::_ops::OpDecl { let result = match result { Ok(result) => result, Err(err) => { - let err = err.into(); let mut scope = unsafe { deno_core::v8::CallbackScope::new(&*fast_api_callback_options) }; let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return unsafe { std::mem::zeroed() }; @@ -134,11 +132,9 @@ pub const fn op_void_with_result() -> ::deno_core::_ops::OpDecl { >::cast_unchecked(args.data()) .value() as *const deno_core::_ops::OpCtx) }; - let err = err.into(); let exception = deno_core::error::to_v8_error( &mut scope, - opctx.get_error_class_fn, - &err, + &deno_core::error::OpErrorWrapper(err.into()), ); scope.throw_exception(exception); return 1; diff --git a/testing/checkin/runner/ops_error.rs b/testing/checkin/runner/ops_error.rs index 96cac4fd8..d44cc7ce8 100644 --- a/testing/checkin/runner/ops_error.rs +++ b/testing/checkin/runner/ops_error.rs @@ -30,7 +30,7 @@ pub fn op_error_context_sync( #[string] message: String, #[string] context: String, ) -> Result<(), OpError> { - Err(anyhow!(message).context(context).into()) + Err(anyhow::Error::msg(message).context(context).into()) } #[op2(async)] From 970b5c8a0cb9befb1daf2b5463a0c9a4635cb93a Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 26 Aug 2024 13:54:39 +0200 Subject: [PATCH 11/52] fmt --- core/runtime/jsruntime.rs | 48 +++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/core/runtime/jsruntime.rs b/core/runtime/jsruntime.rs index 08436aab8..f7e2fad5b 100644 --- a/core/runtime/jsruntime.rs +++ b/core/runtime/jsruntime.rs @@ -86,10 +86,10 @@ pub type WaitForInspectorDisconnectCallback = Box; const STATE_DATA_OFFSET: u32 = 0; pub type ExtensionTranspiler = -dyn Fn( - ModuleName, - ModuleCodeString, -) -> Result<(ModuleCodeString, Option), anyhow::Error>; + dyn Fn( + ModuleName, + ModuleCodeString, + ) -> Result<(ModuleCodeString, Option), anyhow::Error>; /// Objects that need to live as long as the isolate #[derive(Default)] @@ -394,7 +394,7 @@ impl Clone for CrossIsolateStore { } pub type SharedArrayBufferStore = -CrossIsolateStore>; + CrossIsolateStore>; pub type CompiledWasmModuleStore = CrossIsolateStore; @@ -1346,7 +1346,7 @@ impl JsRuntime { code: &str, ) -> Option> where - v8::Local<'s, T>: TryFrom, Error=v8::DataError>, + v8::Local<'s, T>: TryFrom, Error = v8::DataError>, { let scope = &mut v8::EscapableHandleScope::new(scope); let source = v8::String::new(scope, code).unwrap(); @@ -1482,7 +1482,7 @@ impl JsRuntime { pub fn call( &mut self, function: &v8::Global, - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { self.call_with_args(function, &[]) } @@ -1496,7 +1496,7 @@ impl JsRuntime { pub fn scoped_call( scope: &mut v8::HandleScope, function: &v8::Global, - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { Self::scoped_call_with_args(scope, function, &[]) } @@ -1511,7 +1511,7 @@ impl JsRuntime { &mut self, function: &v8::Global, args: &[v8::Global], - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { let scope = &mut self.handle_scope(); Self::scoped_call_with_args(scope, function, args) } @@ -1527,7 +1527,7 @@ impl JsRuntime { scope: &mut v8::HandleScope, function: &v8::Global, args: &[v8::Global], - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { let scope = &mut v8::TryCatch::new(scope); let cb = function.open(scope); let this = v8::undefined(scope).into(); @@ -1692,7 +1692,7 @@ impl JsRuntime { pub fn resolve( &mut self, promise: v8::Global, - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { let scope = &mut self.handle_scope(); Self::scoped_resolve(scope, promise) } @@ -1704,7 +1704,7 @@ impl JsRuntime { pub fn scoped_resolve( scope: &mut v8::HandleScope, promise: v8::Global, - ) -> impl Future, CoreError>> { + ) -> impl Future, CoreError>> { let promise = v8::Local::new(scope, promise); if !promise.is_promise() { return RcPromiseFuture::new(Ok(v8::Global::new(scope, promise))); @@ -1769,7 +1769,7 @@ impl JsRuntime { /// `Promise resolution is still pending but the event loop has already resolved` pub async fn with_event_loop_promise<'fut, T, E>( &mut self, - mut fut: impl Future> + Unpin + 'fut, + mut fut: impl Future> + Unpin + 'fut, poll_options: PollEventLoopOptions, ) -> Result where @@ -1789,7 +1789,7 @@ impl JsRuntime { } Poll::Pending }) - .await + .await } /// A utility function that run provided future concurrently with the event loop. @@ -1800,7 +1800,7 @@ impl JsRuntime { /// Useful for interacting with local inspector session. pub async fn with_event_loop_future<'fut, T, E>( &mut self, - mut fut: impl Future> + Unpin + 'fut, + mut fut: impl Future> + Unpin + 'fut, poll_options: PollEventLoopOptions, ) -> Result where @@ -1819,7 +1819,7 @@ impl JsRuntime { } Poll::Pending }) - .await + .await } /// Runs a single tick of event loop @@ -2109,7 +2109,7 @@ impl JsRuntimeForSnapshot { .borrow() .clone() } - .map(|cb| data_store.register(cb)); + .map(|cb| data_store.register(cb)); let snapshotted_data = SnapshottedData { module_map_data, @@ -2179,10 +2179,10 @@ impl EventLoopPendingState { .borrow() .is_empty() || !state - .exception_state - .pending_handled_promise_rejections - .borrow() - .is_empty(); + .exception_state + .pending_handled_promise_rejections + .borrow() + .is_empty(); let has_pending_refed_ops = has_pending_tasks || has_pending_refed_timers || num_pending_ops > num_unrefed_ops; @@ -2296,7 +2296,7 @@ impl JsRuntime { pub fn mod_evaluate( &mut self, id: ModuleId, - ) -> impl Future> { + ) -> impl Future> { let isolate = &mut self.inner.v8_isolate; let realm = &self.inner.main_realm; let scope = &mut realm.handle_scope(isolate); @@ -2570,11 +2570,11 @@ impl JsRuntime { .complete(RuntimeActivityType::Timer, timers[i].0 as _); } // depth, id, function - let value = v8::Integer::new(scope, timers[i].1.1 as _); + let value = v8::Integer::new(scope, timers[i].1 .1 as _); arr.set_index(scope, (i * 3) as _, value.into()); let value = v8::Number::new(scope, timers[i].0 as _); arr.set_index(scope, (i * 3 + 1) as _, value.into()); - let value = v8::Local::new(scope, timers[i].1.0.clone()); + let value = v8::Local::new(scope, timers[i].1 .0.clone()); arr.set_index(scope, (i * 3 + 2) as _, value.into()); } arr.into() From 5fb5e0b29832038c2ca1ef5459be62d05b54f591 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 26 Aug 2024 14:34:15 +0200 Subject: [PATCH 12/52] lints --- core/error.rs | 2 +- core/io/resource_table.rs | 11 ++++------- core/runtime/bindings.rs | 19 ++++++++++--------- 3 files changed, 15 insertions(+), 17 deletions(-) diff --git a/core/error.rs b/core/error.rs index 84b0da446..0b2ab15d8 100644 --- a/core/error.rs +++ b/core/error.rs @@ -166,7 +166,7 @@ fn js_class_and_message_to_exception<'s>( "RangeError" => v8::Exception::range_error(scope, message), "ReferenceError" => v8::Exception::reference_error(scope, message), "SyntaxError" => v8::Exception::syntax_error(scope, message), - "Error" | _ => v8::Exception::error(scope, message), + _ => v8::Exception::error(scope, message), } } diff --git a/core/io/resource_table.rs b/core/io/resource_table.rs index 4a3a200fd..1ef56d966 100644 --- a/core/io/resource_table.rs +++ b/core/io/resource_table.rs @@ -86,7 +86,7 @@ impl ResourceTable { .get(&rid) .and_then(|rc| rc.downcast_rc::()) .cloned() - .ok_or_else(|| ResourceError::BadResourceId) + .ok_or(ResourceError::BadResourceId) } pub fn get_any( @@ -97,7 +97,7 @@ impl ResourceTable { .index .get(&rid) .cloned() - .ok_or_else(|| ResourceError::BadResourceId) + .ok_or(ResourceError::BadResourceId) } /// Replaces a resource with a new resource. @@ -141,10 +141,7 @@ impl ResourceTable { &mut self, rid: ResourceId, ) -> Result, ResourceError> { - self - .index - .remove(&rid) - .ok_or_else(|| ResourceError::BadResourceId) + self.index.remove(&rid).ok_or(ResourceError::BadResourceId) } /// Removes the resource with the given `rid` from the resource table. If the @@ -158,7 +155,7 @@ impl ResourceTable { self .index .remove(&rid) - .ok_or_else(|| ResourceError::BadResourceId) + .ok_or(ResourceError::BadResourceId) .map(|resource| resource.close()) } diff --git a/core/runtime/bindings.rs b/core/runtime/bindings.rs index a06653235..d0f2cba56 100644 --- a/core/runtime/bindings.rs +++ b/core/runtime/bindings.rs @@ -419,6 +419,7 @@ pub extern "C" fn wasm_async_resolve_promise_callback( } } +#[allow(clippy::unnecessary_wraps)] pub fn host_import_module_dynamically_callback<'s>( scope: &mut v8::HandleScope<'s>, _host_defined_options: v8::Local<'s, v8::Data>, @@ -534,7 +535,7 @@ pub extern "C" fn host_initialize_import_meta_object_callback( scope, "WebAssembly is not available in this environment", ) - .unwrap(); + .unwrap(); let exception = v8::Exception::error(scope, message); scope.throw_exception(exception); return; @@ -753,10 +754,10 @@ pub(crate) fn watch_promise<'s, F>( ) -> Option> where F: FnOnce( - &mut v8::HandleScope, - v8::ReturnValue, - Result, v8::Local>, - ) + 'static, + &mut v8::HandleScope, + v8::ReturnValue, + Result, v8::Local>, + ) + 'static, { let external = v8::External::new(scope, Box::into_raw(Box::new(Some(f))) as _); @@ -776,8 +777,8 @@ where f(scope, rv, Ok(args.get(0))); }, ) - .data(external.into()) - .build(scope); + .data(external.into()) + .build(scope); let on_rejected = v8::Function::builder( |scope: &mut v8::HandleScope, @@ -788,8 +789,8 @@ where f(scope, rv, Err(args.get(0))); }, ) - .data(external.into()) - .build(scope); + .data(external.into()) + .build(scope); // function builders will return None if the runtime is shutting down let (Some(on_fulfilled), Some(on_rejected)) = (on_fulfilled, on_rejected) From 6483eb8df21501395188707887dc553a2ece5622 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 26 Aug 2024 16:05:41 +0200 Subject: [PATCH 13/52] fix --- core/error.rs | 17 +++++++++-------- core/runtime/bindings.rs | 18 +++++++++--------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/core/error.rs b/core/error.rs index 0b2ab15d8..3d2a39d71 100644 --- a/core/error.rs +++ b/core/error.rs @@ -18,7 +18,6 @@ use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write as _; -use thiserror::__private::AsDynError; /// A generic wrapper that can encapsulate any concrete error type. // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. @@ -84,6 +83,7 @@ pub enum CoreError { impl CoreError { pub fn print_with_cause(&self) -> String { + use std::error::Error; let mut err_message = self.to_string(); if let Some(source) = self.source() { @@ -102,7 +102,7 @@ impl CoreError { ) -> v8::Global { let err_string = self.get_message().to_string(); let mut error_chain = vec![]; - let mut intermediary_error = Some(self.as_dyn_error()); + let mut intermediary_error: Option<&(dyn Error)> = Some(&self); while let Some(err) = intermediary_error { if let Some(source) = err.source() { @@ -389,7 +389,7 @@ impl JsNativeError { #[macro_export] macro_rules! js_error_wrapper { ($err_path:path, $err_name:ident, $js_err_type:tt) => { - deno_core::js_error_wrapper!($err_path, $err_name, |_| $js_err_type); + deno_core::js_error_wrapper!($err_path, $err_name, |_error| $js_err_type); }; ($err_path:path, $err_name:ident, |$inner:ident| $js_err_type:tt) => { #[derive(Debug)] @@ -404,15 +404,16 @@ macro_rules! js_error_wrapper { self.0.source() } } + impl std::fmt::Display for $err_name { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } + } impl deno_core::error::JsErrorClass for $err_name { fn get_class(&self) -> &'static str { let $inner = &self.0; $js_err_type } - - fn get_message(&self) -> Cow<'static, str> { - self.0.to_string().into() - } } }; } @@ -427,7 +428,7 @@ impl std::fmt::Debug for StdAnyError { } impl std::fmt::Display for StdAnyError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } diff --git a/core/runtime/bindings.rs b/core/runtime/bindings.rs index d0f2cba56..f53926473 100644 --- a/core/runtime/bindings.rs +++ b/core/runtime/bindings.rs @@ -535,7 +535,7 @@ pub extern "C" fn host_initialize_import_meta_object_callback( scope, "WebAssembly is not available in this environment", ) - .unwrap(); + .unwrap(); let exception = v8::Exception::error(scope, message); scope.throw_exception(exception); return; @@ -754,10 +754,10 @@ pub(crate) fn watch_promise<'s, F>( ) -> Option> where F: FnOnce( - &mut v8::HandleScope, - v8::ReturnValue, - Result, v8::Local>, - ) + 'static, + &mut v8::HandleScope, + v8::ReturnValue, + Result, v8::Local>, + ) + 'static, { let external = v8::External::new(scope, Box::into_raw(Box::new(Some(f))) as _); @@ -777,8 +777,8 @@ where f(scope, rv, Ok(args.get(0))); }, ) - .data(external.into()) - .build(scope); + .data(external.into()) + .build(scope); let on_rejected = v8::Function::builder( |scope: &mut v8::HandleScope, @@ -789,8 +789,8 @@ where f(scope, rv, Err(args.get(0))); }, ) - .data(external.into()) - .build(scope); + .data(external.into()) + .build(scope); // function builders will return None if the runtime is shutting down let (Some(on_fulfilled), Some(on_rejected)) = (on_fulfilled, on_rejected) From eb9d8e0030238e1126935696bfe01f68943d6902 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 26 Aug 2024 16:17:22 +0200 Subject: [PATCH 14/52] lints --- core/runtime/ops.rs | 65 +++++++++++++++------------------- core/runtime/tests/misc.rs | 2 ++ core/runtime/tests/ops.rs | 7 ++++ core/runtime/tests/snapshot.rs | 1 + 4 files changed, 38 insertions(+), 37 deletions(-) diff --git a/core/runtime/ops.rs b/core/runtime/ops.rs index ba66af656..541c45b38 100644 --- a/core/runtime/ops.rs +++ b/core/runtime/ops.rs @@ -34,7 +34,7 @@ pub fn map_async_op_infallible( lazy: bool, deferred: bool, promise_id: i32, - op: impl Future + 'static, + op: impl Future + 'static, rv_map: V8RetValMapper, ) -> Option { ctx.op_driver().submit_op_infallible_scheduling( @@ -55,7 +55,7 @@ pub fn map_async_op_fallible< lazy: bool, deferred: bool, promise_id: i32, - op: impl Future> + 'static, + op: impl Future> + 'static, rv_map: V8RetValMapper, ) -> Option> { ctx.op_driver().submit_op_fallible_scheduling( @@ -886,6 +886,7 @@ mod tests { Err(JsNativeError::generic("failed!!!").into()) } + #[allow(clippy::unnecessary_wraps)] #[op2(fast)] pub fn op_test_result_void_ok() -> Result<(), OpError> { Ok(()) @@ -908,15 +909,14 @@ mod tests { } #[tokio::test(flavor = "current_thread")] - pub async fn test_op_result_void_switch( - ) -> Result<(), Box> { + pub async fn test_op_result_void_switch() -> Result<(), Box> { RETURN_COUNT.with(|count| count.set(0)); let err = run_test2( JIT_ITERATIONS, "op_test_result_void_switch", "op_test_result_void_switch();", ) - .expect_err("Expected this to fail"); + .expect_err("Expected this to fail"); let CoreError::Js(js_err) = err.downcast::().unwrap() else { unreachable!(); }; @@ -930,14 +930,14 @@ mod tests { Err(JsNativeError::generic("failed!!!").into()) } + #[allow(clippy::unnecessary_wraps)] #[op2(fast)] pub fn op_test_result_primitive_ok() -> Result { Ok(123) } #[tokio::test] - pub async fn test_op_result_primitive( - ) -> Result<(), Box> { + pub async fn test_op_result_primitive() -> Result<(), Box> { run_test2( JIT_ITERATIONS, "op_test_result_primitive_err", @@ -1663,8 +1663,7 @@ mod tests { } #[tokio::test] - pub async fn test_op_buffer_jsbuffer( - ) -> Result<(), Box> { + pub async fn test_op_buffer_jsbuffer() -> Result<(), Box> { run_test2( JIT_ITERATIONS, "op_buffer_jsbuffer", @@ -1739,8 +1738,7 @@ mod tests { } #[tokio::test] - pub async fn test_op_buffer_any_length( - ) -> Result<(), Box> { + pub async fn test_op_buffer_any_length() -> Result<(), Box> { run_test2( JIT_ITERATIONS, "op_buffer_any_length", @@ -1799,8 +1797,7 @@ mod tests { } #[tokio::test] - pub async fn test_op_arraybuffer_slice( - ) -> Result<(), Box> { + pub async fn test_op_arraybuffer_slice() -> Result<(), Box> { // Zero-length buffers run_test2( JIT_ITERATIONS, @@ -1890,8 +1887,7 @@ mod tests { } #[tokio::test] - pub async fn test_op_buffer_bytesmut( - ) -> Result<(), Box> { + pub async fn test_op_buffer_bytesmut() -> Result<(), Box> { run_test2( 10, "op_buffer_bytesmut", @@ -2114,19 +2110,19 @@ mod tests { "op_async_number", "assert(await op_async_number(__index__) == __index__)", ) - .await?; + .await?; run_async_test( JIT_ITERATIONS, "op_async_add", "assert(await op_async_add(__index__, 100) == __index__ + 100)", ) - .await?; + .await?; run_async_test( 10, "op_async_add_smi", "assert(await op_async_add_smi(__index__, 100) == __index__ + 100)", ) - .await?; + .await?; // See note about overflow on the op method run_async_test( 10, @@ -2142,7 +2138,7 @@ mod tests { } #[op2(async)] - fn op_async_sleep_impl() -> impl Future { + fn op_async_sleep_impl() -> impl Future { tokio::time::sleep(Duration::from_millis(500)) } @@ -2161,14 +2157,13 @@ mod tests { } #[tokio::test] - pub async fn test_op_async_sleep_error( - ) -> Result<(), Box> { + pub async fn test_op_async_sleep_error() -> Result<(), Box> { run_async_test( 5, "op_async_sleep_error", "try { await op_async_sleep_error(); assert(false) } catch (e) {}", ) - .await?; + .await?; Ok(()) } @@ -2190,7 +2185,7 @@ mod tests { "op_async_deferred_success", "assert(await op_async_deferred_success() == 42)", ) - .await?; + .await?; run_async_test( JIT_SLOW_ITERATIONS, "op_async_deferred_error", @@ -2217,7 +2212,7 @@ mod tests { "op_async_lazy_success", "assert(await op_async_lazy_success() == 42)", ) - .await?; + .await?; run_async_test( JIT_SLOW_ITERATIONS, "op_async_lazy_error", @@ -2232,7 +2227,7 @@ mod tests { #[op2(async)] pub fn op_async_result_impl( mode: u8, - ) -> Result>, OpError> { + ) -> Result>, OpError> { if mode == 0 { return Err(JsNativeError::generic("early exit").into()); } @@ -2249,8 +2244,7 @@ mod tests { } #[tokio::test] - pub async fn test_op_async_result_impl( - ) -> Result<(), Box> { + pub async fn test_op_async_result_impl() -> Result<(), Box> { for (n, msg) in [ (0, "early exit"), (1, "early async exit"), @@ -2303,7 +2297,7 @@ mod tests { } #[op2(async)] - fn op_async_buffer_impl(#[buffer] input: &[u8]) -> impl Future { + fn op_async_buffer_impl(#[buffer] input: &[u8]) -> impl Future { let l = input.len(); async move { l as _ } } @@ -2328,7 +2322,7 @@ mod tests { "op_async_buffer_impl", "assert(await op_async_buffer_impl(new Uint8Array(10)) == 10)", ) - .await?; + .await?; Ok(()) } @@ -2348,7 +2342,7 @@ mod tests { "op_external_make, op_async_external", "await op_async_external(op_external_make())", ) - .await?; + .await?; Ok(()) } @@ -2362,14 +2356,13 @@ mod tests { } #[tokio::test] - pub async fn test_op_async_serde_option_v8( - ) -> Result<(), Box> { + pub async fn test_op_async_serde_option_v8() -> Result<(), Box> { run_async_test( 2, "op_async_serde_option_v8", "assert((await op_async_serde_option_v8({s: 'abc'})).s == 'abc!')", ) - .await?; + .await?; Ok(()) } @@ -2400,8 +2393,7 @@ mod tests { } #[tokio::test] - pub async fn test_op_number_to_from_v8( - ) -> Result<(), Box> { + pub async fn test_op_number_to_from_v8() -> Result<(), Box> { run_test2( JIT_ITERATIONS, "op_number_to_from_v8", @@ -2459,8 +2451,7 @@ mod tests { } #[tokio::test] - pub async fn test_op_bool_to_from_v8( - ) -> Result<(), Box> { + pub async fn test_op_bool_to_from_v8() -> Result<(), Box> { run_test2( JIT_ITERATIONS, "op_bool_to_from_v8", diff --git a/core/runtime/tests/misc.rs b/core/runtime/tests/misc.rs index c5a1da80f..d49aa76bf 100644 --- a/core/runtime/tests/misc.rs +++ b/core/runtime/tests/misc.rs @@ -706,12 +706,14 @@ fn test_has_tick_scheduled() { static MACROTASK: AtomicUsize = AtomicUsize::new(0); static NEXT_TICK: AtomicUsize = AtomicUsize::new(0); + #[allow(clippy::unnecessary_wraps)] #[op2(fast)] fn op_macrotask() -> Result<(), OpError> { MACROTASK.fetch_add(1, Ordering::Relaxed); Ok(()) } + #[allow(clippy::unnecessary_wraps)] #[op2(fast)] fn op_next_tick() -> Result<(), OpError> { NEXT_TICK.fetch_add(1, Ordering::Relaxed); diff --git a/core/runtime/tests/ops.rs b/core/runtime/tests/ops.rs index ae813af95..885582e8d 100644 --- a/core/runtime/tests/ops.rs +++ b/core/runtime/tests/ops.rs @@ -59,6 +59,7 @@ async fn test_async_opstate_borrow() { #[tokio::test] async fn test_sync_op_serialize_object_with_numbers_as_keys() { + #[allow(clippy::unnecessary_wraps)] #[op2] fn op_sync_serialize_object_with_numbers_as_keys( #[serde] value: serde_json::Value, @@ -144,6 +145,7 @@ async fn test_async_op_serialize_object_with_numbers_as_keys() { #[test] fn test_op_return_serde_v8_error() { + #[allow(clippy::unnecessary_wraps)] #[op2] #[serde] fn op_err() -> Result, OpError> { @@ -165,6 +167,7 @@ fn test_op_return_serde_v8_error() { #[test] fn test_op_high_arity() { + #[allow(clippy::unnecessary_wraps)] #[op2(fast)] #[number] fn op_add_4( @@ -190,6 +193,7 @@ fn test_op_high_arity() { #[test] fn test_op_disabled() { + #[allow(clippy::unnecessary_wraps)] #[op2(fast)] #[number] fn op_foo() -> Result { @@ -214,11 +218,13 @@ fn test_op_disabled() { #[test] fn test_op_detached_buffer() { + #[allow(clippy::unnecessary_wraps)] #[op2] fn op_sum_take(#[buffer(detach)] b: JsBuffer) -> Result { Ok(b.as_ref().iter().clone().map(|x| *x as u32).sum()) } + #[allow(clippy::unnecessary_wraps)] #[op2] #[buffer] fn op_boomerang(#[buffer(detach)] b: JsBuffer) -> Result { @@ -293,6 +299,7 @@ fn duplicate_op_names() { mod a { use super::*; + #[allow(clippy::unnecessary_wraps)] #[op2] #[string] pub fn op_test() -> Result { diff --git a/core/runtime/tests/snapshot.rs b/core/runtime/tests/snapshot.rs index a33a8171a..d13012734 100644 --- a/core/runtime/tests/snapshot.rs +++ b/core/runtime/tests/snapshot.rs @@ -230,6 +230,7 @@ fn es_snapshot() { } } + #[allow(clippy::unnecessary_wraps)] #[op2] #[string] fn op_test() -> Result { From e21ce6f08a9a872b0b2b54823530e0bbf447be6f Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 26 Aug 2024 16:18:56 +0200 Subject: [PATCH 15/52] fmt --- core/runtime/ops.rs | 63 ++++++++++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 26 deletions(-) diff --git a/core/runtime/ops.rs b/core/runtime/ops.rs index 541c45b38..18336416a 100644 --- a/core/runtime/ops.rs +++ b/core/runtime/ops.rs @@ -34,7 +34,7 @@ pub fn map_async_op_infallible( lazy: bool, deferred: bool, promise_id: i32, - op: impl Future + 'static, + op: impl Future + 'static, rv_map: V8RetValMapper, ) -> Option { ctx.op_driver().submit_op_infallible_scheduling( @@ -55,7 +55,7 @@ pub fn map_async_op_fallible< lazy: bool, deferred: bool, promise_id: i32, - op: impl Future> + 'static, + op: impl Future> + 'static, rv_map: V8RetValMapper, ) -> Option> { ctx.op_driver().submit_op_fallible_scheduling( @@ -909,14 +909,15 @@ mod tests { } #[tokio::test(flavor = "current_thread")] - pub async fn test_op_result_void_switch() -> Result<(), Box> { + pub async fn test_op_result_void_switch( + ) -> Result<(), Box> { RETURN_COUNT.with(|count| count.set(0)); let err = run_test2( JIT_ITERATIONS, "op_test_result_void_switch", "op_test_result_void_switch();", ) - .expect_err("Expected this to fail"); + .expect_err("Expected this to fail"); let CoreError::Js(js_err) = err.downcast::().unwrap() else { unreachable!(); }; @@ -937,7 +938,8 @@ mod tests { } #[tokio::test] - pub async fn test_op_result_primitive() -> Result<(), Box> { + pub async fn test_op_result_primitive( + ) -> Result<(), Box> { run_test2( JIT_ITERATIONS, "op_test_result_primitive_err", @@ -1663,7 +1665,8 @@ mod tests { } #[tokio::test] - pub async fn test_op_buffer_jsbuffer() -> Result<(), Box> { + pub async fn test_op_buffer_jsbuffer( + ) -> Result<(), Box> { run_test2( JIT_ITERATIONS, "op_buffer_jsbuffer", @@ -1738,7 +1741,8 @@ mod tests { } #[tokio::test] - pub async fn test_op_buffer_any_length() -> Result<(), Box> { + pub async fn test_op_buffer_any_length( + ) -> Result<(), Box> { run_test2( JIT_ITERATIONS, "op_buffer_any_length", @@ -1797,7 +1801,8 @@ mod tests { } #[tokio::test] - pub async fn test_op_arraybuffer_slice() -> Result<(), Box> { + pub async fn test_op_arraybuffer_slice( + ) -> Result<(), Box> { // Zero-length buffers run_test2( JIT_ITERATIONS, @@ -1887,7 +1892,8 @@ mod tests { } #[tokio::test] - pub async fn test_op_buffer_bytesmut() -> Result<(), Box> { + pub async fn test_op_buffer_bytesmut( + ) -> Result<(), Box> { run_test2( 10, "op_buffer_bytesmut", @@ -2110,19 +2116,19 @@ mod tests { "op_async_number", "assert(await op_async_number(__index__) == __index__)", ) - .await?; + .await?; run_async_test( JIT_ITERATIONS, "op_async_add", "assert(await op_async_add(__index__, 100) == __index__ + 100)", ) - .await?; + .await?; run_async_test( 10, "op_async_add_smi", "assert(await op_async_add_smi(__index__, 100) == __index__ + 100)", ) - .await?; + .await?; // See note about overflow on the op method run_async_test( 10, @@ -2138,7 +2144,7 @@ mod tests { } #[op2(async)] - fn op_async_sleep_impl() -> impl Future { + fn op_async_sleep_impl() -> impl Future { tokio::time::sleep(Duration::from_millis(500)) } @@ -2157,13 +2163,14 @@ mod tests { } #[tokio::test] - pub async fn test_op_async_sleep_error() -> Result<(), Box> { + pub async fn test_op_async_sleep_error( + ) -> Result<(), Box> { run_async_test( 5, "op_async_sleep_error", "try { await op_async_sleep_error(); assert(false) } catch (e) {}", ) - .await?; + .await?; Ok(()) } @@ -2185,7 +2192,7 @@ mod tests { "op_async_deferred_success", "assert(await op_async_deferred_success() == 42)", ) - .await?; + .await?; run_async_test( JIT_SLOW_ITERATIONS, "op_async_deferred_error", @@ -2212,7 +2219,7 @@ mod tests { "op_async_lazy_success", "assert(await op_async_lazy_success() == 42)", ) - .await?; + .await?; run_async_test( JIT_SLOW_ITERATIONS, "op_async_lazy_error", @@ -2227,7 +2234,7 @@ mod tests { #[op2(async)] pub fn op_async_result_impl( mode: u8, - ) -> Result>, OpError> { + ) -> Result>, OpError> { if mode == 0 { return Err(JsNativeError::generic("early exit").into()); } @@ -2244,7 +2251,8 @@ mod tests { } #[tokio::test] - pub async fn test_op_async_result_impl() -> Result<(), Box> { + pub async fn test_op_async_result_impl( + ) -> Result<(), Box> { for (n, msg) in [ (0, "early exit"), (1, "early async exit"), @@ -2297,7 +2305,7 @@ mod tests { } #[op2(async)] - fn op_async_buffer_impl(#[buffer] input: &[u8]) -> impl Future { + fn op_async_buffer_impl(#[buffer] input: &[u8]) -> impl Future { let l = input.len(); async move { l as _ } } @@ -2322,7 +2330,7 @@ mod tests { "op_async_buffer_impl", "assert(await op_async_buffer_impl(new Uint8Array(10)) == 10)", ) - .await?; + .await?; Ok(()) } @@ -2342,7 +2350,7 @@ mod tests { "op_external_make, op_async_external", "await op_async_external(op_external_make())", ) - .await?; + .await?; Ok(()) } @@ -2356,13 +2364,14 @@ mod tests { } #[tokio::test] - pub async fn test_op_async_serde_option_v8() -> Result<(), Box> { + pub async fn test_op_async_serde_option_v8( + ) -> Result<(), Box> { run_async_test( 2, "op_async_serde_option_v8", "assert((await op_async_serde_option_v8({s: 'abc'})).s == 'abc!')", ) - .await?; + .await?; Ok(()) } @@ -2393,7 +2402,8 @@ mod tests { } #[tokio::test] - pub async fn test_op_number_to_from_v8() -> Result<(), Box> { + pub async fn test_op_number_to_from_v8( + ) -> Result<(), Box> { run_test2( JIT_ITERATIONS, "op_number_to_from_v8", @@ -2451,7 +2461,8 @@ mod tests { } #[tokio::test] - pub async fn test_op_bool_to_from_v8() -> Result<(), Box> { + pub async fn test_op_bool_to_from_v8( + ) -> Result<(), Box> { run_test2( JIT_ITERATIONS, "op_bool_to_from_v8", From f8c5f2b985897c5e699b1928c8c228f325b0974d Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 26 Aug 2024 22:21:25 +0200 Subject: [PATCH 16/52] lint --- core/error.rs | 11 +++++++++++ core/modules/loaders.rs | 8 ++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/core/error.rs b/core/error.rs index 3d2a39d71..4143d41f1 100644 --- a/core/error.rs +++ b/core/error.rs @@ -1774,6 +1774,17 @@ pub fn format_frame(frame: &JsStackFrame) -> String { mod tests { use super::*; + #[test] + fn test_anyhow_js_class() { + let err = anyhow::Error::msg("foo"); + assert_eq!(err.get_class(), "Error"); + assert_eq!(err.get_message(), "foo"); + + let err = anyhow::Error::new(JsNativeError::type_error("bar")); + assert_eq!(err.get_class(), "TypeError"); + assert_eq!(err.get_message(), "bar"); + } + #[test] fn test_format_file_name() { let file_name = format_file_name("data:,Hello%2C%20World%21"); diff --git a/core/modules/loaders.rs b/core/modules/loaders.rs index 113023c9c..cf78eed9e 100644 --- a/core/modules/loaders.rs +++ b/core/modules/loaders.rs @@ -45,8 +45,8 @@ pub enum ModuleLoaderError { .maybe_referrer.as_ref().map_or("(no referrer)", |referrer| referrer.as_str()) )] Unsupported { - specifier: ModuleSpecifier, - maybe_referrer: Option, + specifier: Box, + maybe_referrer: Option>, }, #[error(transparent)] Resolution(#[from] crate::ModuleResolutionError), @@ -209,8 +209,8 @@ impl ModuleLoader for NoopModuleLoader { _requested_module_type: RequestedModuleType, ) -> ModuleLoadResponse { ModuleLoadResponse::Sync(Err(ModuleLoaderError::Unsupported { - specifier: module_specifier.clone(), - maybe_referrer: maybe_referrer.cloned(), + specifier: Box::new(module_specifier.clone()), + maybe_referrer: maybe_referrer.map(|referrer| Box::new(referrer.clone())), })) } } From e00c1de1aa225d11ee7a2b4bb9d9a35e01f1dc8e Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 26 Aug 2024 22:27:52 +0200 Subject: [PATCH 17/52] fix --- core/runtime/tests/ops.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/core/runtime/tests/ops.rs b/core/runtime/tests/ops.rs index 885582e8d..5357a406a 100644 --- a/core/runtime/tests/ops.rs +++ b/core/runtime/tests/ops.rs @@ -322,6 +322,7 @@ fn duplicate_op_names() { #[test] fn ops_in_js_have_proper_names() { + #[allow(clippy::unnecessary_wraps)] #[op2] #[string] fn op_test_sync() -> Result { From 12e735ff942757773e63e6d55b1c13d7ab2a8471 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Tue, 27 Aug 2024 15:29:17 +0200 Subject: [PATCH 18/52] add get_additional_properties --- core/00_infra.js | 8 +++++--- core/error.rs | 24 +++++++++++++++--------- core/error_codes.rs | 21 ++++++++++----------- core/io/resource.rs | 13 +++++++------ core/lib.rs | 1 + core/modules/mod.rs | 2 +- core/runtime/op_driver/op_results.rs | 20 +++++++------------- 7 files changed, 46 insertions(+), 43 deletions(-) diff --git a/core/00_infra.js b/core/00_infra.js index 13c82691a..bd5f478da 100644 --- a/core/00_infra.js +++ b/core/00_infra.js @@ -180,9 +180,11 @@ const err = errorBuilder ? errorBuilder(res.message) : new Error( `Unregistered error class: "${className}"\n ${res.message}\n Classes of errors returned from ops should be registered via Deno.core.registerErrorClass().`, ); - // Set .code if error was a known OS error, see error_codes.rs - if (res.code) { - err.code = res.code; + + if (res.additional_properties) { + for (const [key, value] of res.additional_properties) { + res[key] = value; + } } // Strip eventLoopTick() calls from stack trace ErrorCaptureStackTrace(err, eventLoopTick); diff --git a/core/error.rs b/core/error.rs index 4143d41f1..0f88fea02 100644 --- a/core/error.rs +++ b/core/error.rs @@ -18,6 +18,7 @@ use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write as _; +use serde::de::StdError; /// A generic wrapper that can encapsulate any concrete error type. // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. @@ -144,6 +145,9 @@ pub trait JsErrorClass: Display + Debug + Send + Sync + 'static { fn get_message(&self) -> Cow<'static, str> { self.to_string().into() } + fn get_additional_properties(&self) -> Option> { + None + } fn throw(&self, scope: &mut v8::HandleScope) { let exception = js_class_and_message_to_exception( @@ -172,17 +176,11 @@ fn js_class_and_message_to_exception<'s>( impl JsErrorClass for anyhow::Error { fn get_class(&self) -> &'static str { - match self.downcast_ref::<&dyn JsErrorClass>() { - Some(err) => err.get_class(), - None => "Error", - } + "Error" } fn get_message(&self) -> Cow<'static, str> { - match self.downcast_ref::<&dyn JsErrorClass>() { - Some(err) => err.get_message(), - None => format!("{:#}", self).into(), - } + format!("{:#}", self).into() } } @@ -281,6 +279,9 @@ impl JsErrorClass for std::io::Error { } } } + fn get_additional_properties(&self) -> Option, Cow<'static, str>)>> { + crate::error_codes::get_error_code(&self).map(|code| vec![("code".into(), code.into())]) + } } impl JsErrorClass for std::env::VarError { @@ -311,6 +312,11 @@ impl JsErrorClass "Error" } } +impl JsErrorClass for tokio::task::JoinError { + fn get_class(&self) -> &'static str { + "Error" + } +} impl JsErrorClass for serde_json::Error { fn get_class(&self) -> &'static str { @@ -1780,7 +1786,7 @@ mod tests { assert_eq!(err.get_class(), "Error"); assert_eq!(err.get_message(), "foo"); - let err = anyhow::Error::new(JsNativeError::type_error("bar")); + let err = anyhow::Error::new(MaybeJsErrorClass::JsError(Box::new(JsNativeError::type_error("bar")))); assert_eq!(err.get_class(), "TypeError"); assert_eq!(err.get_message(), "bar"); } diff --git a/core/error_codes.rs b/core/error_codes.rs index 87fd39bd9..7c302fb57 100644 --- a/core/error_codes.rs +++ b/core/error_codes.rs @@ -1,18 +1,17 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. pub fn get_error_code( - err: &impl crate::error::JsErrorClass, + err: &std::io::Error, ) -> Option<&'static str> { - (err as &dyn std::any::Any) - .downcast_ref::() - .map(|e| match e.raw_os_error() { - Some(code) => get_os_error_code(code), - None => get_io_error_code(e), - }) - .and_then(|code| match code.is_empty() { - true => None, - false => Some(code), - }) + let code = match err.raw_os_error() { + Some(code) => get_os_error_code(code), + None => get_io_error_code(err), + }; + + match code.is_empty() { + true => None, + false => Some(code), + } } fn get_io_error_code(err: &std::io::Error) -> &'static str { diff --git a/core/io/resource.rs b/core/io/resource.rs index c390c267b..dddb687b0 100644 --- a/core/io/resource.rs +++ b/core/io/resource.rs @@ -6,7 +6,8 @@ // resources. Resources may or may not correspond to a real operating system // file descriptor (hence the different name). -use crate::error::JsNativeError; +use crate::error::{JsErrorClass}; +use crate::error::{JsNativeError}; use crate::io::AsyncResult; use crate::io::BufMutView; use crate::io::BufView; @@ -111,7 +112,7 @@ pub trait Resource: Any + 'static { /// Write an error state to this resource, if the resource supports it. fn write_error( self: Rc, - _error: crate::error::AnyError, + _error: impl JsErrorClass, ) -> AsyncResult<()> { Box::pin(futures::future::err(JsNativeError::not_supported().into())) } @@ -160,18 +161,18 @@ pub trait Resource: Any + 'static { fn read_byob_sync( self: Rc, data: &mut [u8], - ) -> Result { + ) -> Result { _ = data; - Err(JsNativeError::not_supported().into()) + Err(JsNativeError::not_supported()) } /// The same as [`write()`][Resource::write], but synchronous. fn write_sync( self: Rc, data: &[u8], - ) -> Result { + ) -> Result { _ = data; - Err(JsNativeError::not_supported().into()) + Err(JsNativeError::not_supported()) } /// The shutdown method can be used to asynchronously close the resource. It diff --git a/core/lib.rs b/core/lib.rs index a62837c9f..bf462a84d 100644 --- a/core/lib.rs +++ b/core/lib.rs @@ -37,6 +37,7 @@ mod web_timeout; // Re-exports pub use anyhow; +pub use thiserror; pub use deno_unsync as unsync; pub use futures; pub use parking_lot; diff --git a/core/modules/mod.rs b/core/modules/mod.rs index 4924bc9f8..0c7b6f468 100644 --- a/core/modules/mod.rs +++ b/core/modules/mod.rs @@ -1,5 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::exception_to_err_result; +use crate::error::{exception_to_err_result, JsErrorClass}; use crate::error::CoreError; use crate::fast_string::FastString; use crate::module_specifier::ModuleSpecifier; diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index e3817e599..a7a34c1ef 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -260,28 +260,22 @@ impl OpResult { } #[derive(Debug)] -pub struct OpError { - error: Box, - error_code: Option<&'static str>, -} +pub struct OpError(Box); impl std::fmt::Display for OpError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}: {}", - self.error.get_class(), - self.error.get_message() + self.0.get_class(), + self.0.get_message() ) } } impl From for OpError { fn from(err: T) -> Self { - Self { - error_code: crate::error_codes::get_error_code(&err), - error: Box::new(err), - } + Self(Box::new(err)) } } @@ -291,9 +285,9 @@ impl Serialize for OpError { S: serde::Serializer, { let mut serde_state = serializer.serialize_struct("OpError", 3)?; - serde_state.serialize_field("$err_class_name", self.error.get_class())?; - serde_state.serialize_field("message", &self.error.get_message())?; - serde_state.serialize_field("code", &self.error_code)?; + serde_state.serialize_field("$err_class_name", self.0.get_class())?; + serde_state.serialize_field("message", &self.0.get_message())?; + serde_state.serialize_field("additional_properties", &self.0.get_additional_properties())?; serde_state.end() } } From 5edf11cfaddd8e5796e24eac77d647c1606d130c Mon Sep 17 00:00:00 2001 From: crowlkats Date: Wed, 28 Aug 2024 11:46:48 +0200 Subject: [PATCH 19/52] clean up --- core/benches/snapshot/snapshot.rs | 15 +- core/error.rs | 54 +- core/error_codes.rs | 4 +- core/io/mod.rs | 3 +- core/io/resource.rs | 16 +- core/lib.rs | 3 +- core/modules/loaders.rs | 15 +- core/modules/map.rs | 2 +- core/modules/mod.rs | 7 +- core/modules/tests.rs | 14 +- core/ops_builtin.rs | 2 +- core/resources.rs | 612 --------------------- core/runtime/jsruntime.rs | 4 +- core/runtime/op_driver/op_results.rs | 21 +- testing/checkin/runner/mod.rs | 16 +- testing/checkin/runner/ops_io.rs | 6 +- testing/checkin/runner/ts_module_loader.rs | 9 +- 17 files changed, 104 insertions(+), 699 deletions(-) delete mode 100644 core/resources.rs diff --git a/core/benches/snapshot/snapshot.rs b/core/benches/snapshot/snapshot.rs index 28a100290..9693b0559 100644 --- a/core/benches/snapshot/snapshot.rs +++ b/core/benches/snapshot/snapshot.rs @@ -3,6 +3,7 @@ use criterion::*; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; +use deno_core::error::JsErrorClass; use deno_core::Extension; use deno_core::JsRuntime; use deno_core::JsRuntimeForSnapshot; @@ -48,10 +49,16 @@ fn make_extensions_ops() -> Vec { fake_extensions!(init_ops, a, b, c, d, e, f, g, h, i, j, k, l, m, n) } +deno_core::js_error_wrapper!( + deno_ast::ParseDiagnostic, + JsParseDiagnostic, + "TypeError" +); + pub fn maybe_transpile_source( specifier: ModuleName, source: ModuleCodeString, -) -> Result<(ModuleCodeString, Option), anyhow::Error> { +) -> Result<(ModuleCodeString, Option), Box> { let media_type = MediaType::TypeScript; let parsed = deno_ast::parse_module(ParseParams { @@ -61,7 +68,8 @@ pub fn maybe_transpile_source( capture_tokens: false, scope_analysis: false, maybe_syntax: None, - })?; + }) + .map_err(JsParseDiagnostic)?; let transpiled_source = parsed .transpile( &deno_ast::TranspileOptions { @@ -73,7 +81,8 @@ pub fn maybe_transpile_source( inline_sources: true, ..Default::default() }, - )? + ) + .map_err(anyhow::Error::new)? .into_source(); Ok(( String::from_utf8(transpiled_source.source).unwrap().into(), diff --git a/core/error.rs b/core/error.rs index 0f88fea02..ec4eb91b0 100644 --- a/core/error.rs +++ b/core/error.rs @@ -18,7 +18,6 @@ use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write as _; -use serde::de::StdError; /// A generic wrapper that can encapsulate any concrete error type. // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. @@ -33,7 +32,7 @@ pub enum CoreError { #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] - ExtensionTranspiler(anyhow::Error), + ExtensionTranspiler(JsNativeError), #[error("Failed to parse {0}")] Parse(FastStaticString), #[error("Failed to execute {0}")] @@ -145,9 +144,12 @@ pub trait JsErrorClass: Display + Debug + Send + Sync + 'static { fn get_message(&self) -> Cow<'static, str> { self.to_string().into() } - fn get_additional_properties(&self) -> Option> { + fn get_additional_properties(&self) -> Option, Cow<'static, str>)>> { None } + fn to_native(self) -> JsNativeError where Self: Sized { + JsNativeError::from_err(self) + } fn throw(&self, scope: &mut v8::HandleScope) { let exception = js_class_and_message_to_exception( @@ -279,8 +281,12 @@ impl JsErrorClass for std::io::Error { } } } - fn get_additional_properties(&self) -> Option, Cow<'static, str>)>> { - crate::error_codes::get_error_code(&self).map(|code| vec![("code".into(), code.into())]) + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + crate::error_codes::get_error_code(&self) + .map(|code| vec![("code".into(), code.into())]) } } @@ -342,13 +348,21 @@ impl JsErrorClass for url::ParseError { } } -#[derive(Debug, thiserror::Error)] -#[error("{class}: {message}")] +#[derive(Debug)] pub struct JsNativeError { - pub class: &'static str, + class: &'static str, message: Cow<'static, str>, + pub source: Option>, } +impl Display for JsNativeError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{}: {}", self.class, self.message) + } +} + +impl Error for JsNativeError {} + impl JsErrorClass for JsNativeError { fn get_class(&self) -> &'static str { self.class @@ -367,9 +381,19 @@ impl JsNativeError { JsNativeError { class, message: message.into(), + source: None, } } + pub fn from_err(err: T) -> Self { + Self { + class: err.get_class(), + message: err.get_message(), + source: Some(Box::new(err)), + } + } + + pub fn generic(message: impl Into>) -> JsNativeError { Self::new("Error", message) } @@ -466,7 +490,8 @@ pub fn to_v8_error<'a>( let class = v8::String::new(tc_scope, error.get_class()).unwrap(); let message = v8::String::new(tc_scope, &error.get_message()).unwrap(); let mut args = vec![class.into(), message.into()]; - if let Some(code) = crate::error_codes::get_error_code(error) { + + if let Some(code) = (error as &dyn std::any::Any).downcast_ref::().and_then(crate::error_codes::get_error_code) { args.push(v8::String::new(tc_scope, code).unwrap().into()); } let maybe_exception = cb.call(tc_scope, this, &args); @@ -1780,17 +1805,6 @@ pub fn format_frame(frame: &JsStackFrame) -> String { mod tests { use super::*; - #[test] - fn test_anyhow_js_class() { - let err = anyhow::Error::msg("foo"); - assert_eq!(err.get_class(), "Error"); - assert_eq!(err.get_message(), "foo"); - - let err = anyhow::Error::new(MaybeJsErrorClass::JsError(Box::new(JsNativeError::type_error("bar")))); - assert_eq!(err.get_class(), "TypeError"); - assert_eq!(err.get_message(), "bar"); - } - #[test] fn test_format_file_name() { let file_name = format_file_name("data:,Hello%2C%20World%21"); diff --git a/core/error_codes.rs b/core/error_codes.rs index 7c302fb57..09277a608 100644 --- a/core/error_codes.rs +++ b/core/error_codes.rs @@ -1,8 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -pub fn get_error_code( - err: &std::io::Error, -) -> Option<&'static str> { +pub fn get_error_code(err: &std::io::Error) -> Option<&'static str> { let code = match err.raw_os_error() { Some(code) => get_os_error_code(code), None => get_io_error_code(err), diff --git a/core/io/mod.rs b/core/io/mod.rs index 696c217ed..688cf3e52 100644 --- a/core/io/mod.rs +++ b/core/io/mod.rs @@ -25,10 +25,11 @@ pub use resource_handle::ResourceHandleSocket; pub use resource_table::ResourceError; pub use resource_table::ResourceId; pub use resource_table::ResourceTable; +use crate::error::JsNativeError; /// Returned by resource shutdown methods pub type AsyncResult = - Pin>>>; + Pin>>>; pub enum WriteOutcome { Partial { nwritten: usize, view: BufView }, diff --git a/core/io/resource.rs b/core/io/resource.rs index dddb687b0..d3099dd33 100644 --- a/core/io/resource.rs +++ b/core/io/resource.rs @@ -6,8 +6,8 @@ // resources. Resources may or may not correspond to a real operating system // file descriptor (hence the different name). -use crate::error::{JsErrorClass}; -use crate::error::{JsNativeError}; +use crate::error::JsErrorClass; +use crate::error::JsNativeError; use crate::io::AsyncResult; use crate::io::BufMutView; use crate::io::BufView; @@ -112,9 +112,9 @@ pub trait Resource: Any + 'static { /// Write an error state to this resource, if the resource supports it. fn write_error( self: Rc, - _error: impl JsErrorClass, + _error: &dyn JsErrorClass, ) -> AsyncResult<()> { - Box::pin(futures::future::err(JsNativeError::not_supported().into())) + Box::pin(futures::future::err(JsNativeError::not_supported())) } /// Write a single chunk of data to the resource. The operation may not be @@ -126,7 +126,7 @@ pub trait Resource: Any + 'static { /// with a "not supported" error. fn write(self: Rc, buf: BufView) -> AsyncResult { _ = buf; - Box::pin(futures::future::err(JsNativeError::not_supported().into())) + Box::pin(futures::future::err(JsNativeError::not_supported())) } /// Write an entire chunk of data to the resource. Unlike `write()`, this will @@ -161,7 +161,7 @@ pub trait Resource: Any + 'static { fn read_byob_sync( self: Rc, data: &mut [u8], - ) -> Result { + ) -> Result { _ = data; Err(JsNativeError::not_supported()) } @@ -170,7 +170,7 @@ pub trait Resource: Any + 'static { fn write_sync( self: Rc, data: &[u8], - ) -> Result { + ) -> Result { _ = data; Err(JsNativeError::not_supported()) } @@ -181,7 +181,7 @@ pub trait Resource: Any + 'static { /// If this method is not implemented, the default implementation will error /// with a "not supported" error. fn shutdown(self: Rc) -> AsyncResult<()> { - Box::pin(futures::future::err(JsNativeError::not_supported().into())) + Box::pin(futures::future::err(JsNativeError::not_supported())) } /// Resources may implement the `close()` trait method if they need to do diff --git a/core/lib.rs b/core/lib.rs index bf462a84d..a342e5955 100644 --- a/core/lib.rs +++ b/core/lib.rs @@ -37,7 +37,6 @@ mod web_timeout; // Re-exports pub use anyhow; -pub use thiserror; pub use deno_unsync as unsync; pub use futures; pub use parking_lot; @@ -51,6 +50,7 @@ pub use serde_v8::StringOrBuffer; pub use serde_v8::ToJsBuffer; pub use serde_v8::U16String; pub use sourcemap; +pub use thiserror; pub use url; pub use v8; @@ -108,7 +108,6 @@ pub use crate::module_specifier::specifier_has_uri_scheme; pub use crate::module_specifier::ModuleResolutionError; pub use crate::module_specifier::ModuleSpecifier; pub use crate::modules::CustomModuleEvaluationKind; -pub use crate::modules::ExtModuleLoaderCb; pub use crate::modules::FsModuleLoader; pub use crate::modules::ModuleCodeBytes; pub use crate::modules::ModuleCodeString; diff --git a/core/modules/loaders.rs b/core/modules/loaders.rs index cf78eed9e..72119a9c1 100644 --- a/core/modules/loaders.rs +++ b/core/modules/loaders.rs @@ -1,7 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::error::JsErrorClass; use crate::error::JsNativeError; -use crate::extensions::ExtensionFileSource; use crate::module_specifier::ModuleSpecifier; use crate::modules::IntoModuleCodeString; use crate::modules::ModuleCodeString; @@ -80,6 +79,11 @@ impl From for ModuleLoaderError { ModuleLoaderError::Core(CoreError::Io(err)) } } +impl From for ModuleLoaderError { + fn from(err: JsNativeError) -> Self { + ModuleLoaderError::Core(CoreError::JsNative(err)) + } +} /// Result of calling `ModuleLoader::load`. pub enum ModuleLoadResponse { @@ -215,11 +219,6 @@ impl ModuleLoader for NoopModuleLoader { } } -/// Function that can be passed to the `ExtModuleLoader` that allows to -/// transpile sources before passing to V8. -pub type ExtModuleLoaderCb = - Box Result>; - pub(crate) struct ExtModuleLoader { sources: RefCell>, } @@ -400,9 +399,9 @@ impl ModuleLoader for FsModuleLoader { let module_specifier = module_specifier.clone(); let fut = async move { let path = module_specifier.to_file_path().map_err(|_| { - anyhow::Error::from(JsNativeError::generic(format!( + JsNativeError::generic(format!( "Provided module specifier \"{module_specifier}\" is not a file URL." - ))) + )) })?; let module_type = if let Some(extension) = path.extension() { let ext = extension.to_string_lossy().to_lowercase(); diff --git a/core/modules/map.rs b/core/modules/map.rs index e43103211..d711a19f7 100644 --- a/core/modules/map.rs +++ b/core/modules/map.rs @@ -404,7 +404,7 @@ impl ModuleMap { &module_url_found, code, ) - .map_err(|e| ModuleError::Core(CoreError::Other(e)))?; + .map_err(|e| ModuleError::Core(CoreError::JsNative(e)))?; match module_evaluation_kind { // Simple case, we just got a single value so we create a regular diff --git a/core/modules/mod.rs b/core/modules/mod.rs index 0c7b6f468..5857d8a8a 100644 --- a/core/modules/mod.rs +++ b/core/modules/mod.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::{exception_to_err_result, JsErrorClass}; use crate::error::CoreError; +use crate::error::exception_to_err_result; use crate::fast_string::FastString; use crate::module_specifier::ModuleSpecifier; use crate::FastStaticString; @@ -21,7 +21,6 @@ mod recursive_load; mod tests; pub(crate) use loaders::ExtModuleLoader; -pub use loaders::ExtModuleLoaderCb; pub use loaders::FsModuleLoader; pub(crate) use loaders::LazyEsmModuleLoader; pub use loaders::ModuleLoadResponse; @@ -211,13 +210,13 @@ pub type CustomModuleEvaluationCb = Box< Cow<'_, str>, &FastString, ModuleSourceCode, - ) -> Result, + ) -> Result, >; /// A callback to get the code cache for a script. /// (specifier, code) -> ... pub type EvalContextGetCodeCacheCb = - Box Result>; + Box Result>; /// Callback when the code cache is ready. /// (specifier, hash, data) -> () diff --git a/core/modules/tests.rs b/core/modules/tests.rs index 407d1e4e4..5922cacf4 100644 --- a/core/modules/tests.rs +++ b/core/modules/tests.rs @@ -793,12 +793,9 @@ fn test_custom_module_type_callback_synthetic() { module_type: Cow<'_, str>, _module_name: &FastString, module_code: ModuleSourceCode, - ) -> Result { + ) -> Result { if module_type != "bytes" { - return Err( - JsNativeError::generic(format!("Can't load '{}' module", module_type)) - .into(), - ); + return Err(JsNativeError::generic(format!("Can't load '{}' module", module_type))); } let buf = match module_code { @@ -877,12 +874,9 @@ fn test_custom_module_type_callback_computed() { module_type: Cow<'_, str>, module_name: &FastString, module_code: ModuleSourceCode, - ) -> Result { + ) -> Result { if module_type != "foobar" { - return Err( - JsNativeError::generic(format!("Can't load '{}' module", module_type)) - .into(), - ); + return Err(JsNativeError::generic(format!("Can't load '{}' module", module_type))); } let buf = match module_code { diff --git a/core/ops_builtin.rs b/core/ops_builtin.rs index 229de16da..99537230b 100644 --- a/core/ops_builtin.rs +++ b/core/ops_builtin.rs @@ -366,7 +366,7 @@ async fn op_write_type_error( ) -> Result<(), OpError> { let resource = state.borrow().resource_table.get_any(rid)?; resource - .write_error(super::error::JsNativeError::type_error(error).into()) + .write_error(&super::error::JsNativeError::type_error(error)) .await?; Ok(()) } diff --git a/core/resources.rs b/core/resources.rs deleted file mode 100644 index ea1f8e173..000000000 --- a/core/resources.rs +++ /dev/null @@ -1,612 +0,0 @@ -// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. - -// Think of Resources as File Descriptors. They are integers that are allocated -// by the privileged side of Deno which refer to various rust objects that need -// to be persisted between various ops. For example, network sockets are -// resources. Resources may or may not correspond to a real operating system -// file descriptor (hence the different name). - -use crate::error::bad_resource_id; -use crate::error::custom_error; -use crate::error::not_supported; -use crate::io::BufMutView; -use crate::io::BufView; -use crate::io::WriteOutcome; -use futures::Future; -use std::any::type_name; -use std::any::Any; -use std::any::TypeId; -use std::borrow::Cow; -use std::collections::BTreeMap; -use std::io::IsTerminal; -use std::iter::Iterator; -use std::pin::Pin; -use std::rc::Rc; - -/// Returned by resource read/write/shutdown methods -pub type AsyncResult = Pin>>>; - -/// Represents an underlying handle for a platform. On unix, everything is an `fd`. On Windows, everything -/// is a Windows handle except for sockets (which are `SOCKET`s). -#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] -#[allow(unused)] -pub enum ResourceHandle { - /// A file handle/descriptor. - Fd(ResourceHandleFd), - /// A socket handle/file descriptor. - Socket(ResourceHandleSocket), -} - -#[cfg(unix)] -pub type ResourceHandleFd = std::os::fd::RawFd; -#[cfg(unix)] -pub type ResourceHandleSocket = std::os::fd::RawFd; -#[cfg(windows)] -pub type ResourceHandleFd = std::os::windows::io::RawHandle; -#[cfg(windows)] -pub type ResourceHandleSocket = std::os::windows::io::RawSocket; - -impl ResourceHandle { - /// Converts a file-like thing to a [`ResourceHandle`]. - #[cfg(windows)] - pub fn from_fd_like(io: &impl std::os::windows::io::AsRawHandle) -> Self { - Self::Fd(io.as_raw_handle()) - } - - /// Converts a file-like thing to a [`ResourceHandle`]. - #[cfg(unix)] - pub fn from_fd_like(io: &impl std::os::unix::io::AsRawFd) -> Self { - Self::Fd(io.as_raw_fd()) - } - - /// Converts a socket-like thing to a [`ResourceHandle`]. - #[cfg(windows)] - pub fn from_socket_like(io: &impl std::os::windows::io::AsRawSocket) -> Self { - Self::Socket(io.as_raw_socket()) - } - - /// Converts a socket-like thing to a [`ResourceHandle`]. - #[cfg(unix)] - pub fn from_socket_like(io: &impl std::os::unix::io::AsRawFd) -> Self { - Self::Socket(io.as_raw_fd()) - } - - /// Runs a basic validity check on the handle, but cannot fully determine if the handle is valid for use. - pub fn is_valid(&self) -> bool { - #[cfg(windows)] - { - match self { - // NULL or INVALID_HANDLE_VALUE - Self::Fd(handle) => { - !handle.is_null() - && *handle != -1_isize as std::os::windows::io::RawHandle - } - // INVALID_SOCKET - Self::Socket(socket) => { - *socket != -1_i64 as std::os::windows::io::RawSocket - } - } - } - #[cfg(unix)] - { - match self { - Self::Fd(fd) => *fd >= 0, - Self::Socket(fd) => *fd >= 0, - } - } - } - - /// Returns this as a file-descriptor-like handle. - pub fn as_fd_like(&self) -> Option { - match self { - Self::Fd(fd) => Some(*fd), - _ => None, - } - } - - /// Returns this as a socket-like handle. - pub fn as_socket_like(&self) -> Option { - match self { - Self::Socket(socket) => Some(*socket), - _ => None, - } - } - - /// Determines if this handle is a terminal. Analagous to [`std::io::IsTerminal`]. - pub fn is_terminal(&self) -> bool { - match self { - Self::Fd(fd) if self.is_valid() => { - #[cfg(windows)] - { - // SAFETY: The resource remains open for the for the duration of borrow_raw - unsafe { - std::os::windows::io::BorrowedHandle::borrow_raw(*fd).is_terminal() - } - } - #[cfg(unix)] - { - // SAFETY: The resource remains open for the for the duration of borrow_raw - unsafe { std::os::fd::BorrowedFd::borrow_raw(*fd).is_terminal() } - } - } - _ => false, - } - } -} - -/// Resources are Rust objects that are attached to a [deno_core::JsRuntime]. -/// They are identified in JS by a numeric ID (the resource ID, or rid). -/// Resources can be created in ops. Resources can also be retrieved in ops by -/// their rid. Resources are not thread-safe - they can only be accessed from -/// the thread that the JsRuntime lives on. -/// -/// Resources are reference counted in Rust. This means that they can be -/// cloned and passed around. When the last reference is dropped, the resource -/// is automatically closed. As long as the resource exists in the resource -/// table, the reference count is at least 1. -/// -/// ### Readable -/// -/// Readable resources are resources that can have data read from. Examples of -/// this are files, sockets, or HTTP streams. -/// -/// Readables can be read from from either JS or Rust. In JS one can use -/// `Deno.core.read()` to read from a single chunk of data from a readable. In -/// Rust one can directly call `read()` or `read_byob()`. The Rust side code is -/// used to implement ops like `op_slice`. -/// -/// A distinction can be made between readables that produce chunks of data -/// themselves (they allocate the chunks), and readables that fill up -/// bring-your-own-buffers (BYOBs). The former is often the case for framed -/// protocols like HTTP, while the latter is often the case for kernel backed -/// resources like files and sockets. -/// -/// All readables must implement `read()`. If resources can support an optimized -/// path for BYOBs, they should also implement `read_byob()`. For kernel backed -/// resources it often makes sense to implement `read_byob()` first, and then -/// implement `read()` as an operation that allocates a new chunk with -/// `len == limit`, then calls `read_byob()`, and then returns a chunk sliced to -/// the number of bytes read. Kernel backed resources can use the -/// [deno_core::impl_readable_byob] macro to implement optimized `read_byob()` -/// and `read()` implementations from a single `Self::read()` method. -/// -/// ### Writable -/// -/// Writable resources are resources that can have data written to. Examples of -/// this are files, sockets, or HTTP streams. -/// -/// Writables can be written to from either JS or Rust. In JS one can use -/// `Deno.core.write()` to write to a single chunk of data to a writable. In -/// Rust one can directly call `write()`. The latter is used to implement ops -/// like `op_slice`. -pub trait Resource: Any + 'static { - /// Returns a string representation of the resource which is made available - /// to JavaScript code through `op_resources`. The default implementation - /// returns the Rust type name, but specific resource types may override this - /// trait method. - fn name(&self) -> Cow { - type_name::().into() - } - - /// Read a single chunk of data from the resource. This operation returns a - /// `BufView` that represents the data that was read. If a zero length buffer - /// is returned, it indicates that the resource has reached EOF. - /// - /// If this method is not implemented, the default implementation will error - /// with a "not supported" error. - /// - /// If a readable can provide an optimized path for BYOBs, it should also - /// implement `read_byob()`. - fn read(self: Rc, limit: usize) -> AsyncResult { - _ = limit; - Box::pin(futures::future::err(not_supported())) - } - - /// Read a single chunk of data from the resource into the provided `BufMutView`. - /// - /// This operation returns the number of bytes read. If zero bytes are read, - /// it indicates that the resource has reached EOF. - /// - /// If this method is not implemented explicitly, the default implementation - /// will call `read()` and then copy the data into the provided buffer. For - /// readable resources that can provide an optimized path for BYOBs, it is - /// strongly recommended to override this method. - fn read_byob( - self: Rc, - mut buf: BufMutView, - ) -> AsyncResult<(usize, BufMutView)> { - Box::pin(async move { - let read = self.read(buf.len()).await?; - let nread = read.len(); - buf[..nread].copy_from_slice(&read); - Ok((nread, buf)) - }) - } - - /// Write an error state to this resource, if the resource supports it. - fn write_error(self: Rc, _error: Error) -> AsyncResult<()> { - Box::pin(futures::future::err(not_supported())) - } - - /// Write a single chunk of data to the resource. The operation may not be - /// able to write the entire chunk, in which case it should return the number - /// of bytes written. Additionally it should return the `BufView` that was - /// passed in. - /// - /// If this method is not implemented, the default implementation will error - /// with a "not supported" error. - fn write(self: Rc, buf: BufView) -> AsyncResult { - _ = buf; - Box::pin(futures::future::err(not_supported())) - } - - /// Write an entire chunk of data to the resource. Unlike `write()`, this will - /// ensure the entire chunk is written. If the operation is not able to write - /// the entire chunk, an error is to be returned. - /// - /// By default this method will call `write()` repeatedly until the entire - /// chunk is written. Resources that can write the entire chunk in a single - /// operation using an optimized path should override this method. - fn write_all(self: Rc, view: BufView) -> AsyncResult<()> { - Box::pin(async move { - let mut view = view; - let this = self; - while !view.is_empty() { - let resp = this.clone().write(view).await?; - match resp { - WriteOutcome::Partial { - nwritten, - view: new_view, - } => { - view = new_view; - view.advance_cursor(nwritten); - } - WriteOutcome::Full { .. } => break, - } - } - Ok(()) - }) - } - - /// The same as [`read_byob()`][Resource::read_byob], but synchronous. - fn read_byob_sync(self: Rc, data: &mut [u8]) -> Result { - _ = data; - Err(not_supported()) - } - - /// The same as [`write()`][Resource::write], but synchronous. - fn write_sync(self: Rc, data: &[u8]) -> Result { - _ = data; - Err(not_supported()) - } - - /// The shutdown method can be used to asynchronously close the resource. It - /// is not automatically called when the resource is dropped or closed. - /// - /// If this method is not implemented, the default implementation will error - /// with a "not supported" error. - fn shutdown(self: Rc) -> AsyncResult<()> { - Box::pin(futures::future::err(not_supported())) - } - - /// Resources may implement the `close()` trait method if they need to do - /// resource specific clean-ups, such as cancelling pending futures, after a - /// resource has been removed from the resource table. - fn close(self: Rc) {} - - /// Resources backed by a file descriptor or socket handle can let ops know - /// to allow for low-level optimizations. - fn backing_handle(self: Rc) -> Option { - #[allow(deprecated)] - self.backing_fd().map(ResourceHandle::Fd) - } - - /// Resources backed by a file descriptor can let ops know to allow for - /// low-level optimizations. - #[deprecated = "Use backing_handle"] - fn backing_fd(self: Rc) -> Option { - None - } - - fn size_hint(&self) -> (u64, Option) { - (0, None) - } -} - -impl dyn Resource { - #[inline(always)] - fn is(&self) -> bool { - self.type_id() == TypeId::of::() - } - - #[inline(always)] - #[allow(clippy::needless_lifetimes)] - pub fn downcast_rc<'a, T: Resource>(self: &'a Rc) -> Option<&'a Rc> { - if self.is::() { - let ptr = self as *const Rc<_> as *const Rc; - // TODO(piscisaureus): safety comment - #[allow(clippy::undocumented_unsafe_blocks)] - Some(unsafe { &*ptr }) - } else { - None - } - } -} - -/// A `ResourceId` is an integer value referencing a resource. It could be -/// considered to be the Deno equivalent of a `file descriptor` in POSIX like -/// operating systems. Elsewhere in the code base it is commonly abbreviated -/// to `rid`. -// TODO: use `u64` instead? -pub type ResourceId = u32; - -/// Map-like data structure storing Deno's resources (equivalent to file -/// descriptors). -/// -/// Provides basic methods for element access. A resource can be of any type. -/// Different types of resources can be stored in the same map, and provided -/// with a name for description. -/// -/// Each resource is identified through a _resource ID (rid)_, which acts as -/// the key in the map. -#[derive(Default)] -pub struct ResourceTable { - index: BTreeMap>, - next_rid: ResourceId, -} - -impl ResourceTable { - /// Returns the number of resources currently active in the resource table. - /// Resources taken from the table do not contribute to this count. - pub fn len(&self) -> usize { - self.index.len() - } - - /// Returns whether this table is empty. - pub fn is_empty(&self) -> bool { - self.index.is_empty() - } - - /// Inserts resource into the resource table, which takes ownership of it. - /// - /// The resource type is erased at runtime and must be statically known - /// when retrieving it through `get()`. - /// - /// Returns a unique resource ID, which acts as a key for this resource. - pub fn add(&mut self, resource: T) -> ResourceId { - self.add_rc(Rc::new(resource)) - } - - /// Inserts a `Rc`-wrapped resource into the resource table. - /// - /// The resource type is erased at runtime and must be statically known - /// when retrieving it through `get()`. - /// - /// Returns a unique resource ID, which acts as a key for this resource. - pub fn add_rc(&mut self, resource: Rc) -> ResourceId { - let resource = resource as Rc; - self.add_rc_dyn(resource) - } - - pub fn add_rc_dyn(&mut self, resource: Rc) -> ResourceId { - let rid = self.next_rid; - let removed_resource = self.index.insert(rid, resource); - assert!(removed_resource.is_none()); - self.next_rid += 1; - rid - } - - /// Returns true if any resource with the given `rid` exists. - pub fn has(&self, rid: ResourceId) -> bool { - self.index.contains_key(&rid) - } - - /// Returns a reference counted pointer to the resource of type `T` with the - /// given `rid`. If `rid` is not present or has a type different than `T`, - /// this function returns `None`. - pub fn get(&self, rid: ResourceId) -> Result, Error> { - self - .index - .get(&rid) - .and_then(|rc| rc.downcast_rc::()) - .map(Clone::clone) - .ok_or_else(bad_resource_id) - } - - pub fn get_any(&self, rid: ResourceId) -> Result, Error> { - self - .index - .get(&rid) - .map(Clone::clone) - .ok_or_else(bad_resource_id) - } - - /// Replaces a resource with a new resource. - /// - /// Panics if the resource does not exist. - pub fn replace(&mut self, rid: ResourceId, resource: T) { - let result = self - .index - .insert(rid, Rc::new(resource) as Rc); - assert!(result.is_some()); - } - - /// Removes a resource of type `T` from the resource table and returns it. - /// If a resource with the given `rid` exists but its type does not match `T`, - /// it is not removed from the resource table. Note that the resource's - /// `close()` method is *not* called. - /// - /// Also note that there might be a case where - /// the returned `Rc` is referenced by other variables. That is, we cannot - /// assume that `Rc::strong_count(&returned_rc)` is always equal to 1 on success. - /// In particular, be really careful when you want to extract the inner value of - /// type `T` from `Rc`. - pub fn take(&mut self, rid: ResourceId) -> Result, Error> { - let resource = self.get::(rid)?; - self.index.remove(&rid); - Ok(resource) - } - - /// Removes a resource from the resource table and returns it. Note that the - /// resource's `close()` method is *not* called. - /// - /// Also note that there might be a - /// case where the returned `Rc` is referenced by other variables. That is, - /// we cannot assume that `Rc::strong_count(&returned_rc)` is always equal to 1 - /// on success. In particular, be really careful when you want to extract the - /// inner value of type `T` from `Rc`. - pub fn take_any( - &mut self, - rid: ResourceId, - ) -> Result, Error> { - self.index.remove(&rid).ok_or_else(bad_resource_id) - } - - /// Removes the resource with the given `rid` from the resource table. If the - /// only reference to this resource existed in the resource table, this will - /// cause the resource to be dropped. However, since resources are reference - /// counted, therefore pending ops are not automatically cancelled. A resource - /// may implement the `close()` method to perform clean-ups such as canceling - /// ops. - #[deprecated = "This method may deadlock. Use take() and close() instead."] - pub fn close(&mut self, rid: ResourceId) -> Result<(), Error> { - self - .index - .remove(&rid) - .ok_or_else(bad_resource_id) - .map(|resource| resource.close()) - } - - /// Returns an iterator that yields a `(id, name)` pair for every resource - /// that's currently in the resource table. This can be used for debugging - /// purposes or to implement the `op_resources` op. Note that the order in - /// which items appear is not specified. - /// - /// # Example - /// - /// ``` - /// # use deno_core::ResourceTable; - /// # let resource_table = ResourceTable::default(); - /// let resource_names = resource_table.names().collect::>(); - /// ``` - pub fn names(&self) -> impl Iterator)> { - self - .index - .iter() - .map(|(&id, resource)| (id, resource.name())) - } - - /// Retrieves the [`ResourceHandleFd`] for a given resource, for potential optimization - /// purposes within ops. - pub fn get_fd(&self, rid: ResourceId) -> Result { - let Some(handle) = self.get_any(rid)?.backing_handle() else { - return Err(bad_resource_id()); - }; - let Some(fd) = handle.as_fd_like() else { - return Err(bad_resource_id()); - }; - if !handle.is_valid() { - return Err(custom_error("ReferenceError", "null or invalid handle")); - } - Ok(fd) - } - - /// Retrieves the [`ResourceHandleSocket`] for a given resource, for potential optimization - /// purposes within ops. - pub fn get_socket( - &self, - rid: ResourceId, - ) -> Result { - let Some(handle) = self.get_any(rid)?.backing_handle() else { - return Err(bad_resource_id()); - }; - let Some(socket) = handle.as_socket_like() else { - return Err(bad_resource_id()); - }; - if !handle.is_valid() { - return Err(custom_error("ReferenceError", "null or invalid handle")); - } - Ok(socket) - } - - /// Retrieves the [`ResourceHandle`] for a given resource, for potential optimization - /// purposes within ops. - pub fn get_handle( - &self, - rid: ResourceId, - ) -> ::std::result::Result { - let Some(handle) = self.get_any(rid)?.backing_handle() else { - return Err(bad_resource_id()); - }; - if !handle.is_valid() { - return Err(custom_error("ReferenceError", "null or invalid handle")); - } - Ok(handle) - } -} - -#[macro_export] -macro_rules! impl_readable_byob { - () => { - fn read( - self: ::std::rc::Rc, - limit: ::core::primitive::usize, - ) -> AsyncResult<$crate::BufView> { - ::std::boxed::Box::pin(async move { - let mut vec = ::std::vec![0; limit]; - let nread = self.read(&mut vec).await?; - if nread != vec.len() { - vec.truncate(nread); - } - let view = $crate::BufView::from(vec); - ::std::result::Result::Ok(view) - }) - } - - fn read_byob( - self: ::std::rc::Rc, - mut buf: $crate::BufMutView, - ) -> AsyncResult<(::core::primitive::usize, $crate::BufMutView)> { - ::std::boxed::Box::pin(async move { - let nread = self.read(buf.as_mut()).await?; - ::std::result::Result::Ok((nread, buf)) - }) - } - }; -} - -#[macro_export] -macro_rules! impl_writable { - (__write) => { - fn write( - self: ::std::rc::Rc, - view: $crate::BufView, - ) -> $crate::AsyncResult<$crate::WriteOutcome> { - ::std::boxed::Box::pin(async move { - let nwritten = self.write(&view).await?; - ::std::result::Result::Ok($crate::WriteOutcome::Partial { - nwritten, - view, - }) - }) - } - }; - (__write_all) => { - fn write_all( - self: ::std::rc::Rc, - view: $crate::BufView, - ) -> $crate::AsyncResult<()> { - ::std::boxed::Box::pin(async move { - self.write_all(&view).await?; - ::std::result::Result::Ok(()) - }) - } - }; - () => { - $crate::impl_writable!(__write); - }; - (with_all) => { - $crate::impl_writable!(__write); - $crate::impl_writable!(__write_all); - }; -} diff --git a/core/runtime/jsruntime.rs b/core/runtime/jsruntime.rs index f7e2fad5b..c88716cb6 100644 --- a/core/runtime/jsruntime.rs +++ b/core/runtime/jsruntime.rs @@ -13,7 +13,7 @@ use super::SnapshotStoreDataStore; use super::SnapshottedData; use crate::ascii_str; use crate::ascii_str_include; -use crate::error::exception_to_err_result; +use crate::error::{exception_to_err_result, JsNativeError}; use crate::error::CoreError; use crate::error::JsError; use crate::extension_set; @@ -89,7 +89,7 @@ pub type ExtensionTranspiler = dyn Fn( ModuleName, ModuleCodeString, - ) -> Result<(ModuleCodeString, Option), anyhow::Error>; + ) -> Result<(ModuleCodeString, Option), JsNativeError>; /// Objects that need to live as long as the isolate #[derive(Default)] diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index a7a34c1ef..798d5eb5a 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -264,12 +264,7 @@ pub struct OpError(Box); impl std::fmt::Display for OpError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "{}: {}", - self.0.get_class(), - self.0.get_message() - ) + write!(f, "{}: {}", self.0.get_class(), self.0.get_message()) } } @@ -278,6 +273,11 @@ impl From for OpError { Self(Box::new(err)) } } +impl From> for OpError { + fn from(err: Box) -> Self { + Self(err) + } +} impl Serialize for OpError { fn serialize(&self, serializer: S) -> Result @@ -287,7 +287,10 @@ impl Serialize for OpError { let mut serde_state = serializer.serialize_struct("OpError", 3)?; serde_state.serialize_field("$err_class_name", self.0.get_class())?; serde_state.serialize_field("message", &self.0.get_message())?; - serde_state.serialize_field("additional_properties", &self.0.get_additional_properties())?; + serde_state.serialize_field( + "additional_properties", + &self.0.get_additional_properties(), + )?; serde_state.end() } } @@ -304,10 +307,10 @@ impl std::fmt::Display for OpErrorWrapper { impl JsErrorClass for OpErrorWrapper { fn get_class(&self) -> &'static str { - self.0.error.get_class() + self.0 .0.get_class() } fn get_message(&self) -> std::borrow::Cow<'static, str> { - self.0.error.get_message() + self.0 .0.get_message() } } diff --git a/testing/checkin/runner/mod.rs b/testing/checkin/runner/mod.rs index d91cb679b..a60b042fc 100644 --- a/testing/checkin/runner/mod.rs +++ b/testing/checkin/runner/mod.rs @@ -3,7 +3,6 @@ use self::ops_worker::worker_create; use self::ops_worker::WorkerCloseWatcher; use self::ops_worker::WorkerHostSide; use self::ts_module_loader::maybe_transpile_source; -use anyhow::anyhow; use anyhow::Context; use deno_core::v8; use deno_core::CrossIsolateStore; @@ -25,6 +24,7 @@ use std::sync::mpsc::RecvTimeoutError; use std::sync::Arc; use std::sync::Mutex; use std::time::Duration; +use deno_core::error::JsNativeError; mod extensions; mod ops; @@ -166,22 +166,22 @@ fn custom_module_evaluation_cb( module_type: Cow<'_, str>, module_name: &FastString, code: ModuleSourceCode, -) -> Result { +) -> Result { match &*module_type { "bytes" => bytes_module(scope, code), "text" => text_module(scope, module_name, code), - _ => Err(anyhow!( - "Can't import {:?} because of unknown module type {}", + _ => Err(JsNativeError::generic( + format!("Can't import {:?} because of unknown module type {}", module_name, module_type - )), + ))), } } fn bytes_module( scope: &mut v8::HandleScope, code: ModuleSourceCode, -) -> Result { +) -> Result { // FsModuleLoader always returns bytes. let ModuleSourceCode::Bytes(buf) = code else { unreachable!() @@ -202,7 +202,7 @@ fn text_module( scope: &mut v8::HandleScope, module_name: &FastString, code: ModuleSourceCode, -) -> Result { +) -> Result { // FsModuleLoader always returns bytes. let ModuleSourceCode::Bytes(buf) = code else { unreachable!() @@ -210,7 +210,7 @@ fn text_module( let code = std::str::from_utf8(buf.as_bytes()).with_context(|| { format!("Can't convert {:?} source code to string", module_name) - })?; + }).map_err(JsNativeError::from_err)?; let str_ = v8::String::new(scope, code).unwrap(); let value: v8::Local = str_.into(); Ok(CustomModuleEvaluationKind::Synthetic(v8::Global::new( diff --git a/testing/checkin/runner/ops_io.rs b/testing/checkin/runner/ops_io.rs index a4a3770b6..4af65372e 100644 --- a/testing/checkin/runner/ops_io.rs +++ b/testing/checkin/runner/ops_io.rs @@ -1,5 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use deno_core::error::OpError; +use deno_core::error::{JsNativeError, OpError}; use deno_core::op2; use deno_core::AsyncRefCell; use deno_core::BufView; @@ -31,7 +31,7 @@ impl Resource for PipeResource { async { let mut lock = RcRef::map(self, |this| &this.rx).borrow_mut().await; // Note that we're holding a slice across an await point, so this code is very much not safe - let res = lock.read(&mut buf).await?; + let res = lock.read(&mut buf).await.map_err(JsNativeError::from_err)?; Ok((res, buf)) } .boxed_local() @@ -43,7 +43,7 @@ impl Resource for PipeResource { ) -> deno_core::AsyncResult { async { let mut lock = RcRef::map(self, |this| &this.tx).borrow_mut().await; - let nwritten = lock.write(&buf).await?; + let nwritten = lock.write(&buf).await.map_err(JsNativeError::from_err)?; Ok(WriteOutcome::Partial { nwritten, view: buf, diff --git a/testing/checkin/runner/ts_module_loader.rs b/testing/checkin/runner/ts_module_loader.rs index 24159828b..ecec3d223 100644 --- a/testing/checkin/runner/ts_module_loader.rs +++ b/testing/checkin/runner/ts_module_loader.rs @@ -10,7 +10,8 @@ use anyhow::Context; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; -use deno_core::error::ModuleLoaderError; +use deno_core::error::{JsNativeError}; +use deno_core::error::{ModuleLoaderError}; use deno_core::resolve_import; use deno_core::url::Url; use deno_core::ModuleCodeBytes; @@ -161,7 +162,7 @@ impl ModuleLoader for TypescriptModuleLoader { pub fn maybe_transpile_source( specifier: ModuleName, source: ModuleCodeString, -) -> Result<(ModuleCodeString, Option), anyhow::Error> { +) -> Result<(ModuleCodeString, Option), JsNativeError> { // Always transpile `checkin:` built-in modules, since they might be TypeScript. let media_type = if specifier.starts_with("checkin:") { MediaType::TypeScript @@ -186,7 +187,7 @@ pub fn maybe_transpile_source( capture_tokens: false, scope_analysis: false, maybe_syntax: None, - })?; + }).map_err(|err| JsNativeError::from_err(anyhow::Error::from(err)))?; let transpiled_source = parsed .transpile( &deno_ast::TranspileOptions { @@ -199,7 +200,7 @@ pub fn maybe_transpile_source( inline_sources: false, ..Default::default() }, - )? + ).map_err(|err| JsNativeError::from_err(anyhow::Error::from(err)))? .into_source(); Ok(( From 873991ba88b041ac756f35c485ccc66b84c374eb Mon Sep 17 00:00:00 2001 From: crowlkats Date: Wed, 28 Aug 2024 11:48:00 +0200 Subject: [PATCH 20/52] fmt --- core/error.rs | 15 +++++++++++---- core/io/mod.rs | 2 +- core/io/resource.rs | 10 ++-------- core/modules/mod.rs | 10 +++++++--- core/modules/tests.rs | 10 ++++++++-- core/runtime/jsruntime.rs | 2 +- testing/checkin/runner/mod.rs | 19 ++++++++++--------- testing/checkin/runner/ts_module_loader.rs | 10 ++++++---- 8 files changed, 46 insertions(+), 32 deletions(-) diff --git a/core/error.rs b/core/error.rs index ec4eb91b0..8a299633b 100644 --- a/core/error.rs +++ b/core/error.rs @@ -144,10 +144,15 @@ pub trait JsErrorClass: Display + Debug + Send + Sync + 'static { fn get_message(&self) -> Cow<'static, str> { self.to_string().into() } - fn get_additional_properties(&self) -> Option, Cow<'static, str>)>> { + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { None } - fn to_native(self) -> JsNativeError where Self: Sized { + fn to_native(self) -> JsNativeError + where + Self: Sized, + { JsNativeError::from_err(self) } @@ -393,7 +398,6 @@ impl JsNativeError { } } - pub fn generic(message: impl Into>) -> JsNativeError { Self::new("Error", message) } @@ -491,7 +495,10 @@ pub fn to_v8_error<'a>( let message = v8::String::new(tc_scope, &error.get_message()).unwrap(); let mut args = vec![class.into(), message.into()]; - if let Some(code) = (error as &dyn std::any::Any).downcast_ref::().and_then(crate::error_codes::get_error_code) { + if let Some(code) = (error as &dyn std::any::Any) + .downcast_ref::() + .and_then(crate::error_codes::get_error_code) + { args.push(v8::String::new(tc_scope, code).unwrap().into()); } let maybe_exception = cb.call(tc_scope, this, &args); diff --git a/core/io/mod.rs b/core/io/mod.rs index 688cf3e52..87999ade0 100644 --- a/core/io/mod.rs +++ b/core/io/mod.rs @@ -15,6 +15,7 @@ mod resource; mod resource_handle; mod resource_table; +use crate::error::JsNativeError; pub use buffer_strategy::AdaptiveBufferStrategy; pub use buffers::BufMutView; pub use buffers::BufView; @@ -25,7 +26,6 @@ pub use resource_handle::ResourceHandleSocket; pub use resource_table::ResourceError; pub use resource_table::ResourceId; pub use resource_table::ResourceTable; -use crate::error::JsNativeError; /// Returned by resource shutdown methods pub type AsyncResult = diff --git a/core/io/resource.rs b/core/io/resource.rs index d3099dd33..b65fa3ee7 100644 --- a/core/io/resource.rs +++ b/core/io/resource.rs @@ -110,10 +110,7 @@ pub trait Resource: Any + 'static { } /// Write an error state to this resource, if the resource supports it. - fn write_error( - self: Rc, - _error: &dyn JsErrorClass, - ) -> AsyncResult<()> { + fn write_error(self: Rc, _error: &dyn JsErrorClass) -> AsyncResult<()> { Box::pin(futures::future::err(JsNativeError::not_supported())) } @@ -167,10 +164,7 @@ pub trait Resource: Any + 'static { } /// The same as [`write()`][Resource::write], but synchronous. - fn write_sync( - self: Rc, - data: &[u8], - ) -> Result { + fn write_sync(self: Rc, data: &[u8]) -> Result { _ = data; Err(JsNativeError::not_supported()) } diff --git a/core/modules/mod.rs b/core/modules/mod.rs index 5857d8a8a..59ea7e88b 100644 --- a/core/modules/mod.rs +++ b/core/modules/mod.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::CoreError; use crate::error::exception_to_err_result; +use crate::error::CoreError; use crate::fast_string::FastString; use crate::module_specifier::ModuleSpecifier; use crate::FastStaticString; @@ -215,8 +215,12 @@ pub type CustomModuleEvaluationCb = Box< /// A callback to get the code cache for a script. /// (specifier, code) -> ... -pub type EvalContextGetCodeCacheCb = - Box Result>; +pub type EvalContextGetCodeCacheCb = Box< + dyn Fn( + &Url, + &v8::String, + ) -> Result, +>; /// Callback when the code cache is ready. /// (specifier, hash, data) -> () diff --git a/core/modules/tests.rs b/core/modules/tests.rs index 5922cacf4..26d533013 100644 --- a/core/modules/tests.rs +++ b/core/modules/tests.rs @@ -795,7 +795,10 @@ fn test_custom_module_type_callback_synthetic() { module_code: ModuleSourceCode, ) -> Result { if module_type != "bytes" { - return Err(JsNativeError::generic(format!("Can't load '{}' module", module_type))); + return Err(JsNativeError::generic(format!( + "Can't load '{}' module", + module_type + ))); } let buf = match module_code { @@ -876,7 +879,10 @@ fn test_custom_module_type_callback_computed() { module_code: ModuleSourceCode, ) -> Result { if module_type != "foobar" { - return Err(JsNativeError::generic(format!("Can't load '{}' module", module_type))); + return Err(JsNativeError::generic(format!( + "Can't load '{}' module", + module_type + ))); } let buf = match module_code { diff --git a/core/runtime/jsruntime.rs b/core/runtime/jsruntime.rs index c88716cb6..a4262c760 100644 --- a/core/runtime/jsruntime.rs +++ b/core/runtime/jsruntime.rs @@ -13,9 +13,9 @@ use super::SnapshotStoreDataStore; use super::SnapshottedData; use crate::ascii_str; use crate::ascii_str_include; -use crate::error::{exception_to_err_result, JsNativeError}; use crate::error::CoreError; use crate::error::JsError; +use crate::error::{exception_to_err_result, JsNativeError}; use crate::extension_set; use crate::extension_set::LoadedSources; use crate::extensions::GlobalObjectMiddlewareFn; diff --git a/testing/checkin/runner/mod.rs b/testing/checkin/runner/mod.rs index a60b042fc..76f63efcb 100644 --- a/testing/checkin/runner/mod.rs +++ b/testing/checkin/runner/mod.rs @@ -4,6 +4,7 @@ use self::ops_worker::WorkerCloseWatcher; use self::ops_worker::WorkerHostSide; use self::ts_module_loader::maybe_transpile_source; use anyhow::Context; +use deno_core::error::JsNativeError; use deno_core::v8; use deno_core::CrossIsolateStore; use deno_core::CustomModuleEvaluationKind; @@ -24,7 +25,6 @@ use std::sync::mpsc::RecvTimeoutError; use std::sync::Arc; use std::sync::Mutex; use std::time::Duration; -use deno_core::error::JsNativeError; mod extensions; mod ops; @@ -170,11 +170,10 @@ fn custom_module_evaluation_cb( match &*module_type { "bytes" => bytes_module(scope, code), "text" => text_module(scope, module_name, code), - _ => Err(JsNativeError::generic( - format!("Can't import {:?} because of unknown module type {}", - module_name, - module_type - ))), + _ => Err(JsNativeError::generic(format!( + "Can't import {:?} because of unknown module type {}", + module_name, module_type + ))), } } @@ -208,9 +207,11 @@ fn text_module( unreachable!() }; - let code = std::str::from_utf8(buf.as_bytes()).with_context(|| { - format!("Can't convert {:?} source code to string", module_name) - }).map_err(JsNativeError::from_err)?; + let code = std::str::from_utf8(buf.as_bytes()) + .with_context(|| { + format!("Can't convert {:?} source code to string", module_name) + }) + .map_err(JsNativeError::from_err)?; let str_ = v8::String::new(scope, code).unwrap(); let value: v8::Local = str_.into(); Ok(CustomModuleEvaluationKind::Synthetic(v8::Global::new( diff --git a/testing/checkin/runner/ts_module_loader.rs b/testing/checkin/runner/ts_module_loader.rs index ecec3d223..f37330126 100644 --- a/testing/checkin/runner/ts_module_loader.rs +++ b/testing/checkin/runner/ts_module_loader.rs @@ -10,8 +10,8 @@ use anyhow::Context; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; -use deno_core::error::{JsNativeError}; -use deno_core::error::{ModuleLoaderError}; +use deno_core::error::JsNativeError; +use deno_core::error::ModuleLoaderError; use deno_core::resolve_import; use deno_core::url::Url; use deno_core::ModuleCodeBytes; @@ -187,7 +187,8 @@ pub fn maybe_transpile_source( capture_tokens: false, scope_analysis: false, maybe_syntax: None, - }).map_err(|err| JsNativeError::from_err(anyhow::Error::from(err)))?; + }) + .map_err(|err| JsNativeError::from_err(anyhow::Error::from(err)))?; let transpiled_source = parsed .transpile( &deno_ast::TranspileOptions { @@ -200,7 +201,8 @@ pub fn maybe_transpile_source( inline_sources: false, ..Default::default() }, - ).map_err(|err| JsNativeError::from_err(anyhow::Error::from(err)))? + ) + .map_err(|err| JsNativeError::from_err(anyhow::Error::from(err)))? .into_source(); Ok(( From 0d4e7a1e158efa16bc026c88d019301ed657b4bf Mon Sep 17 00:00:00 2001 From: crowlkats Date: Wed, 28 Aug 2024 11:50:51 +0200 Subject: [PATCH 21/52] lint --- core/error.rs | 2 +- core/io/resource.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/error.rs b/core/error.rs index 8a299633b..0e55e3a04 100644 --- a/core/error.rs +++ b/core/error.rs @@ -290,7 +290,7 @@ impl JsErrorClass for std::io::Error { fn get_additional_properties( &self, ) -> Option, Cow<'static, str>)>> { - crate::error_codes::get_error_code(&self) + crate::error_codes::get_error_code(self) .map(|code| vec![("code".into(), code.into())]) } } diff --git a/core/io/resource.rs b/core/io/resource.rs index b65fa3ee7..e5d99d420 100644 --- a/core/io/resource.rs +++ b/core/io/resource.rs @@ -85,7 +85,7 @@ pub trait Resource: Any + 'static { /// implement `read_byob()`. fn read(self: Rc, limit: usize) -> AsyncResult { _ = limit; - Box::pin(futures::future::err(JsNativeError::not_supported().into())) + Box::pin(futures::future::err(JsNativeError::not_supported())) } /// Read a single chunk of data from the resource into the provided `BufMutView`. From 0f192a1afb2b2fdd05445f519ec0696892550e3d Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 14 Oct 2024 05:22:35 +0200 Subject: [PATCH 22/52] fix --- core/ops_builtin.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/core/ops_builtin.rs b/core/ops_builtin.rs index a6adb014e..5d2afed08 100644 --- a/core/ops_builtin.rs +++ b/core/ops_builtin.rs @@ -432,11 +432,11 @@ async fn do_load_job<'s>( module_map_rc: Rc, specifier: &str, code: Option, -) -> Result { +) -> Result { if let Some(code) = code { module_map_rc .new_es_module(scope, false, specifier.to_owned(), code, false, None) - .map_err(|e| e.into_any_error(scope, false, false))?; + .map_err(|e| e.into_error(scope, false, false))?; } let mut load = ModuleMap::load_side(module_map_rc.clone(), specifier).await?; @@ -445,7 +445,7 @@ async fn do_load_job<'s>( let (request, info) = load_result?; load .register_and_recurse(scope, &request, info) - .map_err(|e| e.into_any_error(scope, false, false))?; + .map_err(|e| e.into_error(scope, false, false))?; } let root_id = load.root_module_id.expect("Root module should be loaded"); @@ -514,7 +514,7 @@ fn op_import_sync<'s>( scope: &mut v8::HandleScope<'s>, #[string] specifier: &str, #[string] code: Option, -) -> Result, Error> { +) -> Result, OpError> { let module_map_rc = JsRealm::module_map_from(scope); // no js execution within block_on @@ -542,7 +542,8 @@ fn op_import_sync<'s>( { let Some(module) = wrap_module(scope, module) else { let exception = scope.exception().unwrap(); - return exception_to_err_result(scope, exception, false, false); + return exception_to_err_result(scope, exception, false, false) + .map_err(Into::into); }; Ok(v8::Local::new(scope, module.get_module_namespace())) } else { From 1964f399676de4291651a9649c5a2b229deb1dca Mon Sep 17 00:00:00 2001 From: crowlkats Date: Tue, 15 Oct 2024 00:52:47 +0200 Subject: [PATCH 23/52] fix --- core/error.rs | 2 +- core/examples/snapshot/src/main.rs | 3 ++- core/ops_builtin.rs | 3 +++ testing/checkin/runner/ops_io.rs | 2 +- 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/core/error.rs b/core/error.rs index 1ff45fd18..3d238c0bb 100644 --- a/core/error.rs +++ b/core/error.rs @@ -25,7 +25,7 @@ pub type AnyError = anyhow::Error; #[derive(Debug, thiserror::Error)] pub enum CoreError { - #[error("Top-level await is not allowed in extensions")] + #[error("Top-level await is not allowed in synchronous evaluation")] TLA, #[error(transparent)] Js(#[from] JsError), diff --git a/core/examples/snapshot/src/main.rs b/core/examples/snapshot/src/main.rs index 83f865d0c..f44fc53b8 100644 --- a/core/examples/snapshot/src/main.rs +++ b/core/examples/snapshot/src/main.rs @@ -39,7 +39,8 @@ async fn run_js(file_path: &str) -> Result<(), AnyError> { js_runtime .run_event_loop(PollEventLoopOptions::default()) .await?; - result.await + result.await?; + Ok(()) } // Load the snapshot generated by build.rs: diff --git a/core/ops_builtin.rs b/core/ops_builtin.rs index 5d2afed08..32c451814 100644 --- a/core/ops_builtin.rs +++ b/core/ops_builtin.rs @@ -490,6 +490,8 @@ fn wrap_module<'s>( let global_module = v8::Global::new(scope, module); scope.set_slot(global_module); + + #[allow(clippy::unnecessary_wraps)] fn resolve_callback<'s>( context: v8::Local<'s, v8::Context>, specifier: v8::Local<'s, v8::String>, @@ -502,6 +504,7 @@ fn wrap_module<'s>( let module = scope.remove_slot::>().unwrap(); Some(v8::Local::new(&mut scope, module)) } + wrapper_module.instantiate_module(scope, resolve_callback)?; wrapper_module.evaluate(scope)?; diff --git a/testing/checkin/runner/ops_io.rs b/testing/checkin/runner/ops_io.rs index aef71dfe2..0ac8ebc7c 100644 --- a/testing/checkin/runner/ops_io.rs +++ b/testing/checkin/runner/ops_io.rs @@ -108,7 +108,7 @@ pub async fn op_file_open( #[op2] #[string] -pub fn op_path_to_url(#[string] path: &str) -> Result { +pub fn op_path_to_url(#[string] path: &str) -> Result { let path = std::path::absolute(path)?; let url = url::Url::from_file_path(path).unwrap(); Ok(url.to_string()) From 4b7d31aa8b8bba2de6f100e042b51619b1df07aa Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 18 Oct 2024 15:47:33 +0200 Subject: [PATCH 24/52] cleanip and fixes --- core/async_cancel.rs | 25 ++++++++++++++++++++++--- core/error.rs | 4 ++-- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/core/async_cancel.rs b/core/async_cancel.rs index c54150a9f..1323372f7 100644 --- a/core/async_cancel.rs +++ b/core/async_cancel.rs @@ -10,6 +10,9 @@ use std::io; use std::pin::Pin; use std::rc::Rc; +use crate::error::JsErrorClass; +use crate::RcLike; +use crate::Resource; use futures::future::FusedFuture; use futures::future::Future; use futures::future::TryFuture; @@ -17,9 +20,6 @@ use futures::task::Context; use futures::task::Poll; use pin_project::pin_project; -use crate::RcLike; -use crate::Resource; - use self::internal as i; #[derive(Debug, Default)] @@ -242,6 +242,25 @@ impl From for io::Error { } } +impl JsErrorClass for Canceled { + fn get_class(&self) -> &'static str { + let io_err: io::Error = self.to_owned().into(); + io_err.get_class() + } + + fn get_message(&self) -> Cow<'static, str> { + let io_err: io::Error = self.to_owned().into(); + io_err.get_message() + } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + let io_err: io::Error = self.to_owned().into(); + io_err.get_additional_properties() + } +} + mod internal { use super::Abortable; use super::CancelHandle; diff --git a/core/error.rs b/core/error.rs index 3d238c0bb..36a6fa18b 100644 --- a/core/error.rs +++ b/core/error.rs @@ -195,7 +195,7 @@ impl JsErrorClass for CoreError { fn get_class(&self) -> &'static str { match self { CoreError::Js(js_error) => { - unreachable!("JsError's should not be reachable: {}", js_error) + unreachable!("JsError should not be reachable: {}", js_error) } CoreError::Io(err) => err.get_class(), CoreError::ExtensionTranspiler(err) => err.get_class(), @@ -222,7 +222,7 @@ impl JsErrorClass for CoreError { fn get_message(&self) -> Cow<'static, str> { match self { CoreError::Js(js_error) => { - unreachable!("JsError's should not be reachable: {}", js_error) + unreachable!("JsError should not be reachable: {}", js_error) } CoreError::Io(err) => err.get_message(), CoreError::ExtensionTranspiler(err) => err.get_message(), From d6e00119d2047ff42c6ab1cfa836ae121474a4f0 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sat, 19 Oct 2024 18:39:43 +0200 Subject: [PATCH 25/52] more cleanup --- core/error.rs | 55 +++++++++++++++++++++++---------------- core/io/resource_table.rs | 2 +- core/module_specifier.rs | 2 +- core/modules/loaders.rs | 12 ++++----- core/modules/mod.rs | 2 +- core/runtime/bindings.rs | 14 ++++++---- 6 files changed, 50 insertions(+), 37 deletions(-) diff --git a/core/error.rs b/core/error.rs index 36a6fa18b..aa65079f9 100644 --- a/core/error.rs +++ b/core/error.rs @@ -23,6 +23,15 @@ use std::fmt::Write as _; // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. pub type AnyError = anyhow::Error; +pub const GENERIC_ERROR: &'static str = "Error"; +pub const RANGE_ERROR: &'static str = "RangeError"; +pub const TYPE_ERROR: &'static str = "TypeError"; +pub const SYNTAX_ERROR: &'static str = "SyntaxError"; +pub const URI_ERROR: &'static str = "URIError"; +pub const REFERENCE_ERROR: &'static str = "ReferenceError"; + +pub const NOT_SUPPORTED_ERROR: &'static str = "NotSupported"; + #[derive(Debug, thiserror::Error)] pub enum CoreError { #[error("Top-level await is not allowed in synchronous evaluation")] @@ -173,17 +182,17 @@ fn js_class_and_message_to_exception<'s>( ) -> v8::Local<'s, v8::Value> { let message = v8::String::new(scope, message).unwrap(); match class { - "TypeError" => v8::Exception::type_error(scope, message), - "RangeError" => v8::Exception::range_error(scope, message), - "ReferenceError" => v8::Exception::reference_error(scope, message), - "SyntaxError" => v8::Exception::syntax_error(scope, message), + TYPE_ERROR => v8::Exception::type_error(scope, message), + RANGE_ERROR => v8::Exception::range_error(scope, message), + REFERENCE_ERROR => v8::Exception::reference_error(scope, message), + SYNTAX_ERROR => v8::Exception::syntax_error(scope, message), _ => v8::Exception::error(scope, message), } } impl JsErrorClass for anyhow::Error { fn get_class(&self) -> &'static str { - "Error" + GENERIC_ERROR } fn get_message(&self) -> Cow<'static, str> { @@ -215,7 +224,7 @@ impl JsErrorClass for CoreError { | CoreError::MissingFromModuleMap(_) | CoreError::ExecutionTerminated | CoreError::PendingPromiseResolution - | CoreError::EvaluateDynamicImportedModule => "Error", + | CoreError::EvaluateDynamicImportedModule => GENERIC_ERROR, } } @@ -249,7 +258,7 @@ impl JsErrorClass for CoreError { impl JsErrorClass for serde_v8::Error { fn get_class(&self) -> &'static str { - "TypeError" + TYPE_ERROR } } @@ -268,13 +277,13 @@ impl JsErrorClass for std::io::Error { AddrNotAvailable => "AddrNotAvailable", BrokenPipe => "BrokenPipe", AlreadyExists => "AlreadyExists", - InvalidInput => "TypeError", + InvalidInput => TYPE_ERROR, InvalidData => "InvalidData", TimedOut => "TimedOut", Interrupted => "Interrupted", WriteZero => "WriteZero", UnexpectedEof => "UnexpectedEof", - Other => "Error", + Other => GENERIC_ERROR, WouldBlock => "WouldBlock", kind => { let kind_str = kind.to_string(); @@ -283,7 +292,7 @@ impl JsErrorClass for std::io::Error { "IsADirectory" => "IsADirectory", "NetworkUnreachable" => "NetworkUnreachable", "NotADirectory" => "NotADirectory", - _ => "Error", + _ => GENERIC_ERROR, } } } @@ -308,13 +317,13 @@ impl JsErrorClass for std::env::VarError { impl JsErrorClass for std::sync::mpsc::RecvError { fn get_class(&self) -> &'static str { - "Error" + GENERIC_ERROR } } impl JsErrorClass for v8::DataError { fn get_class(&self) -> &'static str { - "TypeError" + TYPE_ERROR } } @@ -322,12 +331,12 @@ impl JsErrorClass for tokio::sync::mpsc::error::SendError { fn get_class(&self) -> &'static str { - "Error" + GENERIC_ERROR } } impl JsErrorClass for tokio::task::JoinError { fn get_class(&self) -> &'static str { - "Error" + GENERIC_ERROR } } @@ -342,7 +351,7 @@ impl JsErrorClass for serde_json::Error { .and_then(|e| e.downcast_ref::()) .unwrap() .get_class(), - Category::Syntax => "SyntaxError", + Category::Syntax => SYNTAX_ERROR, Category::Data => "InvalidData", Category::Eof => "UnexpectedEof", } @@ -351,7 +360,7 @@ impl JsErrorClass for serde_json::Error { impl JsErrorClass for url::ParseError { fn get_class(&self) -> &'static str { - "URIError" + URI_ERROR } } @@ -401,24 +410,24 @@ impl JsNativeError { } pub fn generic(message: impl Into>) -> JsNativeError { - Self::new("Error", message) + Self::new(GENERIC_ERROR, message) } pub fn type_error(message: impl Into>) -> JsNativeError { - Self::new("TypeError", message) + Self::new(TYPE_ERROR, message) } pub fn range_error(message: impl Into>) -> JsNativeError { - Self::new("RangeError", message) + Self::new(RANGE_ERROR, message) } pub fn uri_error(message: impl Into>) -> JsNativeError { - Self::new("URIError", message) + Self::new(URI_ERROR, message) } // Non-standard errors pub fn not_supported() -> JsNativeError { - Self::new("NotSupported", "The operation is not supported") + Self::new(NOT_SUPPORTED_ERROR, "The operation is not supported") } } @@ -954,7 +963,7 @@ impl JsError { let e: NativeJsError = serde_v8::from_v8(scope, exception.into()).unwrap_or_default(); // Get the message by formatting error.name and error.message. - let name = e.name.clone().unwrap_or_else(|| "Error".to_string()); + let name = e.name.clone().unwrap_or_else(|| GENERIC_ERROR.to_string()); let message_prop = e.message.clone().unwrap_or_default(); let exception_message = exception_message.unwrap_or_else(|| { if !name.is_empty() && !message_prop.is_empty() { @@ -1630,7 +1639,7 @@ fn format_stack_trace<'s>( let name = get_property(scope, obj, v8_static_strings::NAME) .filter(|v| !v.is_undefined()) .map(|v| v.to_rust_string_lossy(scope)) - .unwrap_or_else(|| "Error".to_string()); + .unwrap_or_else(|| GENERIC_ERROR.to_string()); match (!msg.is_empty(), !name.is_empty()) { (true, true) => write!(result, "{}: {}", name, msg).unwrap(), diff --git a/core/io/resource_table.rs b/core/io/resource_table.rs index 1ef56d966..c5b0ad6bf 100644 --- a/core/io/resource_table.rs +++ b/core/io/resource_table.rs @@ -245,7 +245,7 @@ pub enum ResourceError { impl crate::error::JsErrorClass for ResourceError { fn get_class(&self) -> &'static str { match self { - ResourceError::Reference => "ReferenceError", + ResourceError::Reference => crate::error::REFERENCE_ERROR, ResourceError::BadResourceId => "BadResource", ResourceError::Unavailable => "Busy", ResourceError::Other(_) => "BadResource", diff --git a/core/module_specifier.rs b/core/module_specifier.rs index 9bd8aebe4..652471000 100644 --- a/core/module_specifier.rs +++ b/core/module_specifier.rs @@ -27,7 +27,7 @@ pub enum ModuleResolutionError { impl super::error::JsErrorClass for ModuleResolutionError { fn get_class(&self) -> &'static str { - "URIError" + crate::error::URI_ERROR } } diff --git a/core/modules/loaders.rs b/core/modules/loaders.rs index 72119a9c1..f5a20b199 100644 --- a/core/modules/loaders.rs +++ b/core/modules/loaders.rs @@ -56,12 +56,12 @@ pub enum ModuleLoaderError { impl JsErrorClass for ModuleLoaderError { fn get_class(&self) -> &'static str { match self { - ModuleLoaderError::SpecifierExcludedFromSnapshot(_) => "Error", - ModuleLoaderError::SpecifierMissingLazyLoadable(_) => "Error", - ModuleLoaderError::NpmUnsupportedMetaResolve => "Error", - ModuleLoaderError::JsonMissingAttribute => "Error", - ModuleLoaderError::NotFound => "Error", - ModuleLoaderError::Unsupported { .. } => "Error", + ModuleLoaderError::SpecifierExcludedFromSnapshot(_) + | ModuleLoaderError::SpecifierMissingLazyLoadable(_) + | ModuleLoaderError::NpmUnsupportedMetaResolve + | ModuleLoaderError::JsonMissingAttribute + | ModuleLoaderError::NotFound + | ModuleLoaderError::Unsupported { .. } => crate::error::GENERIC_ERROR, ModuleLoaderError::Resolution(err) => err.get_class(), ModuleLoaderError::Core(err) => err.get_class(), } diff --git a/core/modules/mod.rs b/core/modules/mod.rs index 59ea7e88b..4f7ab027a 100644 --- a/core/modules/mod.rs +++ b/core/modules/mod.rs @@ -644,7 +644,7 @@ pub enum ModuleConcreteError { impl super::error::JsErrorClass for ModuleConcreteError { fn get_class(&self) -> &'static str { - "Error" + crate::error::GENERIC_ERROR } } diff --git a/core/runtime/bindings.rs b/core/runtime/bindings.rs index 368cb7f96..63efefa9c 100644 --- a/core/runtime/bindings.rs +++ b/core/runtime/bindings.rs @@ -658,7 +658,9 @@ fn catch_dynamic_import_promise_error( let arg = args.get(0); if is_instance_of_error(scope, arg) { let e: crate::error::NativeJsError = serde_v8::from_v8(scope, arg).unwrap(); - let name = e.name.unwrap_or_else(|| "Error".to_string()); + let name = e + .name + .unwrap_or_else(|| crate::error::GENERIC_ERROR.to_string()); if !has_call_site(scope, arg) { let msg = v8::Exception::create_message(scope, arg); let arg: v8::Local = arg.try_into().unwrap(); @@ -673,10 +675,12 @@ fn catch_dynamic_import_promise_error( } } let exception = match name.as_str() { - "RangeError" => v8::Exception::range_error(scope, message), - "TypeError" => v8::Exception::type_error(scope, message), - "SyntaxError" => v8::Exception::syntax_error(scope, message), - "ReferenceError" => v8::Exception::reference_error(scope, message), + crate::error::RANGE_ERROR => v8::Exception::range_error(scope, message), + crate::error::TYPE_ERROR => v8::Exception::type_error(scope, message), + crate::error::SYNTAX_ERROR => { + v8::Exception::syntax_error(scope, message) + } + crate::error::REFERENCE_ERROR => v8::Exception::reference_error(scope, message), _ => v8::Exception::error(scope, message), }; let code_key = CODE.v8_string(scope); From 8ed6ef30c1f658de7e3ca160f07281d859fb7180 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sat, 19 Oct 2024 22:39:10 +0200 Subject: [PATCH 26/52] lint --- core/convert.rs | 2 +- core/error.rs | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/core/convert.rs b/core/convert.rs index a3250c0f6..eecbc6af1 100644 --- a/core/convert.rs +++ b/core/convert.rs @@ -274,6 +274,6 @@ impl<'a> FromV8<'a> for bool { value .try_cast::() .map(|v| v.is_true()) - .map_err(|_| JsNativeError::type_error("Expected boolean").into()) + .map_err(|_| JsNativeError::type_error("Expected boolean")) } } diff --git a/core/error.rs b/core/error.rs index aa65079f9..abd31e75f 100644 --- a/core/error.rs +++ b/core/error.rs @@ -23,14 +23,14 @@ use std::fmt::Write as _; // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. pub type AnyError = anyhow::Error; -pub const GENERIC_ERROR: &'static str = "Error"; -pub const RANGE_ERROR: &'static str = "RangeError"; -pub const TYPE_ERROR: &'static str = "TypeError"; -pub const SYNTAX_ERROR: &'static str = "SyntaxError"; -pub const URI_ERROR: &'static str = "URIError"; -pub const REFERENCE_ERROR: &'static str = "ReferenceError"; - -pub const NOT_SUPPORTED_ERROR: &'static str = "NotSupported"; +pub const GENERIC_ERROR: &str = "Error"; +pub const RANGE_ERROR: &str = "RangeError"; +pub const TYPE_ERROR: &str = "TypeError"; +pub const SYNTAX_ERROR: &str = "SyntaxError"; +pub const URI_ERROR: &str = "URIError"; +pub const REFERENCE_ERROR: &str = "ReferenceError"; + +pub const NOT_SUPPORTED_ERROR: &str = "NotSupported"; #[derive(Debug, thiserror::Error)] pub enum CoreError { From fbada7fc890633162f1ca68c00732c06ebb68dfa Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sun, 20 Oct 2024 03:28:17 +0200 Subject: [PATCH 27/52] fix --- core/benches/snapshot/snapshot.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/core/benches/snapshot/snapshot.rs b/core/benches/snapshot/snapshot.rs index 9693b0559..4bbc246eb 100644 --- a/core/benches/snapshot/snapshot.rs +++ b/core/benches/snapshot/snapshot.rs @@ -3,7 +3,7 @@ use criterion::*; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; -use deno_core::error::JsErrorClass; +use deno_core::error::JsNativeError; use deno_core::Extension; use deno_core::JsRuntime; use deno_core::JsRuntimeForSnapshot; @@ -55,10 +55,16 @@ deno_core::js_error_wrapper!( "TypeError" ); +deno_core::js_error_wrapper!( + deno_ast::TranspileError, + JsTranspileError, + "TypeError" +); + pub fn maybe_transpile_source( specifier: ModuleName, source: ModuleCodeString, -) -> Result<(ModuleCodeString, Option), Box> { +) -> Result<(ModuleCodeString, Option), JsNativeError> { let media_type = MediaType::TypeScript; let parsed = deno_ast::parse_module(ParseParams { @@ -69,7 +75,7 @@ pub fn maybe_transpile_source( scope_analysis: false, maybe_syntax: None, }) - .map_err(JsParseDiagnostic)?; + .map_err(|e| JsNativeError::from_err(JsParseDiagnostic(e)))?; let transpiled_source = parsed .transpile( &deno_ast::TranspileOptions { @@ -82,7 +88,7 @@ pub fn maybe_transpile_source( ..Default::default() }, ) - .map_err(anyhow::Error::new)? + .map_err(|e| JsNativeError::from_err(JsTranspileError(e)))? .into_source(); Ok(( String::from_utf8(transpiled_source.source).unwrap().into(), From 74d993ced0192822477dc15ed800e3c303c8b7ee Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sun, 20 Oct 2024 18:01:18 +0200 Subject: [PATCH 28/52] fix --- core/error.rs | 7 +++++-- core/modules/map.rs | 17 +++++++++++------ core/modules/tests.rs | 2 +- core/runtime/ops.rs | 8 ++------ ops/op2/README.md | 4 ++-- 5 files changed, 21 insertions(+), 17 deletions(-) diff --git a/core/error.rs b/core/error.rs index abd31e75f..f0aa10e9b 100644 --- a/core/error.rs +++ b/core/error.rs @@ -19,6 +19,8 @@ use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write as _; +pub use super::modules::ModuleConcreteError; + /// A generic wrapper that can encapsulate any concrete error type. // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. pub type AnyError = anyhow::Error; @@ -373,7 +375,7 @@ pub struct JsNativeError { impl Display for JsNativeError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - write!(f, "{}: {}", self.class, self.message) + write!(f, "{}", self.message) } } @@ -842,7 +844,7 @@ where Some(result) } -#[derive(Default, serde::Deserialize)] +#[derive(Debug, Default, serde::Deserialize)] pub(crate) struct NativeJsError { pub name: Option, pub message: Option, @@ -933,6 +935,7 @@ impl JsError { exception: v8::Local<'a, v8::Value>, mut seen: HashSet>, ) -> Self { + println!("{}", std::backtrace::Backtrace::force_capture().to_string()); // Create a new HandleScope because we're creating a lot of new local // handles below. let scope = &mut v8::HandleScope::new(scope); diff --git a/core/modules/map.rs b/core/modules/map.rs index 2bbd2b6fa..eacb309db 100644 --- a/core/modules/map.rs +++ b/core/modules/map.rs @@ -176,9 +176,10 @@ impl ModuleMap { let module = v8::Local::new(scope, handle); match module.get_status() { v8::ModuleStatus::Errored => { - return Err( - JsError::from_v8_exception(scope, module.get_exception()).into(), - ); + return Err(CoreError::Js(JsError::from_v8_exception( + scope, + module.get_exception(), + ))); } v8::ModuleStatus::Evaluated => {} _ => { @@ -1209,11 +1210,15 @@ impl ModuleMap { let Some(value) = module.evaluate(tc_scope) else { let exception = tc_scope.exception().unwrap(); - return Err(JsError::from_v8_exception(tc_scope, exception).into()); + return Err(CoreError::Js(JsError::from_v8_exception( + tc_scope, exception, + ))); }; if let Some(exception) = tc_scope.exception() { - return Err(JsError::from_v8_exception(tc_scope, exception).into()); + return Err(CoreError::Js(JsError::from_v8_exception( + tc_scope, exception, + ))); } let status = module.get_status(); @@ -1228,7 +1233,7 @@ impl ModuleMap { PromiseState::Fulfilled => Ok(()), PromiseState::Rejected => { let err = promise.result(tc_scope); - Err(JsError::from_v8_exception(tc_scope, err).into()) + Err(CoreError::Js(JsError::from_v8_exception(tc_scope, err))) } PromiseState::Pending => { unreachable!() diff --git a/core/modules/tests.rs b/core/modules/tests.rs index e83d695c7..55fb36bff 100644 --- a/core/modules/tests.rs +++ b/core/modules/tests.rs @@ -845,7 +845,7 @@ fn test_custom_module_type_callback_synthetic() { match err { ModuleError::Core(err) => { - assert_eq!(err.to_string(), "Error: Can't load 'foo' module"); + assert_eq!(err.to_string(), "Can't load 'foo' module"); } _ => unreachable!(), }; diff --git a/core/runtime/ops.rs b/core/runtime/ops.rs index 81c9d697e..596edba63 100644 --- a/core/runtime/ops.rs +++ b/core/runtime/ops.rs @@ -665,11 +665,7 @@ mod tests { } /// Run a test for a single op. - fn run_test2( - repeat: usize, - op: &str, - test: &str, - ) -> Result<(), anyhow::Error> { + fn run_test2(repeat: usize, op: &str, test: &str) -> Result<(), CoreError> { let mut runtime = JsRuntime::new(RuntimeOptions { extensions: vec![testing::init_ops_and_esm()], ..Default::default() @@ -918,7 +914,7 @@ mod tests { "op_test_result_void_switch();", ) .expect_err("Expected this to fail"); - let CoreError::Js(js_err) = err.downcast::().unwrap() else { + let CoreError::Js(js_err) = err else { unreachable!(); }; assert_eq!(js_err.message, Some("failed!!!".into())); diff --git a/ops/op2/README.md b/ops/op2/README.md index bfbb74d6b..69fc881f0 100644 --- a/ops/op2/README.md +++ b/ops/op2/README.md @@ -18,8 +18,8 @@ buffer. ## Fallible `op`s An `op` function may be declared to return `Result` to indicate that the `op` is -fallible. The error type must implement `Into`. When the function -returns `Err`, an exception is thrown. +fallible. The error type must implement `deno_core::error::JsErrorClass`. When +the function returns `Err`, an exception is thrown. ## `async` calls From 4ed073a24f1c2296b5508c12f2526201096445f9 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sun, 20 Oct 2024 18:08:15 +0200 Subject: [PATCH 29/52] fix --- core/error.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/core/error.rs b/core/error.rs index f0aa10e9b..a5d3340da 100644 --- a/core/error.rs +++ b/core/error.rs @@ -935,7 +935,6 @@ impl JsError { exception: v8::Local<'a, v8::Value>, mut seen: HashSet>, ) -> Self { - println!("{}", std::backtrace::Backtrace::force_capture().to_string()); // Create a new HandleScope because we're creating a lot of new local // handles below. let scope = &mut v8::HandleScope::new(scope); From f29342141a915a41da2f1e5d366d5c97e72601af Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sun, 20 Oct 2024 18:41:10 +0200 Subject: [PATCH 30/52] update test --- ops/op2/test_cases_fail/lifetimes.stderr | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/ops/op2/test_cases_fail/lifetimes.stderr b/ops/op2/test_cases_fail/lifetimes.stderr index 70f3e675a..a47d484f6 100644 --- a/ops/op2/test_cases_fail/lifetimes.stderr +++ b/ops/op2/test_cases_fail/lifetimes.stderr @@ -1,8 +1,8 @@ -error: unused import: `deno_core::error::AnyError` - --> ../op2/test_cases_fail/lifetimes.rs:4:5 +error: unused import: `std::future::Future` + --> ../op2/test_cases_fail/lifetimes.rs:5:5 | -4 | use deno_core::error::AnyError; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +5 | use std::future::Future; + | ^^^^^^^^^^^^^^^^^^^ | note: the lint level is defined here --> ../op2/test_cases_fail/lifetimes.rs:2:9 @@ -11,16 +11,10 @@ note: the lint level is defined here | ^^^^^^^^ = note: `#[deny(unused_imports)]` implied by `#[deny(warnings)]` -error: unused import: `std::future::Future` - --> ../op2/test_cases_fail/lifetimes.rs:6:5 - | -6 | use std::future::Future; - | ^^^^^^^^^^^^^^^^^^^ - error[E0597]: `arg0` does not live long enough - --> ../op2/test_cases_fail/lifetimes.rs:12:1 + --> ../op2/test_cases_fail/lifetimes.rs:11:1 | -12 | #[op2(fast)] +11 | #[op2(fast)] | ^^^^^^^^^^^- | | | | | `arg0` dropped here while still borrowed @@ -30,9 +24,9 @@ error[E0597]: `arg0` does not live long enough = note: this error originates in the attribute macro `op2` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0597]: `arg0_temp` does not live long enough - --> ../op2/test_cases_fail/lifetimes.rs:15:1 + --> ../op2/test_cases_fail/lifetimes.rs:14:1 | -15 | #[op2(fast)] +14 | #[op2(fast)] | ^^^^^^^^^^^- | | | | | `arg0_temp` dropped here while still borrowed From abdf96149591ead9c10f9c710ebaa4f04ae69b23 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Tue, 22 Oct 2024 16:09:20 +0200 Subject: [PATCH 31/52] unnecessary_wraps --- ops/lib.rs | 1 + ops/op2/dispatch_async.rs | 1 - ops/op2/dispatch_slow.rs | 76 +++++++++++++++++++-------------------- ops/op2/mod.rs | 2 -- 4 files changed, 38 insertions(+), 42 deletions(-) diff --git a/ops/lib.rs b/ops/lib.rs index 2b7d4c9cb..8877726c6 100644 --- a/ops/lib.rs +++ b/ops/lib.rs @@ -1,5 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. #![doc = include_str!("README.md")] +#![deny(clippy::unnecessary_wraps)] use proc_macro::TokenStream; use std::error::Error; diff --git a/ops/op2/dispatch_async.rs b/ops/op2/dispatch_async.rs index dad16bf43..f2be8d5b5 100644 --- a/ops/op2/dispatch_async.rs +++ b/ops/op2/dispatch_async.rs @@ -49,7 +49,6 @@ pub(crate) fn generate_dispatch_async( let with_self = if generator_state.needs_self { with_self(generator_state, &signature.ret_val) - .map_err(V8SignatureMappingError::NoSelfMapping)? } else { quote!() }; diff --git a/ops/op2/dispatch_slow.rs b/ops/op2/dispatch_slow.rs index 99f94003a..8ac58fb22 100644 --- a/ops/op2/dispatch_slow.rs +++ b/ops/op2/dispatch_slow.rs @@ -113,7 +113,6 @@ pub(crate) fn generate_dispatch_slow( let with_self = if generator_state.needs_self { with_self(generator_state, &signature.ret_val) - .map_err(V8SignatureMappingError::NoSelfMapping)? } else { quote!() }; @@ -252,14 +251,14 @@ pub(crate) fn with_js_runtime_state( pub(crate) fn with_self( generator_state: &mut GeneratorState, ret_val: &RetVal, -) -> Result { +) -> TokenStream { generator_state.needs_opctx = true; generator_state.needs_scope = true; let throw_exception = throw_type_error( generator_state, format!("expected {}", &generator_state.self_ty), - )?; - let tokens = if matches!(ret_val, RetVal::Future(_) | RetVal::FutureResult(_)) + ); + if matches!(ret_val, RetVal::Future(_) | RetVal::FutureResult(_)) { let tokens = gs_quote!(generator_state(self_ty, fn_args, scope) => { let Some(mut self_) = deno_core::_ops::try_unwrap_cppgc_object::<#self_ty>(&mut #scope, #fn_args.this().into()) else { @@ -280,8 +279,7 @@ pub(crate) fn with_self( }; let self_ = &*self_; }) - }; - Ok(tokens) + } } pub fn extract_arg( @@ -330,29 +328,29 @@ pub fn from_arg( Arg::Numeric(NumericArg::u8, _) | Arg::Numeric(NumericArg::u16, _) | Arg::Numeric(NumericArg::u32, _) => { - from_arg_option(generator_state, &arg_ident, "u32")? + from_arg_option(generator_state, &arg_ident, "u32") } Arg::Numeric(NumericArg::i8, _) | Arg::Numeric(NumericArg::i16, _) | Arg::Numeric(NumericArg::i32, _) | Arg::Numeric(NumericArg::__SMI__, _) => { - from_arg_option(generator_state, &arg_ident, "i32")? + from_arg_option(generator_state, &arg_ident, "i32") } Arg::Numeric(NumericArg::u64 | NumericArg::usize, NumericFlag::None) => { - from_arg_option(generator_state, &arg_ident, "u64")? + from_arg_option(generator_state, &arg_ident, "u64") } Arg::Numeric(NumericArg::i64 | NumericArg::isize, NumericFlag::None) => { - from_arg_option(generator_state, &arg_ident, "i64")? + from_arg_option(generator_state, &arg_ident, "i64") } Arg::Numeric( NumericArg::u64 | NumericArg::usize | NumericArg::i64 | NumericArg::isize, NumericFlag::Number, - ) => from_arg_option(generator_state, &arg_ident, "f64")?, + ) => from_arg_option(generator_state, &arg_ident, "f64"), Arg::Numeric(NumericArg::f32, _) => { - from_arg_option(generator_state, &arg_ident, "f32")? + from_arg_option(generator_state, &arg_ident, "f32") } Arg::Numeric(NumericArg::f64, _) => { - from_arg_option(generator_state, &arg_ident, "f64")? + from_arg_option(generator_state, &arg_ident, "f64") } Arg::OptionNumeric(numeric, flag) => { let some = from_arg( @@ -410,7 +408,7 @@ pub fn from_arg( // Only requires isolate, not a full scope *needs_isolate = true; let throw_exception = - throw_type_error_static_string(generator_state, &arg_ident)?; + throw_type_error_static_string(generator_state, &arg_ident); gs_quote!(generator_state(scope) => { // Trade stack space for potentially non-allocating strings let #arg_ident = match deno_core::_ops::to_cow_one_byte(&mut #scope, &#arg_ident) { @@ -459,7 +457,7 @@ pub fn from_arg( } } Arg::External(External::Ptr(_)) => { - from_arg_option(generator_state, &arg_ident, "external")? + from_arg_option(generator_state, &arg_ident, "external") } Arg::Special(Special::Isolate) => { *needs_opctx = true; @@ -530,7 +528,7 @@ pub fn from_arg( | Arg::V8Ref(RefType::Ref, v8) | Arg::OptionV8Ref(RefType::Ref, v8) => { let throw_type_error = - || throw_type_error(generator_state, format!("expected {v8:?}")); + || Ok(throw_type_error(generator_state, format!("expected {v8:?}"))); let extract_intermediate = v8_intermediate_to_arg(&arg_ident, arg); v8_to_arg(v8, &arg_ident, arg, throw_type_error, extract_intermediate)? } @@ -539,7 +537,7 @@ pub fn from_arg( *needs_isolate = true; let scope = scope.clone(); let throw_type_error = - || throw_type_error(generator_state, format!("expected {v8:?}")); + || Ok(throw_type_error(generator_state, format!("expected {v8:?}"))); let extract_intermediate = v8_intermediate_to_global_arg(&scope, &arg_ident, arg); v8_to_arg(v8, &arg_ident, arg, throw_type_error, extract_intermediate)? @@ -548,7 +546,7 @@ pub fn from_arg( *needs_scope = true; let scope = scope.clone(); let err = format_ident!("{}_err", arg_ident); - let throw_exception = throw_type_error_string(generator_state, &err)?; + let throw_exception = throw_type_error_string(generator_state, &err); quote! { let #arg_ident = match deno_core::_ops::serde_v8_to_rust(&mut #scope, #arg_ident) { Ok(t) => t, @@ -564,7 +562,7 @@ pub fn from_arg( syn::parse_str::(ty).expect("Failed to reparse state type"); let scope = scope.clone(); let err = format_ident!("{}_err", arg_ident); - let throw_exception = throw_type_error_string(generator_state, &err)?; + let throw_exception = throw_type_error_string(generator_state, &err); quote! { let #arg_ident = match <#ty as deno_core::FromV8>::from_v8(&mut #scope, #arg_ident) { Ok(t) => t, @@ -578,7 +576,7 @@ pub fn from_arg( *needs_scope = true; let scope = scope.clone(); let throw_exception = - throw_type_error(generator_state, format!("expected {}", &ty))?; + throw_type_error(generator_state, format!("expected {}", &ty)); let ty = syn::parse_str::(ty).expect("Failed to reparse state type"); if matches!(ret_val, RetVal::Future(_) | RetVal::FutureResult(_)) { @@ -604,7 +602,7 @@ pub fn from_arg( Arg::OptionCppGcResource(ty) => { *needs_scope = true; let throw_exception = - throw_type_error(generator_state, format!("expected {}", &ty))?; + throw_type_error(generator_state, format!("expected {}", &ty)); let ty = syn::parse_str::(ty).expect("Failed to reparse state type"); let scope = &generator_state.scope; @@ -648,16 +646,16 @@ pub fn from_arg_option( generator_state: &mut GeneratorState, arg_ident: &Ident, numeric: &str, -) -> Result { +) -> TokenStream { let exception = - throw_type_error(generator_state, format!("expected {numeric}"))?; + throw_type_error(generator_state, format!("expected {numeric}")); let convert = format_ident!("to_{numeric}_option"); - Ok(quote!( + quote!( let Some(#arg_ident) = deno_core::_ops::#convert(&#arg_ident) else { #exception }; let #arg_ident = #arg_ident as _; - )) + ) } pub fn from_arg_array_or_buffer( @@ -701,7 +699,7 @@ pub fn from_arg_buffer( temp: &Ident, ) -> Result { let err = format_ident!("{}_err", arg_ident); - let throw_exception = throw_type_error_static_string(generator_state, &err)?; + let throw_exception = throw_type_error_static_string(generator_state, &err); let array = buffer_type.element(); @@ -737,7 +735,7 @@ pub fn from_arg_arraybuffer( temp: &Ident, ) -> Result { let err = format_ident!("{}_err", arg_ident); - let throw_exception = throw_type_error_static_string(generator_state, &err)?; + let throw_exception = throw_type_error_static_string(generator_state, &err); let to_v8_slice = if matches!(buffer_mode, BufferMode::Detach) { quote!(to_v8_slice_buffer_detachable) @@ -770,7 +768,7 @@ pub fn from_arg_any_buffer( temp: &Ident, ) -> Result { let err = format_ident!("{}_err", arg_ident); - let throw_exception = throw_type_error_static_string(generator_state, &err)?; + let throw_exception = throw_type_error_static_string(generator_state, &err); let to_v8_slice = if matches!(buffer_mode, BufferMode::Detach) { quote!(to_v8_slice_any_detachable) @@ -886,7 +884,7 @@ pub fn return_value_infallible( ArgSlowRetval::RetValFallible => { generator_state.needs_scope = true; let err = format_ident!("{}_err", generator_state.retval); - let throw_exception = throw_type_error_string(generator_state, &err)?; + let throw_exception = throw_type_error_string(generator_state, &err); gs_quote!(generator_state(scope, retval) => (match deno_core::_ops::RustToV8Fallible::to_v8_fallible(#result, &mut #scope) { Ok(v) => #retval.set(v), @@ -905,7 +903,7 @@ pub fn return_value_infallible( ArgSlowRetval::V8LocalFalliable => { generator_state.needs_scope = true; let err = format_ident!("{}_err", generator_state.retval); - let throw_exception = throw_type_error_string(generator_state, &err)?; + let throw_exception = throw_type_error_string(generator_state, &err); gs_quote!(generator_state(scope, retval) => (match deno_core::_ops::RustToV8Fallible::to_v8_fallible(#result, &mut #scope) { Ok(v) => #retval.set(v), @@ -1026,7 +1024,7 @@ pub(crate) fn throw_exception( fn throw_type_error( generator_state: &mut GeneratorState, message: String, -) -> Result { +) -> TokenStream { // Sanity check ASCII and a valid/reasonable message size debug_assert!(message.is_ascii() && message.len() < 1024); @@ -1036,52 +1034,52 @@ fn throw_type_error( with_scope(generator_state) }; - Ok(gs_quote!(generator_state(scope) => { + gs_quote!(generator_state(scope) => { #maybe_scope let msg = deno_core::v8::String::new_from_one_byte(&mut #scope, #message.as_bytes(), deno_core::v8::NewStringType::Normal).unwrap(); let exc = deno_core::v8::Exception::type_error(&mut #scope, msg); #scope.throw_exception(exc); return 1; - })) + }) } /// Generates code to throw an exception from a string variable, adding required additional dependencies as needed. fn throw_type_error_string( generator_state: &mut GeneratorState, message: &Ident, -) -> Result { +) -> TokenStream { let maybe_scope = if generator_state.needs_scope { quote!() } else { with_scope(generator_state) }; - Ok(gs_quote!(generator_state(scope) => { + gs_quote!(generator_state(scope) => { #maybe_scope // TODO(mmastrac): This might be allocating too much, even if it's on the error path let msg = deno_core::v8::String::new(&mut #scope, &format!("{}", deno_core::anyhow::Error::from(#message))).unwrap(); let exc = deno_core::v8::Exception::type_error(&mut #scope, msg); #scope.throw_exception(exc); return 1; - })) + }) } /// Generates code to throw an exception from a string variable, adding required additional dependencies as needed. fn throw_type_error_static_string( generator_state: &mut GeneratorState, message: &Ident, -) -> Result { +) -> TokenStream { let maybe_scope = if generator_state.needs_scope { quote!() } else { with_scope(generator_state) }; - Ok(gs_quote!(generator_state(scope) => { + gs_quote!(generator_state(scope) => { #maybe_scope let msg = deno_core::v8::String::new_from_one_byte(&mut #scope, #message.as_bytes(), deno_core::v8::NewStringType::Normal).unwrap(); let exc = deno_core::v8::Exception::type_error(&mut #scope, msg); #scope.throw_exception(exc); return 1; - })) + }) } diff --git a/ops/op2/mod.rs b/ops/op2/mod.rs index 6671014d4..8246718d2 100644 --- a/ops/op2/mod.rs +++ b/ops/op2/mod.rs @@ -70,8 +70,6 @@ pub enum V8SignatureMappingError { NoRetValMapping(V8MappingError, RetVal), #[error("Unable to map argument {1:?} to {0}")] NoArgMapping(V8MappingError, Arg), - #[error("Unable to map self")] - NoSelfMapping(V8MappingError), } pub type V8MappingError = &'static str; From 73955f7bb53949bfd3bc9ce143ef5f03076d89ea Mon Sep 17 00:00:00 2001 From: crowlkats Date: Tue, 22 Oct 2024 16:35:01 +0200 Subject: [PATCH 32/52] fixes and cleanup --- core/error.rs | 20 ++++--------- core/ops_builtin.rs | 4 +-- ops/op2/dispatch_slow.rs | 19 ++++++++---- testing/checkin/runner/extensions.rs | 2 -- testing/checkin/runner/mod.rs | 19 +++++------- testing/checkin/runner/ops_error.rs | 35 ++++++---------------- testing/checkin/runner/ops_worker.rs | 3 +- testing/checkin/runner/ts_module_loader.rs | 16 ++++++++-- testing/checkin/runtime/error.ts | 13 -------- testing/unit/error_test.ts | 22 +------------- 10 files changed, 54 insertions(+), 99 deletions(-) diff --git a/core/error.rs b/core/error.rs index a5d3340da..990baa3d9 100644 --- a/core/error.rs +++ b/core/error.rs @@ -85,7 +85,7 @@ pub enum CoreError { )] EvaluateDynamicImportedModule, #[error(transparent)] - Module(super::modules::ModuleConcreteError), + Module(ModuleConcreteError), #[error(transparent)] DataError(#[from] v8::DataError), #[error(transparent)] @@ -192,16 +192,6 @@ fn js_class_and_message_to_exception<'s>( } } -impl JsErrorClass for anyhow::Error { - fn get_class(&self) -> &'static str { - GENERIC_ERROR - } - - fn get_message(&self) -> Cow<'static, str> { - format!("{:#}", self).into() - } -} - impl JsErrorClass for CoreError { fn get_class(&self) -> &'static str { match self { @@ -216,7 +206,6 @@ impl JsErrorClass for CoreError { CoreError::Url(err) => err.get_class(), CoreError::Module(err) => err.get_class(), CoreError::DataError(err) => err.get_class(), - CoreError::Other(err) => err.get_class(), CoreError::FutureCanceled(_) => "Interrupted", CoreError::TLA | CoreError::Parse(_) @@ -226,7 +215,8 @@ impl JsErrorClass for CoreError { | CoreError::MissingFromModuleMap(_) | CoreError::ExecutionTerminated | CoreError::PendingPromiseResolution - | CoreError::EvaluateDynamicImportedModule => GENERIC_ERROR, + | CoreError::EvaluateDynamicImportedModule + | CoreError::Other(_) => GENERIC_ERROR, } } @@ -243,7 +233,6 @@ impl JsErrorClass for CoreError { CoreError::Url(err) => err.get_message(), CoreError::Module(err) => err.get_message(), CoreError::DataError(err) => err.get_message(), - CoreError::Other(err) => err.get_message(), CoreError::TLA | CoreError::Parse(_) | CoreError::Execute(_) @@ -253,7 +242,8 @@ impl JsErrorClass for CoreError { | CoreError::FutureCanceled(_) | CoreError::ExecutionTerminated | CoreError::PendingPromiseResolution - | CoreError::EvaluateDynamicImportedModule => self.to_string().into(), + | CoreError::EvaluateDynamicImportedModule + | CoreError::Other(_) => self.to_string().into(), } } } diff --git a/core/ops_builtin.rs b/core/ops_builtin.rs index cd18afe90..22215425c 100644 --- a/core/ops_builtin.rs +++ b/core/ops_builtin.rs @@ -175,13 +175,13 @@ pub async fn op_void_async() {} #[allow(clippy::unused_async)] #[op2(async)] pub async fn op_error_async() -> Result<(), OpError> { - Err(anyhow::Error::msg("error").into()) + Err(JsNativeError::generic("error").into()) } #[allow(clippy::unused_async)] #[op2(async(deferred), fast)] pub async fn op_error_async_deferred() -> Result<(), OpError> { - Err(anyhow::Error::msg("error").into()) + Err(JsNativeError::generic("error").into()) } #[allow(clippy::unused_async)] diff --git a/ops/op2/dispatch_slow.rs b/ops/op2/dispatch_slow.rs index 8ac58fb22..e09e3005b 100644 --- a/ops/op2/dispatch_slow.rs +++ b/ops/op2/dispatch_slow.rs @@ -258,8 +258,7 @@ pub(crate) fn with_self( generator_state, format!("expected {}", &generator_state.self_ty), ); - if matches!(ret_val, RetVal::Future(_) | RetVal::FutureResult(_)) - { + if matches!(ret_val, RetVal::Future(_) | RetVal::FutureResult(_)) { let tokens = gs_quote!(generator_state(self_ty, fn_args, scope) => { let Some(mut self_) = deno_core::_ops::try_unwrap_cppgc_object::<#self_ty>(&mut #scope, #fn_args.this().into()) else { #throw_exception; @@ -527,8 +526,12 @@ pub fn from_arg( | Arg::OptionV8Local(v8) | Arg::V8Ref(RefType::Ref, v8) | Arg::OptionV8Ref(RefType::Ref, v8) => { - let throw_type_error = - || Ok(throw_type_error(generator_state, format!("expected {v8:?}"))); + let throw_type_error = || { + Ok(throw_type_error( + generator_state, + format!("expected {v8:?}"), + )) + }; let extract_intermediate = v8_intermediate_to_arg(&arg_ident, arg); v8_to_arg(v8, &arg_ident, arg, throw_type_error, extract_intermediate)? } @@ -536,8 +539,12 @@ pub fn from_arg( // Only requires isolate, not a full scope *needs_isolate = true; let scope = scope.clone(); - let throw_type_error = - || Ok(throw_type_error(generator_state, format!("expected {v8:?}"))); + let throw_type_error = || { + Ok(throw_type_error( + generator_state, + format!("expected {v8:?}"), + )) + }; let extract_intermediate = v8_intermediate_to_global_arg(&scope, &arg_ident, arg); v8_to_arg(v8, &arg_ident, arg, throw_type_error, extract_intermediate)? diff --git a/testing/checkin/runner/extensions.rs b/testing/checkin/runner/extensions.rs index d9b97001e..f237d134d 100644 --- a/testing/checkin/runner/extensions.rs +++ b/testing/checkin/runner/extensions.rs @@ -38,8 +38,6 @@ deno_core::extension!( ops_error::op_async_throw_error_lazy, ops_error::op_async_throw_error_deferred, ops_error::op_error_custom_sync, - ops_error::op_error_context_sync, - ops_error::op_error_context_async, ops_buffer::op_v8slice_store, ops_buffer::op_v8slice_clone, ops_worker::op_worker_spawn, diff --git a/testing/checkin/runner/mod.rs b/testing/checkin/runner/mod.rs index 76f63efcb..279f7c0f3 100644 --- a/testing/checkin/runner/mod.rs +++ b/testing/checkin/runner/mod.rs @@ -3,7 +3,6 @@ use self::ops_worker::worker_create; use self::ops_worker::WorkerCloseWatcher; use self::ops_worker::WorkerHostSide; use self::ts_module_loader::maybe_transpile_source; -use anyhow::Context; use deno_core::error::JsNativeError; use deno_core::v8; use deno_core::CrossIsolateStore; @@ -168,7 +167,7 @@ fn custom_module_evaluation_cb( code: ModuleSourceCode, ) -> Result { match &*module_type { - "bytes" => bytes_module(scope, code), + "bytes" => Ok(bytes_module(scope, code)), "text" => text_module(scope, module_name, code), _ => Err(JsNativeError::generic(format!( "Can't import {:?} because of unknown module type {}", @@ -180,7 +179,7 @@ fn custom_module_evaluation_cb( fn bytes_module( scope: &mut v8::HandleScope, code: ModuleSourceCode, -) -> Result { +) -> CustomModuleEvaluationKind { // FsModuleLoader always returns bytes. let ModuleSourceCode::Bytes(buf) = code else { unreachable!() @@ -192,9 +191,7 @@ fn bytes_module( let ab = v8::ArrayBuffer::with_backing_store(scope, &backing_store_shared); let uint8_array = v8::Uint8Array::new(scope, ab, 0, buf_len).unwrap(); let value: v8::Local = uint8_array.into(); - Ok(CustomModuleEvaluationKind::Synthetic(v8::Global::new( - scope, value, - ))) + CustomModuleEvaluationKind::Synthetic(v8::Global::new(scope, value)) } fn text_module( @@ -207,11 +204,11 @@ fn text_module( unreachable!() }; - let code = std::str::from_utf8(buf.as_bytes()) - .with_context(|| { - format!("Can't convert {:?} source code to string", module_name) - }) - .map_err(JsNativeError::from_err)?; + let code = std::str::from_utf8(buf.as_bytes()).map_err(|e| { + JsNativeError::generic(format!( + "Can't convert {module_name:?} source code to string: {e}" + )) + })?; let str_ = v8::String::new(scope, code).unwrap(); let value: v8::Local = str_.into(); Ok(CustomModuleEvaluationKind::Synthetic(v8::Global::new( diff --git a/testing/checkin/runner/ops_error.rs b/testing/checkin/runner/ops_error.rs index d44cc7ce8..96b671839 100644 --- a/testing/checkin/runner/ops_error.rs +++ b/testing/checkin/runner/ops_error.rs @@ -1,42 +1,25 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use anyhow::anyhow; use deno_core::error::JsNativeError; -use deno_core::error::OpError; -use deno_core::error::ResourceError; use deno_core::op2; #[op2(async)] -pub async fn op_async_throw_error_eager() -> Result<(), OpError> { - Err(JsNativeError::type_error("Error").into()) +pub async fn op_async_throw_error_eager() -> Result<(), JsNativeError> { + Err(JsNativeError::type_error("Error")) } #[op2(async(deferred), fast)] -pub async fn op_async_throw_error_deferred() -> Result<(), OpError> { - Err(JsNativeError::type_error("Error").into()) +pub async fn op_async_throw_error_deferred() -> Result<(), JsNativeError> { + Err(JsNativeError::type_error("Error")) } #[op2(async(lazy), fast)] -pub async fn op_async_throw_error_lazy() -> Result<(), OpError> { - Err(JsNativeError::type_error("Error").into()) +pub async fn op_async_throw_error_lazy() -> Result<(), JsNativeError> { + Err(JsNativeError::type_error("Error")) } #[op2(fast)] -pub fn op_error_custom_sync(#[string] message: String) -> Result<(), OpError> { - Err(ResourceError::Other(message).into()) -} - -#[op2(fast)] -pub fn op_error_context_sync( - #[string] message: String, - #[string] context: String, -) -> Result<(), OpError> { - Err(anyhow::Error::msg(message).context(context).into()) -} - -#[op2(async)] -pub async fn op_error_context_async( +pub fn op_error_custom_sync( #[string] message: String, - #[string] context: String, -) -> Result<(), OpError> { - Err(anyhow!(message).context(context).into()) +) -> Result<(), JsNativeError> { + Err(JsNativeError::generic(message)) } diff --git a/testing/checkin/runner/ops_worker.rs b/testing/checkin/runner/ops_worker.rs index 108227628..4bcbb2cdb 100644 --- a/testing/checkin/runner/ops_worker.rs +++ b/testing/checkin/runner/ops_worker.rs @@ -3,6 +3,7 @@ use super::create_runtime; use super::run_async; use super::Output; use anyhow::anyhow; +use deno_core::error::JsNativeError; use deno_core::error::OpError; use deno_core::op2; use deno_core::url::Url; @@ -180,7 +181,7 @@ pub fn op_worker_parent( worker.parent_channel.lock().unwrap().take(), worker.parent_close_watcher.lock().unwrap().take(), ) else { - return Err(anyhow!("No parent worker is available").into()); + return Err(JsNativeError::generic("No parent worker is available").into()); }; Ok(WorkerControl { worker_channel, diff --git a/testing/checkin/runner/ts_module_loader.rs b/testing/checkin/runner/ts_module_loader.rs index 199e861ce..26e838852 100644 --- a/testing/checkin/runner/ts_module_loader.rs +++ b/testing/checkin/runner/ts_module_loader.rs @@ -36,6 +36,18 @@ pub struct TypescriptModuleLoader { source_maps: SourceMapStore, } +deno_core::js_error_wrapper!( + deno_ast::ParseDiagnostic, + JsParseDiagnostic, + "TypeError" +); + +deno_core::js_error_wrapper!( + deno_ast::TranspileError, + JsTranspileError, + "TypeError" +); + // TODO(bartlomieju): this is duplicated in `core/examples/ts_modules_loader.rs`. impl ModuleLoader for TypescriptModuleLoader { fn resolve( @@ -192,7 +204,7 @@ pub fn maybe_transpile_source( scope_analysis: false, maybe_syntax: None, }) - .map_err(|err| JsNativeError::from_err(anyhow::Error::from(err)))?; + .map_err(|err| JsNativeError::from_err(JsParseDiagnostic(err)))?; let transpiled_source = parsed .transpile( &deno_ast::TranspileOptions { @@ -206,7 +218,7 @@ pub fn maybe_transpile_source( ..Default::default() }, ) - .map_err(|err| JsNativeError::from_err(anyhow::Error::from(err)))? + .map_err(|err| JsNativeError::from_err(JsTranspileError(err)))? .into_source(); Ok(( diff --git a/testing/checkin/runtime/error.ts b/testing/checkin/runtime/error.ts index 4dca78fe8..95d7af172 100644 --- a/testing/checkin/runtime/error.ts +++ b/testing/checkin/runtime/error.ts @@ -3,8 +3,6 @@ import { op_async_throw_error_deferred, op_async_throw_error_eager, op_async_throw_error_lazy, - op_error_context_async, - op_error_context_sync, op_error_custom_sync, } from "ext:core/ops"; @@ -20,14 +18,3 @@ export async function asyncThrow(kind: "lazy" | "eager" | "deferred") { export function throwCustomError(message: string) { op_error_custom_sync(message); } - -export function throwErrorWithContextSync(message: string, context: string) { - op_error_context_sync(message, context); -} - -export async function throwErrorWithContextAsync( - message: string, - context: string, -) { - await op_error_context_async(message, context); -} diff --git a/testing/unit/error_test.ts b/testing/unit/error_test.ts index 03b408d40..90d287bf7 100644 --- a/testing/unit/error_test.ts +++ b/testing/unit/error_test.ts @@ -1,27 +1,7 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -import { - throwCustomError, - throwErrorWithContextAsync, - throwErrorWithContextSync, -} from "checkin:error"; +import { throwCustomError } from "checkin:error"; import { assert, assertEquals, test } from "checkin:testing"; -test(function testSyncContext() { - try { - throwErrorWithContextSync("message", "with context"); - } catch (e) { - assertEquals(e.message, "with context: message"); - } -}); - -test(async function testAsyncContext() { - try { - await throwErrorWithContextAsync("message", "with context"); - } catch (e) { - assertEquals(e.message, "with context: message"); - } -}); - test(function testCustomError() { try { throwCustomError("uh oh"); From b3e1c2a5ae3c0f6f0c845e9cf206d85cb4baac82 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sun, 10 Nov 2024 10:15:14 +0100 Subject: [PATCH 33/52] jserror macro --- Cargo.lock | 16 ++ Cargo.toml | 2 + core/Cargo.toml | 1 + core/error.rs | 128 +++++++++-- core/io/resource_table.rs | 17 +- core/lib.rs | 1 + core/module_specifier.rs | 9 +- core/modules/loaders.rs | 33 ++- core/modules/mod.rs | 9 +- core/runtime/op_driver/op_results.rs | 9 +- js_error/Cargo.toml | 28 +++ js_error/js_error/mod.rs | 326 +++++++++++++++++++++++++++ js_error/lib.rs | 18 ++ 13 files changed, 538 insertions(+), 59 deletions(-) create mode 100644 js_error/Cargo.toml create mode 100644 js_error/js_error/mod.rs create mode 100644 js_error/lib.rs diff --git a/Cargo.lock b/Cargo.lock index be5a5eac1..8dcd8d5b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -574,6 +574,7 @@ dependencies = [ "criterion", "deno_ast", "deno_core_icudata", + "deno_js_error", "deno_ops", "deno_unsync", "fastrand", @@ -620,6 +621,21 @@ dependencies = [ "url", ] +[[package]] +name = "deno_js_error" +version = "0.1.0" +dependencies = [ + "pretty_assertions", + "prettyplease", + "proc-macro-rules", + "proc-macro2", + "quote", + "strum", + "strum_macros", + "syn", + "testing_macros", +] + [[package]] name = "deno_media_type" version = "0.1.4" diff --git a/Cargo.toml b/Cargo.toml index 6243034ff..0ca6d42c3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ members = [ "core/examples/snapshot", "dcore", "ops", + "js_error", "ops/compile_test_runner", "serde_v8", "testing", @@ -22,6 +23,7 @@ repository = "https://github.com/denoland/deno_core" # Local dependencies deno_core = { version = "0.314.2", path = "./core" } deno_ops = { version = "0.190.1", path = "./ops" } +deno_js_error = { version = "0.1.0", path = "./js_error" } serde_v8 = { version = "0.223.1", path = "./serde_v8" } deno_core_testing = { path = "./testing" } diff --git a/core/Cargo.toml b/core/Cargo.toml index 69c8d543c..45e0fa451 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -48,6 +48,7 @@ tokio.workspace = true url.workspace = true v8.workspace = true thiserror = "1.0.60" +deno_js_error.workspace = true [dev-dependencies] bencher.workspace = true diff --git a/core/error.rs b/core/error.rs index 990baa3d9..9fb0ef589 100644 --- a/core/error.rs +++ b/core/error.rs @@ -25,14 +25,18 @@ pub use super::modules::ModuleConcreteError; // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. pub type AnyError = anyhow::Error; -pub const GENERIC_ERROR: &str = "Error"; -pub const RANGE_ERROR: &str = "RangeError"; -pub const TYPE_ERROR: &str = "TypeError"; -pub const SYNTAX_ERROR: &str = "SyntaxError"; -pub const URI_ERROR: &str = "URIError"; -pub const REFERENCE_ERROR: &str = "ReferenceError"; +pub mod builtin_classes { + pub const GENERIC_ERROR: &str = "Error"; + pub const RANGE_ERROR: &str = "RangeError"; + pub const TYPE_ERROR: &str = "TypeError"; + pub const SYNTAX_ERROR: &str = "SyntaxError"; + pub const URI_ERROR: &str = "URIError"; + pub const REFERENCE_ERROR: &str = "ReferenceError"; + + pub const NOT_SUPPORTED_ERROR: &str = "NotSupported"; +} -pub const NOT_SUPPORTED_ERROR: &str = "NotSupported"; +pub use builtin_classes::*; #[derive(Debug, thiserror::Error)] pub enum CoreError { @@ -150,16 +154,15 @@ impl From for CoreError { } } +/// Trait to implement how an error should be represented in JavaScript. +/// Note: it is not recommended to manually implement this type, but instead +/// rather use the [deno_core::JsError] macro. pub trait JsErrorClass: Display + Debug + Send + Sync + 'static { fn get_class(&self) -> &'static str; - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } + fn get_message(&self) -> Cow<'static, str>; fn get_additional_properties( &self, - ) -> Option, Cow<'static, str>)>> { - None - } + ) -> Option, Cow<'static, str>)>>; fn to_native(self) -> JsNativeError where Self: Sized, @@ -246,12 +249,28 @@ impl JsErrorClass for CoreError { | CoreError::Other(_) => self.to_string().into(), } } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + None // TODO + } } impl JsErrorClass for serde_v8::Error { fn get_class(&self) -> &'static str { TYPE_ERROR } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + None + } } impl JsErrorClass for std::io::Error { @@ -290,6 +309,10 @@ impl JsErrorClass for std::io::Error { } } + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } + fn get_additional_properties( &self, ) -> Option, Cow<'static, str>)>> { @@ -305,18 +328,48 @@ impl JsErrorClass for std::env::VarError { std::env::VarError::NotUnicode(..) => "InvalidData", } } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + None + } } impl JsErrorClass for std::sync::mpsc::RecvError { fn get_class(&self) -> &'static str { GENERIC_ERROR } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + None + } } impl JsErrorClass for v8::DataError { fn get_class(&self) -> &'static str { TYPE_ERROR } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + None + } } impl JsErrorClass @@ -325,11 +378,31 @@ impl JsErrorClass fn get_class(&self) -> &'static str { GENERIC_ERROR } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + None + } } impl JsErrorClass for tokio::task::JoinError { fn get_class(&self) -> &'static str { GENERIC_ERROR } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + None + } } impl JsErrorClass for serde_json::Error { @@ -348,12 +421,32 @@ impl JsErrorClass for serde_json::Error { Category::Eof => "UnexpectedEof", } } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + None // TODO: could be io error code + } } impl JsErrorClass for url::ParseError { fn get_class(&self) -> &'static str { URI_ERROR } + + fn get_message(&self) -> Cow<'static, str> { + self.to_string().into() + } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + None + } } #[derive(Debug)] @@ -379,6 +472,15 @@ impl JsErrorClass for JsNativeError { fn get_message(&self) -> Cow<'static, str> { self.message.clone() } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + self + .source + .as_ref() + .and_then(|source| source.get_additional_properties()) + } } impl JsNativeError { diff --git a/core/io/resource_table.rs b/core/io/resource_table.rs index c5b0ad6bf..7790e4735 100644 --- a/core/io/resource_table.rs +++ b/core/io/resource_table.rs @@ -230,25 +230,18 @@ impl ResourceTable { } } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, crate::JsError)] pub enum ResourceError { + #[class(REFERENCE)] #[error("null or invalid handle")] Reference, + #[class("BadResource")] #[error("Bad resource ID")] BadResourceId, + #[class("Busy")] #[error("Resource is unavailable because it is in use by a promise")] Unavailable, + #[class("BadResource")] #[error("{0}")] Other(String), } - -impl crate::error::JsErrorClass for ResourceError { - fn get_class(&self) -> &'static str { - match self { - ResourceError::Reference => crate::error::REFERENCE_ERROR, - ResourceError::BadResourceId => "BadResource", - ResourceError::Unavailable => "Busy", - ResourceError::Other(_) => "BadResource", - } - } -} diff --git a/core/lib.rs b/core/lib.rs index 681055af5..276ed19e0 100644 --- a/core/lib.rs +++ b/core/lib.rs @@ -53,6 +53,7 @@ pub use thiserror; pub use url; pub use v8; +pub use deno_js_error::JsError; pub use deno_ops::op2; pub use crate::async_cancel::CancelFuture; diff --git a/core/module_specifier.rs b/core/module_specifier.rs index 652471000..456ec763a 100644 --- a/core/module_specifier.rs +++ b/core/module_specifier.rs @@ -7,7 +7,8 @@ use url::ParseError; use url::Url; /// Error indicating the reason resolving a module specifier failed. -#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error, crate::JsError)] +#[class(URI)] pub enum ModuleResolutionError { #[error("invalid URL: {0}")] InvalidUrl(#[source] ParseError), @@ -25,12 +26,6 @@ pub enum ModuleResolutionError { }, } -impl super::error::JsErrorClass for ModuleResolutionError { - fn get_class(&self) -> &'static str { - crate::error::URI_ERROR - } -} - use ModuleResolutionError::*; /// Resolved module specifier diff --git a/core/modules/loaders.rs b/core/modules/loaders.rs index f5a20b199..0be17cc53 100644 --- a/core/modules/loaders.rs +++ b/core/modules/loaders.rs @@ -1,5 +1,4 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::JsErrorClass; use crate::error::JsNativeError; use crate::module_specifier::ModuleSpecifier; use crate::modules::IntoModuleCodeString; @@ -22,7 +21,8 @@ use std::future::Future; use std::pin::Pin; use std::rc::Rc; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, crate::JsError)] +#[class(GENERIC)] pub enum ModuleLoaderError { #[error("Specifier \"{0}\" was not passed as an extension module and was not included in the snapshot." )] @@ -47,25 +47,20 @@ pub enum ModuleLoaderError { specifier: Box, maybe_referrer: Option>, }, + #[class(inherit)] #[error(transparent)] - Resolution(#[from] crate::ModuleResolutionError), + Resolution( + #[from] + #[inherit] + crate::ModuleResolutionError, + ), + #[class(inherit)] #[error(transparent)] - Core(#[from] CoreError), -} - -impl JsErrorClass for ModuleLoaderError { - fn get_class(&self) -> &'static str { - match self { - ModuleLoaderError::SpecifierExcludedFromSnapshot(_) - | ModuleLoaderError::SpecifierMissingLazyLoadable(_) - | ModuleLoaderError::NpmUnsupportedMetaResolve - | ModuleLoaderError::JsonMissingAttribute - | ModuleLoaderError::NotFound - | ModuleLoaderError::Unsupported { .. } => crate::error::GENERIC_ERROR, - ModuleLoaderError::Resolution(err) => err.get_class(), - ModuleLoaderError::Core(err) => err.get_class(), - } - } + Core( + #[from] + #[inherit] + CoreError, + ), } impl From for ModuleLoaderError { diff --git a/core/modules/mod.rs b/core/modules/mod.rs index 4f7ab027a..6f4ca69a3 100644 --- a/core/modules/mod.rs +++ b/core/modules/mod.rs @@ -626,7 +626,8 @@ pub(crate) struct ModuleInfo { pub module_type: ModuleType, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, crate::JsError)] +#[class(GENERIC)] pub enum ModuleConcreteError { #[error("Trying to create \"main\" module ({new_module:?}), when one already exists ({main_module:?})" )] @@ -642,12 +643,6 @@ pub enum ModuleConcreteError { UnsupportedKind(String), } -impl super::error::JsErrorClass for ModuleConcreteError { - fn get_class(&self) -> &'static str { - crate::error::GENERIC_ERROR - } -} - #[derive(Debug)] pub enum ModuleError { Exception(v8::Global), diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index 798d5eb5a..351bc6e08 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -6,6 +6,7 @@ use crate::OpId; use crate::PromiseId; use serde::ser::SerializeStruct; use serde::Serialize; +use std::borrow::Cow; const MAX_RESULT_SIZE: usize = 32; @@ -310,7 +311,13 @@ impl JsErrorClass for OpErrorWrapper { self.0 .0.get_class() } - fn get_message(&self) -> std::borrow::Cow<'static, str> { + fn get_message(&self) -> Cow<'static, str> { self.0 .0.get_message() } + + fn get_additional_properties( + &self, + ) -> Option, Cow<'static, str>)>> { + self.0 .0.get_additional_properties() + } } diff --git a/js_error/Cargo.toml b/js_error/Cargo.toml new file mode 100644 index 000000000..e17df0f67 --- /dev/null +++ b/js_error/Cargo.toml @@ -0,0 +1,28 @@ +# Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. + +[package] +name = "deno_js_error" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +readme = "README.md" +repository.workspace = true +description = "derive macro for writing Deno Errors" + +[lib] +path = "./lib.rs" +proc-macro = true + +[dependencies] +proc-macro-rules.workspace = true +proc-macro2.workspace = true +quote.workspace = true +strum.workspace = true +strum_macros.workspace = true +syn.workspace = true + +[dev-dependencies] +pretty_assertions.workspace = true +prettyplease.workspace = true +testing_macros.workspace = true diff --git a/js_error/js_error/mod.rs b/js_error/js_error/mod.rs new file mode 100644 index 000000000..1a1046cac --- /dev/null +++ b/js_error/js_error/mod.rs @@ -0,0 +1,326 @@ +use proc_macro2::Ident; +use proc_macro2::TokenStream; +use quote::format_ident; +use quote::quote; +use quote::ToTokens; +use syn::parse::Parse; +use syn::parse::ParseStream; +use syn::parse2; +use syn::spanned::Spanned; +use syn::Data; +use syn::DeriveInput; +use syn::Error; +use syn::Fields; +use syn::LitStr; +use syn::Meta; + +pub(crate) fn js_error(item: TokenStream) -> Result { + let input = parse2::(item)?; + + let (class, get_message, out_properties) = match input.data { + Data::Enum(data) => { + let top_class_attr = input + .attrs + .into_iter() + .find_map(|attr| ClassAttrValue::from_attribute(attr).transpose()) + .transpose()?; + if let Some(top_class_attr) = &top_class_attr { + if matches!(top_class_attr, ClassAttrValue::Inherit(_)) { + return Err(Error::new( + top_class_attr.span(), + "top level class attribute cannot be inherit", + )); + } + } + + let mut get_class = vec![]; + let mut get_message = vec![]; + let mut get_properties = vec![]; + + for variant in data.variants { + let class_attr = variant + .attrs + .into_iter() + .find_map(|attr| ClassAttrValue::from_attribute(attr).transpose()) + .unwrap_or_else(|| { + top_class_attr.clone().ok_or_else(|| { + Error::new(variant.ident.span(), "class attribute is missing") + }) + })?; + + let variant_ident = variant.ident; + + let properties = + properties_to_tokens(get_properties_from_fields(&variant.fields)?); + + let inherit_member = match variant.fields { + Fields::Named(fields_named) => fields_named + .named + .iter() + .find(get_inherit_attr_field) + .map(|field| syn::Member::Named(field.ident.clone().unwrap())), + Fields::Unnamed(fields_unnamed) => fields_unnamed + .unnamed + .iter() + .enumerate() + .find(|(_, field)| get_inherit_attr_field(field)) + .map(|(i, _)| syn::Member::Unnamed(syn::Index::from(i))), + Fields::Unit => None, + }; + + let match_arm = if let Some(member) = &inherit_member { + quote!(Self::#variant_ident { #member: inherit, .. }) + } else { + quote!(Self::#variant_ident { .. }) + }; + + let class = if matches!(class_attr, ClassAttrValue::Inherit(_)) { + if inherit_member.is_some() { + quote!(::deno_core::error::JsErrorClass::get_class(inherit)) + } else { + return Err(Error::new( + class_attr.span(), + "class attribute was set to inherit, but no field was marked as inherit", + )); + } + } else { + quote!(#class_attr) + }; + get_class.push(quote! { + #match_arm => #class, + }); + + let message = if inherit_member.is_some() { + quote!(::deno_core::error::JsErrorClass::get_message(inherit)) + } else { + quote!(self.to_string().into()) + }; + get_message.push(quote! { + #match_arm => #message, + }); + + // TODO: handle adding properties in addition to inherited ones + let properties = if inherit_member.is_some() { + quote!(::deno_core::error::JsErrorClass::get_additional_properties( + inherit + )) + } else { + properties + }; + get_properties.push(quote! { + #match_arm => { + #properties + } + }); + } + + ( + quote! { + match self { + #(#get_class)* + } + }, + quote! { + match self { + #(#get_message)* + } + }, + quote! { + match self { + #(#get_properties)* + } + }, + ) + } + Data::Struct(data) => { + todo!(); + let class = input + .attrs + .into_iter() + .find_map(|attr| ClassAttrValue::from_attribute(attr).transpose()) + .transpose()? + .ok_or_else(|| { + Error::new(input.ident.span(), "class attribute is missing") + })?; + let properties = get_properties_from_fields(&data.fields)?; + + let out_properties = properties_to_tokens(properties); + + (class.into_token_stream(), quote!(""), out_properties) + } + Data::Union(_) => { + return Err(Error::new(input.span(), "Unions are not supported")) + } + }; + + let ident = input.ident; + + Ok(quote! { + #[allow(unused_qualifications)] + impl ::deno_core::error::JsErrorClass for #ident { + fn get_class(&self) -> &'static str { + #class + } + fn get_message(&self) -> ::std::borrow::Cow<'static, str> { + #get_message + } + fn get_additional_properties( + &self + ) -> Option, ::std::borrow::Cow<'static, str>)>> { + #out_properties + } + } + }) +} + +fn get_inherit_attr_field(field: &&syn::Field) -> bool { + field + .attrs + .iter() + .any(|attr| attr.path().is_ident("inherit")) +} + +mod kw { + syn::custom_keyword!(class); + syn::custom_keyword!(property); + syn::custom_keyword!(inherit); +} + +#[derive(Debug, Clone)] +enum ClassAttrValue { + Lit(syn::LitStr), + Ident(Ident), + Inherit(kw::inherit), +} + +impl ClassAttrValue { + fn from_attribute(attr: syn::Attribute) -> Result, Error> { + if attr.path().is_ident("class") { + let list = attr.meta.require_list()?; + let value = list.parse_args::()?; + return Ok(Some(value)); + } + + Ok(None) + } +} + +impl ToTokens for ClassAttrValue { + fn to_tokens(&self, tokens: &mut TokenStream) { + let class_tokens = match self { + ClassAttrValue::Lit(lit) => quote!(#lit), + ClassAttrValue::Ident(ident) => { + let error_name = format_ident!("{}_ERROR", ident); + quote!(::deno_core::error::builtin_classes::#error_name) + } + ClassAttrValue::Inherit(_) => unreachable!(), + }; + + class_tokens.to_tokens(tokens) + } +} + +impl Parse for ClassAttrValue { + fn parse(input: ParseStream) -> syn::Result { + let lookahead = input.lookahead1(); + + if lookahead.peek(syn::LitStr) { + Ok(Self::Lit(input.parse()?)) + } else if lookahead.peek(kw::inherit) { + Ok(Self::Inherit(input.parse()?)) + } else if lookahead.peek(syn::Ident) { + Ok(Self::Ident(input.parse()?)) + } else { + Err(lookahead.error()) + } + } +} + +#[derive(Debug)] +struct ParsedProperty { + ident: syn::Member, + name: String, +} + +fn get_properties_from_fields( + fields: &Fields, +) -> Result, Error> { + const PROPERTY_IDENT: &str = "property"; + let mut out_fields = vec![]; + + match fields { + Fields::Named(named) => { + for field in &named.named { + for attr in &field.attrs { + if attr.path().is_ident(PROPERTY_IDENT) { + let name = match &attr.meta { + Meta::Path(_) => None, + Meta::List(list) => { + return Err(Error::new( + list.delimiter.span().open(), + "expected `=`", + )); + } + Meta::NameValue(meta) => { + Some(parse2::(meta.value.to_token_stream())?.value()) + } + }; + + let ident = field.ident.clone().unwrap(); + let name = name.unwrap_or_else(|| ident.to_string()); + let ident = syn::Member::Named(field.ident.clone().unwrap()); + out_fields.push(ParsedProperty { name, ident }); + + break; + } + } + } + } + Fields::Unnamed(unnamed) => { + for (i, field) in unnamed.unnamed.iter().enumerate() { + for attr in &field.attrs { + if attr.path().is_ident(PROPERTY_IDENT) { + let name_value = attr.meta.require_name_value()?; + let name = + parse2::(name_value.value.to_token_stream())?.value(); + + let ident = syn::Member::Unnamed(syn::Index::from(i)); + out_fields.push(ParsedProperty { name, ident }); + + break; + } + } + } + } + Fields::Unit => {} + } + + Ok(out_fields) +} + +fn properties_to_tokens(properties: Vec) -> TokenStream { + if !properties.is_empty() { + let properties = properties + .into_iter() + .map(|property| { + let ident = property.ident; + let ident_str = property.name; + + quote! { + ( + ::std::borrow::Cow::Borrowed(#ident_str), + ::std::borrow::Cow::Owned(self.#ident.to_string()), + ), + } + }) + .collect::>(); + + quote! { + Some(vec![ + #(#properties),* + ]) + } + } else { + quote!(None) + } +} diff --git a/js_error/lib.rs b/js_error/lib.rs new file mode 100644 index 000000000..f283ef7c4 --- /dev/null +++ b/js_error/lib.rs @@ -0,0 +1,18 @@ +// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +#![deny(clippy::unnecessary_wraps)] + +mod js_error; + +use proc_macro::TokenStream; + +#[proc_macro_derive(JsError, attributes(class, property, inherit))] +pub fn derive_js_error(item: TokenStream) -> TokenStream { + js_error_macro(item) +} + +fn js_error_macro(item: TokenStream) -> TokenStream { + match js_error::js_error(item.into()) { + Ok(output) => output.into(), + Err(err) => err.into_compile_error().into(), + } +} From c353ab07a780db10fd70b4ed386515746fb91477 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sun, 10 Nov 2024 11:39:06 +0100 Subject: [PATCH 34/52] fix --- core/error.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/core/error.rs b/core/error.rs index 9fb0ef589..2e75bf530 100644 --- a/core/error.rs +++ b/core/error.rs @@ -553,6 +553,19 @@ macro_rules! js_error_wrapper { let $inner = &self.0; $js_err_type } + fn get_message(&self) -> std::borrow::Cow<'static, str> { + self.to_string().into() + } + fn get_additional_properties( + &self, + ) -> Option< + Vec<( + std::borrow::Cow<'static, str>, + std::borrow::Cow<'static, str>, + )>, + > { + None + } } }; } From 0529b83af68347a85c054382490b31f8c92525e6 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Tue, 19 Nov 2024 03:19:24 +0100 Subject: [PATCH 35/52] fix --- Cargo.lock | 74 +++-- Cargo.toml | 6 +- core/Cargo.toml | 2 +- core/error.rs | 326 +++------------------ core/error_codes.rs | 213 -------------- core/io/resource.rs | 8 +- core/io/resource_table.rs | 4 +- core/lib.rs | 3 +- core/module_specifier.rs | 6 +- core/modules/loaders.rs | 4 +- core/modules/map.rs | 13 +- core/modules/mod.rs | 4 +- core/ops_builtin_v8.rs | 7 +- core/runtime/bindings.rs | 36 ++- core/runtime/op_driver/op_results.rs | 21 +- core/runtime/ops.rs | 7 +- core/runtime/tests/ops.rs | 12 +- js_error/Cargo.toml | 28 -- js_error/js_error/mod.rs | 326 --------------------- js_error/lib.rs | 18 -- serde_v8/Cargo.toml | 1 + serde_v8/error.rs | 3 +- testing/Cargo.toml | 1 + testing/checkin/runner/ts_module_loader.rs | 4 +- 24 files changed, 172 insertions(+), 955 deletions(-) delete mode 100644 core/error_codes.rs delete mode 100644 js_error/Cargo.toml delete mode 100644 js_error/js_error/mod.rs delete mode 100644 js_error/lib.rs diff --git a/Cargo.lock b/Cargo.lock index ff88cf7d2..6690af800 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -552,7 +552,7 @@ dependencies = [ "swc_visit", "swc_visit_macros", "text_lines", - "thiserror", + "thiserror 1.0.60", "unicode-width", "url", ] @@ -571,7 +571,7 @@ dependencies = [ "criterion", "deno_ast", "deno_core_icudata", - "deno_js_error", + "deno_error", "deno_ops", "deno_unsync", "fastrand", @@ -589,7 +589,7 @@ dependencies = [ "smallvec", "sourcemap", "static_assertions", - "thiserror", + "thiserror 1.0.60", "tokio", "twox-hash", "unicycle", @@ -610,6 +610,7 @@ dependencies = [ "anyhow", "deno_ast", "deno_core", + "deno_error", "futures", "pretty_assertions", "prettyplease", @@ -619,18 +620,28 @@ dependencies = [ ] [[package]] -name = "deno_js_error" -version = "0.1.0" +name = "deno_error" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7212b2c7eab654fa8856f7d0c5ad6c805f9e32982079735ca3a0fee1381e101" +dependencies = [ + "deno_error_macro", + "libc", + "serde", + "serde_json", + "tokio", + "url", +] + +[[package]] +name = "deno_error_macro" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23a3cd1a50eed6696671493663fa1d2542a487350527b133ef8db0765bc83334" dependencies = [ - "pretty_assertions", - "prettyplease", - "proc-macro-rules", "proc-macro2", "quote", - "strum", - "strum_macros", "syn", - "testing_macros", ] [[package]] @@ -657,7 +668,7 @@ dependencies = [ "strum_macros", "syn", "testing_macros", - "thiserror", + "thiserror 2.0.3", ] [[package]] @@ -769,7 +780,7 @@ dependencies = [ "rand", "sha1", "simdutf8", - "thiserror", + "thiserror 1.0.60", "tokio", "utf-8", ] @@ -1194,9 +1205,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.154" +version = "0.2.162" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" +checksum = "18d287de67fe55fd7e1581fe933d965a5a9477b38e949cfa9f8574ef01506398" [[package]] name = "libloading" @@ -1548,9 +1559,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.82" +version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ad3d49ab951a01fbaafe34f2ec74122942fe18a3f9814c3268f1bb72042131b" +checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" dependencies = [ "unicode-ident", ] @@ -1860,13 +1871,14 @@ name = "serde_v8" version = "0.228.0" dependencies = [ "bencher", + "deno_error", "num-bigint", "serde", "serde_bytes", "serde_json", "serde_v8_utilities", "smallvec", - "thiserror", + "thiserror 2.0.3", "v8", ] @@ -2397,9 +2409,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.61" +version = "2.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c993ed8ccba56ae856363b1845da7266a7cb78e1d146c8a32d54b45a8b831fc9" +checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" dependencies = [ "proc-macro2", "quote", @@ -2452,7 +2464,16 @@ version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "579e9083ca58dd9dcf91a9923bb9054071b9ebbd800b342194c9feb0ee89fc18" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.60", +] + +[[package]] +name = "thiserror" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c006c85c7651b3cf2ada4584faa36773bd07bac24acfb39f3c431b36d7e667aa" +dependencies = [ + "thiserror-impl 2.0.3", ] [[package]] @@ -2466,6 +2487,17 @@ dependencies = [ "syn", ] +[[package]] +name = "thiserror-impl" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "tinytemplate" version = "1.2.1" diff --git a/Cargo.toml b/Cargo.toml index fdcb5ba65..bc67b3e65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,6 @@ members = [ "core/examples/snapshot", "dcore", "ops", - "js_error", "ops/compile_test_runner", "serde_v8", "testing", @@ -23,7 +22,7 @@ repository = "https://github.com/denoland/deno_core" # Local dependencies deno_core = { version = "0.319.0", path = "./core" } deno_ops = { version = "0.195.0", path = "./ops" } -deno_js_error = { version = "0.1.0", path = "./js_error" } +deno_error_macro = { version = "0.1.0", path = "./error/js_error" } serde_v8 = { version = "0.228.0", path = "./serde_v8" } deno_core_testing = { path = "./testing" } @@ -31,6 +30,7 @@ v8 = { version = "130.0.1", default-features = false } deno_ast = { version = "=0.40.0", features = ["transpiling"] } deno_unsync = "0.4.1" deno_core_icudata = "0.74.0" +deno_error = { version = "0.4.0", features = ["serde_json", "serde", "url", "tokio"] } anyhow = "1" bencher = "0.1" @@ -61,7 +61,7 @@ static_assertions = "1" strum = { version = "0.25.0", features = ["derive"] } strum_macros = "0.25.0" testing_macros = "0.2.11" -thiserror = "1" +thiserror = "2" tokio = { version = "1", features = ["full"] } twox-hash = { version = "2.0.0", default-features = false, features = ["xxhash64"] } url = { version = "2", features = ["serde", "expose_internals"] } diff --git a/core/Cargo.toml b/core/Cargo.toml index 2d6088f56..d21746830 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -48,7 +48,7 @@ tokio.workspace = true url.workspace = true v8.workspace = true thiserror = "1.0.60" -deno_js_error.workspace = true +deno_error.workspace = true [dev-dependencies] bencher.workspace = true diff --git a/core/error.rs b/core/error.rs index 2e75bf530..b5e31fce5 100644 --- a/core/error.rs +++ b/core/error.rs @@ -1,5 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +pub use super::modules::ModuleConcreteError; pub use super::runtime::op_driver::OpError; pub use super::runtime::op_driver::OpErrorWrapper; pub use crate::io::ResourceError; @@ -10,6 +11,7 @@ use crate::runtime::JsRuntime; use crate::source_map::SourceMapApplication; use crate::url::Url; use crate::FastStaticString; +use deno_error::builtin_classes::*; use std::borrow::Cow; use std::collections::HashSet; use std::error::Error; @@ -19,24 +21,15 @@ use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write as _; -pub use super::modules::ModuleConcreteError; +pub use deno_error; +pub use deno_error::JsError; +pub use deno_error::JsErrorClass; /// A generic wrapper that can encapsulate any concrete error type. // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. pub type AnyError = anyhow::Error; -pub mod builtin_classes { - pub const GENERIC_ERROR: &str = "Error"; - pub const RANGE_ERROR: &str = "RangeError"; - pub const TYPE_ERROR: &str = "TypeError"; - pub const SYNTAX_ERROR: &str = "SyntaxError"; - pub const URI_ERROR: &str = "URIError"; - pub const REFERENCE_ERROR: &str = "ReferenceError"; - - pub const NOT_SUPPORTED_ERROR: &str = "NotSupported"; -} - -pub use builtin_classes::*; +deno_error::js_error_wrapper!(v8::DataError, DataError, TYPE_ERROR); #[derive(Debug, thiserror::Error)] pub enum CoreError { @@ -91,7 +84,7 @@ pub enum CoreError { #[error(transparent)] Module(ModuleConcreteError), #[error(transparent)] - DataError(#[from] v8::DataError), + DataError(DataError), #[error(transparent)] Other(#[from] anyhow::Error), } @@ -148,50 +141,15 @@ impl CoreError { } } -impl From for CoreError { - fn from(err: ModuleLoaderError) -> Self { - CoreError::ModuleLoader(Box::new(err)) +impl From for CoreError { + fn from(err: v8::DataError) -> Self { + CoreError::DataError(DataError(err)) } } -/// Trait to implement how an error should be represented in JavaScript. -/// Note: it is not recommended to manually implement this type, but instead -/// rather use the [deno_core::JsError] macro. -pub trait JsErrorClass: Display + Debug + Send + Sync + 'static { - fn get_class(&self) -> &'static str; - fn get_message(&self) -> Cow<'static, str>; - fn get_additional_properties( - &self, - ) -> Option, Cow<'static, str>)>>; - fn to_native(self) -> JsNativeError - where - Self: Sized, - { - JsNativeError::from_err(self) - } - - fn throw(&self, scope: &mut v8::HandleScope) { - let exception = js_class_and_message_to_exception( - scope, - self.get_class(), - &self.get_message(), - ); - scope.throw_exception(exception); - } -} - -fn js_class_and_message_to_exception<'s>( - scope: &mut v8::HandleScope<'s>, - class: &str, - message: &str, -) -> v8::Local<'s, v8::Value> { - let message = v8::String::new(scope, message).unwrap(); - match class { - TYPE_ERROR => v8::Exception::type_error(scope, message), - RANGE_ERROR => v8::Exception::range_error(scope, message), - REFERENCE_ERROR => v8::Exception::reference_error(scope, message), - SYNTAX_ERROR => v8::Exception::syntax_error(scope, message), - _ => v8::Exception::error(scope, message), +impl From for CoreError { + fn from(err: ModuleLoaderError) -> Self { + CoreError::ModuleLoader(Box::new(err)) } } @@ -257,195 +215,30 @@ impl JsErrorClass for CoreError { } } -impl JsErrorClass for serde_v8::Error { - fn get_class(&self) -> &'static str { - TYPE_ERROR - } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } - - fn get_additional_properties( - &self, - ) -> Option, Cow<'static, str>)>> { - None - } -} - -impl JsErrorClass for std::io::Error { - fn get_class(&self) -> &'static str { - use std::io::ErrorKind::*; - - match self.kind() { - NotFound => "NotFound", - PermissionDenied => "PermissionDenied", - ConnectionRefused => "ConnectionRefused", - ConnectionReset => "ConnectionReset", - ConnectionAborted => "ConnectionAborted", - NotConnected => "NotConnected", - AddrInUse => "AddrInUse", - AddrNotAvailable => "AddrNotAvailable", - BrokenPipe => "BrokenPipe", - AlreadyExists => "AlreadyExists", - InvalidInput => TYPE_ERROR, - InvalidData => "InvalidData", - TimedOut => "TimedOut", - Interrupted => "Interrupted", - WriteZero => "WriteZero", - UnexpectedEof => "UnexpectedEof", - Other => GENERIC_ERROR, - WouldBlock => "WouldBlock", - kind => { - let kind_str = kind.to_string(); - match kind_str.as_str() { - "FilesystemLoop" => "FilesystemLoop", - "IsADirectory" => "IsADirectory", - "NetworkUnreachable" => "NetworkUnreachable", - "NotADirectory" => "NotADirectory", - _ => GENERIC_ERROR, - } - } - } - } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } - - fn get_additional_properties( - &self, - ) -> Option, Cow<'static, str>)>> { - crate::error_codes::get_error_code(self) - .map(|code| vec![("code".into(), code.into())]) - } -} - -impl JsErrorClass for std::env::VarError { - fn get_class(&self) -> &'static str { - match self { - std::env::VarError::NotPresent => "NotFound", - std::env::VarError::NotUnicode(..) => "InvalidData", - } - } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } - - fn get_additional_properties( - &self, - ) -> Option, Cow<'static, str>)>> { - None - } -} - -impl JsErrorClass for std::sync::mpsc::RecvError { - fn get_class(&self) -> &'static str { - GENERIC_ERROR - } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } - - fn get_additional_properties( - &self, - ) -> Option, Cow<'static, str>)>> { - None - } -} - -impl JsErrorClass for v8::DataError { - fn get_class(&self) -> &'static str { - TYPE_ERROR - } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } - - fn get_additional_properties( - &self, - ) -> Option, Cow<'static, str>)>> { - None - } -} - -impl JsErrorClass - for tokio::sync::mpsc::error::SendError -{ - fn get_class(&self) -> &'static str { - GENERIC_ERROR - } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } - - fn get_additional_properties( - &self, - ) -> Option, Cow<'static, str>)>> { - None - } -} -impl JsErrorClass for tokio::task::JoinError { - fn get_class(&self) -> &'static str { - GENERIC_ERROR - } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } - - fn get_additional_properties( - &self, - ) -> Option, Cow<'static, str>)>> { - None - } -} - -impl JsErrorClass for serde_json::Error { - fn get_class(&self) -> &'static str { - use serde::de::StdError; - use serde_json::error::*; - - match self.classify() { - Category::Io => self - .source() - .and_then(|e| e.downcast_ref::()) - .unwrap() - .get_class(), - Category::Syntax => SYNTAX_ERROR, - Category::Data => "InvalidData", - Category::Eof => "UnexpectedEof", - } - } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } - - fn get_additional_properties( - &self, - ) -> Option, Cow<'static, str>)>> { - None // TODO: could be io error code - } +pub fn throw_js_error_class( + scope: &mut v8::HandleScope, + error: &E, +) { + let exception = js_class_and_message_to_exception( + scope, + error.get_class(), + &error.get_message(), + ); + scope.throw_exception(exception); } -impl JsErrorClass for url::ParseError { - fn get_class(&self) -> &'static str { - URI_ERROR - } - - fn get_message(&self) -> Cow<'static, str> { - self.to_string().into() - } - - fn get_additional_properties( - &self, - ) -> Option, Cow<'static, str>)>> { - None +fn js_class_and_message_to_exception<'s>( + scope: &mut v8::HandleScope<'s>, + class: &str, + message: &str, +) -> v8::Local<'s, v8::Value> { + let message = v8::String::new(scope, message).unwrap(); + match class { + TYPE_ERROR => v8::Exception::type_error(scope, message), + RANGE_ERROR => v8::Exception::range_error(scope, message), + REFERENCE_ERROR => v8::Exception::reference_error(scope, message), + SYNTAX_ERROR => v8::Exception::syntax_error(scope, message), + _ => v8::Exception::error(scope, message), } } @@ -525,49 +318,10 @@ impl JsNativeError { } } -#[macro_export] -macro_rules! js_error_wrapper { - ($err_path:path, $err_name:ident, $js_err_type:tt) => { - deno_core::js_error_wrapper!($err_path, $err_name, |_error| $js_err_type); - }; - ($err_path:path, $err_name:ident, |$inner:ident| $js_err_type:tt) => { - #[derive(Debug)] - pub struct $err_name(pub $err_path); - impl From<$err_path> for $err_name { - fn from(err: $err_path) -> Self { - Self(err) - } - } - impl std::error::Error for $err_name { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - self.0.source() - } - } - impl std::fmt::Display for $err_name { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.0.fmt(f) - } - } - impl deno_core::error::JsErrorClass for $err_name { - fn get_class(&self) -> &'static str { - let $inner = &self.0; - $js_err_type - } - fn get_message(&self) -> std::borrow::Cow<'static, str> { - self.to_string().into() - } - fn get_additional_properties( - &self, - ) -> Option< - Vec<( - std::borrow::Cow<'static, str>, - std::borrow::Cow<'static, str>, - )>, - > { - None - } - } - }; +impl From for JsNativeError { + fn from(value: crate::Canceled) -> Self { + Self::from_err(value) + } } /// A wrapper around `anyhow::Error` that implements `std::error::Error` @@ -615,7 +369,7 @@ pub fn to_v8_error<'a>( if let Some(code) = (error as &dyn std::any::Any) .downcast_ref::() - .and_then(crate::error_codes::get_error_code) + .and_then(deno_error::get_error_code) { args.push(v8::String::new(tc_scope, code).unwrap().into()); } diff --git a/core/error_codes.rs b/core/error_codes.rs deleted file mode 100644 index 09277a608..000000000 --- a/core/error_codes.rs +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. - -pub fn get_error_code(err: &std::io::Error) -> Option<&'static str> { - let code = match err.raw_os_error() { - Some(code) => get_os_error_code(code), - None => get_io_error_code(err), - }; - - match code.is_empty() { - true => None, - false => Some(code), - } -} - -fn get_io_error_code(err: &std::io::Error) -> &'static str { - // not exhaustive but simple and possibly sufficient once `io_error_more` is stabilized (https://github.com/rust-lang/rust/issues/86442) - // inversion of https://github.com/rust-lang/rust/blob/dca3f1b786efd27be3b325ed1e01e247aa589c3b/library/std/src/sys/unix/mod.rs#L138-L185 - // TODO(@AaronO): revisit as `io_error_more` lands in rust stable - use std::io::ErrorKind; - match err.kind() { - // ErrorKind::ArgumentListTooLong => "E2BIG", - ErrorKind::AddrInUse => "EADDRINUSE", - ErrorKind::AddrNotAvailable => "EADDRNOTAVAIL", - // ErrorKind::ResourceBusy => "EBUSY", - ErrorKind::ConnectionAborted => "ECONNABORTED", - ErrorKind::ConnectionRefused => "ECONNREFUSED", - ErrorKind::ConnectionReset => "ECONNRESET", - // ErrorKind::Deadlock => "EDEADLK", - // ErrorKind::FilesystemQuotaExceeded => "EDQUOT", - ErrorKind::AlreadyExists => "EEXIST", - // ErrorKind::FileTooLarge => "EFBIG", - // ErrorKind::HostUnreachable => "EHOSTUNREACH", - ErrorKind::Interrupted => "EINTR", - ErrorKind::InvalidInput => "EINVAL", - // ErrorKind::IsADirectory => "EISDIR", - // ErrorKind::FilesystemLoop => "ELOOP", - ErrorKind::NotFound => "ENOENT", - ErrorKind::OutOfMemory => "ENOMEM", - // ErrorKind::StorageFull => "ENOSPC", - ErrorKind::Unsupported => "ENOSYS", - // ErrorKind::TooManyLinks => "EMLINK", - // ErrorKind::FilenameTooLong => "ENAMETOOLONG", - // ErrorKind::NetworkDown => "ENETDOWN", - // ErrorKind::NetworkUnreachable => "ENETUNREACH", - ErrorKind::NotConnected => "ENOTCONN", - // ErrorKind::NotADirectory => "ENOTDIR", - // ErrorKind::DirectoryNotEmpty => "ENOTEMPTY", - ErrorKind::BrokenPipe => "EPIPE", - // ErrorKind::ReadOnlyFilesystem => "EROFS", - // ErrorKind::NotSeekable => "ESPIPE", - // ErrorKind::StaleNetworkFileHandle => "ESTALE", - ErrorKind::TimedOut => "ETIMEDOUT", - // ErrorKind::ExecutableFileBusy => "ETXTBSY", - // ErrorKind::CrossesDevices => "EXDEV", - ErrorKind::PermissionDenied => "EACCES", // NOTE: Collides with EPERM ... - ErrorKind::WouldBlock => "EWOULDBLOCK", // NOTE: Collides with EAGAIN ... - _ => "", - } -} - -/// Maps OS errno codes to string names -/// derived from libuv: https://github.com/libuv/libuv/blob/26b2e5dbb6301756644d6e4cf6ca9c49c00513d3/include/uv/errno.h -/// generated with tools/codegen_error_codes.js -#[cfg(unix)] -fn get_os_error_code(errno: i32) -> &'static str { - match errno { - libc::E2BIG => "E2BIG", - libc::EACCES => "EACCES", - libc::EADDRINUSE => "EADDRINUSE", - libc::EADDRNOTAVAIL => "EADDRNOTAVAIL", - libc::EAFNOSUPPORT => "EAFNOSUPPORT", - libc::EAGAIN => "EAGAIN", - libc::EALREADY => "EALREADY", - libc::EBADF => "EBADF", - libc::EBUSY => "EBUSY", - libc::ECANCELED => "ECANCELED", - libc::ECONNABORTED => "ECONNABORTED", - libc::ECONNREFUSED => "ECONNREFUSED", - libc::ECONNRESET => "ECONNRESET", - libc::EEXIST => "EEXIST", - libc::EFAULT => "EFAULT", - libc::EHOSTUNREACH => "EHOSTUNREACH", - libc::EINVAL => "EINVAL", - libc::EIO => "EIO", - libc::EISCONN => "EISCONN", - libc::EISDIR => "EISDIR", - libc::ELOOP => "ELOOP", - libc::EMFILE => "EMFILE", - libc::EMSGSIZE => "EMSGSIZE", - libc::ENAMETOOLONG => "ENAMETOOLONG", - libc::ENETUNREACH => "ENETUNREACH", - libc::ENOBUFS => "ENOBUFS", - libc::ENOENT => "ENOENT", - libc::ENOMEM => "ENOMEM", - libc::ENOSPC => "ENOSPC", - libc::ENOTCONN => "ENOTCONN", - libc::ENOTDIR => "ENOTDIR", - libc::ENOTEMPTY => "ENOTEMPTY", - libc::ENOTSOCK => "ENOTSOCK", - libc::ENOTSUP => "ENOTSUP", - libc::EPERM => "EPERM", - libc::EPIPE => "EPIPE", - libc::EPROTONOSUPPORT => "EPROTONOSUPPORT", - libc::EROFS => "EROFS", - libc::ETIMEDOUT => "ETIMEDOUT", - libc::EXDEV => "EXDEV", - libc::ESOCKTNOSUPPORT => "ESOCKTNOSUPPORT", - _ => "", - } -} - -#[cfg(windows)] -fn get_os_error_code(errno: i32) -> &'static str { - match errno { - 998 => "EACCES", // ERROR_NOACCESS - 10013 => "EACCES", // WSAEACCES - 1920 => "EACCES", // ERROR_CANT_ACCESS_FILE - 1227 => "EADDRINUSE", // ERROR_ADDRESS_ALREADY_ASSOCIATED - 10048 => "EADDRINUSE", // WSAEADDRINUSE - 10049 => "EADDRNOTAVAIL", // WSAEADDRNOTAVAIL - 10047 => "EAFNOSUPPORT", // WSAEAFNOSUPPORT - 10035 => "EAGAIN", // WSAEWOULDBLOCK - 10037 => "EALREADY", // WSAEALREADY - 1004 => "EBADF", // ERROR_INVALID_FLAGS - 6 => "EBADF", // ERROR_INVALID_HANDLE - 33 => "EBUSY", // ERROR_LOCK_VIOLATION - 231 => "EBUSY", // ERROR_PIPE_BUSY - 32 => "EBUSY", // ERROR_SHARING_VIOLATION - 995 => "ECANCELED", // ERROR_OPERATION_ABORTED - 10004 => "ECANCELED", // WSAEINTR - 1236 => "ECONNABORTED", // ERROR_CONNECTION_ABORTED - 10053 => "ECONNABORTED", // WSAECONNABORTED - 1225 => "ECONNREFUSED", // ERROR_CONNECTION_REFUSED - 10061 => "ECONNREFUSED", // WSAECONNREFUSED - 64 => "ECONNRESET", // ERROR_NETNAME_DELETED - 10054 => "ECONNRESET", // WSAECONNRESET - 183 => "EEXIST", // ERROR_ALREADY_EXISTS - 80 => "EEXIST", // ERROR_FILE_EXISTS - 111 => "EFAULT", // ERROR_BUFFER_OVERFLOW - 10014 => "EFAULT", // WSAEFAULT - 1232 => "EHOSTUNREACH", // ERROR_HOST_UNREACHABLE - 10065 => "EHOSTUNREACH", // WSAEHOSTUNREACH - 122 => "EINVAL", // ERROR_INSUFFICIENT_BUFFER - 13 => "EINVAL", // ERROR_INVALID_DATA - 87 => "EINVAL", // ERROR_INVALID_PARAMETER - 1464 => "EINVAL", // ERROR_SYMLINK_NOT_SUPPORTED - 10022 => "EINVAL", // WSAEINVAL - 10046 => "EINVAL", // WSAEPFNOSUPPORT - 1102 => "EIO", // ERROR_BEGINNING_OF_MEDIA - 1111 => "EIO", // ERROR_BUS_RESET - 23 => "EIO", // ERROR_CRC - 1166 => "EIO", // ERROR_DEVICE_DOOR_OPEN - 1165 => "EIO", // ERROR_DEVICE_REQUIRES_CLEANING - 1393 => "EIO", // ERROR_DISK_CORRUPT - 1129 => "EIO", // ERROR_EOM_OVERFLOW - 1101 => "EIO", // ERROR_FILEMARK_DETECTED - 31 => "EIO", // ERROR_GEN_FAILURE - 1106 => "EIO", // ERROR_INVALID_BLOCK_LENGTH - 1117 => "EIO", // ERROR_IO_DEVICE - 1104 => "EIO", // ERROR_NO_DATA_DETECTED - 205 => "EIO", // ERROR_NO_SIGNAL_SENT - 110 => "EIO", // ERROR_OPEN_FAILED - 1103 => "EIO", // ERROR_SETMARK_DETECTED - 156 => "EIO", // ERROR_SIGNAL_REFUSED - 10056 => "EISCONN", // WSAEISCONN - 1921 => "ELOOP", // ERROR_CANT_RESOLVE_FILENAME - 4 => "EMFILE", // ERROR_TOO_MANY_OPEN_FILES - 10024 => "EMFILE", // WSAEMFILE - 10040 => "EMSGSIZE", // WSAEMSGSIZE - 206 => "ENAMETOOLONG", // ERROR_FILENAME_EXCED_RANGE - 1231 => "ENETUNREACH", // ERROR_NETWORK_UNREACHABLE - 10051 => "ENETUNREACH", // WSAENETUNREACH - 10055 => "ENOBUFS", // WSAENOBUFS - 161 => "ENOENT", // ERROR_BAD_PATHNAME - 267 => "ENOENT", // ERROR_DIRECTORY - 203 => "ENOENT", // ERROR_ENVVAR_NOT_FOUND - 2 => "ENOENT", // ERROR_FILE_NOT_FOUND - 123 => "ENOENT", // ERROR_INVALID_NAME - 15 => "ENOENT", // ERROR_INVALID_DRIVE - 4392 => "ENOENT", // ERROR_INVALID_REPARSE_DATA - 126 => "ENOENT", // ERROR_MOD_NOT_FOUND - 3 => "ENOENT", // ERROR_PATH_NOT_FOUND - 11001 => "ENOENT", // WSAHOST_NOT_FOUND - 11004 => "ENOENT", // WSANO_DATA - 8 => "ENOMEM", // ERROR_NOT_ENOUGH_MEMORY - 14 => "ENOMEM", // ERROR_OUTOFMEMORY - 82 => "ENOSPC", // ERROR_CANNOT_MAKE - 112 => "ENOSPC", // ERROR_DISK_FULL - 277 => "ENOSPC", // ERROR_EA_TABLE_FULL - 1100 => "ENOSPC", // ERROR_END_OF_MEDIA - 39 => "ENOSPC", // ERROR_HANDLE_DISK_FULL - 2250 => "ENOTCONN", // ERROR_NOT_CONNECTED - 10057 => "ENOTCONN", // WSAENOTCONN - 145 => "ENOTEMPTY", // ERROR_DIR_NOT_EMPTY - 10038 => "ENOTSOCK", // WSAENOTSOCK - 50 => "ENOTSUP", // ERROR_NOT_SUPPORTED - 5 => "EPERM", // ERROR_ACCESS_DENIED - 1314 => "EPERM", // ERROR_PRIVILEGE_NOT_HELD - 230 => "EPIPE", // ERROR_BAD_PIPE - 232 => "EPIPE", // ERROR_NO_DATA - 233 => "EPIPE", // ERROR_PIPE_NOT_CONNECTED - 10058 => "EPIPE", // WSAESHUTDOWN - 10043 => "EPROTONOSUPPORT", // WSAEPROTONOSUPPORT - 19 => "EROFS", // ERROR_WRITE_PROTECT - 121 => "ETIMEDOUT", // ERROR_SEM_TIMEOUT - 10060 => "ETIMEDOUT", // WSAETIMEDOUT - 17 => "EXDEV", // ERROR_NOT_SAME_DEVICE - 1 => "EISDIR", // ERROR_INVALID_FUNCTION - 208 => "E2BIG", // ERROR_META_EXPANSION_TOO_LONG - 10044 => "ESOCKTNOSUPPORT", // WSAESOCKTNOSUPPORT - _ => "", - } -} diff --git a/core/io/resource.rs b/core/io/resource.rs index e5d99d420..4f59dd485 100644 --- a/core/io/resource.rs +++ b/core/io/resource.rs @@ -231,7 +231,7 @@ macro_rules! impl_readable_byob { ) -> AsyncResult<$crate::BufView> { ::std::boxed::Box::pin(async move { let mut vec = ::std::vec![0; limit]; - let nread = self.read(&mut vec).await?; + let nread = self.read(&mut vec).await.map_err(::deno_core::error::JsNativeError::from_err)?; if nread != vec.len() { vec.truncate(nread); } @@ -245,7 +245,7 @@ macro_rules! impl_readable_byob { mut buf: $crate::BufMutView, ) -> AsyncResult<(::core::primitive::usize, $crate::BufMutView)> { ::std::boxed::Box::pin(async move { - let nread = self.read(buf.as_mut()).await?; + let nread = self.read(buf.as_mut()).await.map_err(::deno_core::error::JsNativeError::from_err)?; ::std::result::Result::Ok((nread, buf)) }) } @@ -260,7 +260,7 @@ macro_rules! impl_writable { view: $crate::BufView, ) -> $crate::AsyncResult<$crate::WriteOutcome> { ::std::boxed::Box::pin(async move { - let nwritten = self.write(&view).await?; + let nwritten = self.write(&view).await.map_err(::deno_core::error::JsNativeError::from_err)?; ::std::result::Result::Ok($crate::WriteOutcome::Partial { nwritten, view, @@ -274,7 +274,7 @@ macro_rules! impl_writable { view: $crate::BufView, ) -> $crate::AsyncResult<()> { ::std::boxed::Box::pin(async move { - self.write_all(&view).await?; + self.write_all(&view).await.map_err(::deno_core::error::JsNativeError::from_err)?; ::std::result::Result::Ok(()) }) } diff --git a/core/io/resource_table.rs b/core/io/resource_table.rs index 7790e4735..bc4ccae3c 100644 --- a/core/io/resource_table.rs +++ b/core/io/resource_table.rs @@ -230,9 +230,9 @@ impl ResourceTable { } } -#[derive(Debug, thiserror::Error, crate::JsError)] +#[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum ResourceError { - #[class(REFERENCE)] + #[class(reference)] #[error("null or invalid handle")] Reference, #[class("BadResource")] diff --git a/core/lib.rs b/core/lib.rs index d70053492..d466500ec 100644 --- a/core/lib.rs +++ b/core/lib.rs @@ -11,7 +11,6 @@ mod async_cell; pub mod convert; pub mod cppgc; pub mod error; -mod error_codes; mod extension_set; mod extensions; mod external; @@ -53,7 +52,7 @@ pub use thiserror; pub use url; pub use v8; -pub use deno_js_error::JsError; +pub use deno_error::JsError; pub use deno_ops::op2; pub use crate::async_cancel::CancelFuture; diff --git a/core/module_specifier.rs b/core/module_specifier.rs index 456ec763a..416b01e4b 100644 --- a/core/module_specifier.rs +++ b/core/module_specifier.rs @@ -7,8 +7,10 @@ use url::ParseError; use url::Url; /// Error indicating the reason resolving a module specifier failed. -#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error, crate::JsError)] -#[class(URI)] +#[derive( + Clone, Debug, Eq, PartialEq, thiserror::Error, deno_error::JsError, +)] +#[class(uri)] pub enum ModuleResolutionError { #[error("invalid URL: {0}")] InvalidUrl(#[source] ParseError), diff --git a/core/modules/loaders.rs b/core/modules/loaders.rs index 0be17cc53..1e01ee2ed 100644 --- a/core/modules/loaders.rs +++ b/core/modules/loaders.rs @@ -21,8 +21,8 @@ use std::future::Future; use std::pin::Pin; use std::rc::Rc; -#[derive(Debug, thiserror::Error, crate::JsError)] -#[class(GENERIC)] +#[derive(Debug, thiserror::Error, deno_error::JsError)] +#[class(generic)] pub enum ModuleLoaderError { #[error("Specifier \"{0}\" was not passed as an extension module and was not included in the snapshot." )] diff --git a/core/modules/map.rs b/core/modules/map.rs index eacb309db..3eedc92b5 100644 --- a/core/modules/map.rs +++ b/core/modules/map.rs @@ -6,7 +6,6 @@ use super::ModuleConcreteError; use crate::ascii_str; use crate::error::exception_to_err_result; use crate::error::JsError; -use crate::error::JsErrorClass; use crate::error::JsNativeError; use crate::modules::get_requested_module_type_from_attributes; use crate::modules::parse_import_attributes; @@ -836,10 +835,12 @@ impl ModuleMap { return Some(module); } - JsNativeError::type_error(format!( - r#"Cannot resolve module "{specifier_str}" from "{referrer_name}""# - )) - .throw(scope); + crate::error::throw_js_error_class( + scope, + &JsNativeError::type_error(format!( + r#"Cannot resolve module "{specifier_str}" from "{referrer_name}""# + )), + ); None } @@ -887,7 +888,7 @@ impl ModuleMap { match self.resolve(specifier, referrer, ResolutionKind::Import) { Ok(s) => s, Err(e) => { - e.throw(scope); + crate::error::throw_js_error_class(scope, &e); return None; } }; diff --git a/core/modules/mod.rs b/core/modules/mod.rs index 6f4ca69a3..18ce8f316 100644 --- a/core/modules/mod.rs +++ b/core/modules/mod.rs @@ -626,8 +626,8 @@ pub(crate) struct ModuleInfo { pub module_type: ModuleType, } -#[derive(Debug, thiserror::Error, crate::JsError)] -#[class(GENERIC)] +#[derive(Debug, thiserror::Error, deno_error::JsError)] +#[class(generic)] pub enum ModuleConcreteError { #[error("Trying to create \"main\" module ({new_module:?}), when one already exists ({main_module:?})" )] diff --git a/core/ops_builtin_v8.rs b/core/ops_builtin_v8.rs index 18cabfa6d..3c65098cd 100644 --- a/core/ops_builtin_v8.rs +++ b/core/ops_builtin_v8.rs @@ -276,7 +276,9 @@ pub fn op_eval_context<'a>( let output = v8::PrimitiveArray::new(tc_scope, array.length() as _); for i in 0..array.length() { let value = array.get_index(tc_scope, i).unwrap(); - let value = value.try_cast::()?; + let value = value + .try_cast::() + .map_err(crate::error::DataError)?; output.set(tc_scope, i as _, value); } Some(output.into()) @@ -807,7 +809,8 @@ pub fn op_set_promise_hooks( .enumerate() .filter(|(_, hook)| !hook.is_undefined()) .try_fold([None; 4], |mut v8_fns, (i, hook)| { - let v8_fn = v8::Local::::try_from(hook)?; + let v8_fn = v8::Local::::try_from(hook) + .map_err(crate::error::DataError)?; v8_fns[i] = Some(v8_fn); Ok::<_, OpError>(v8_fns) })?; diff --git a/core/runtime/bindings.rs b/core/runtime/bindings.rs index 053937204..329041509 100644 --- a/core/runtime/bindings.rs +++ b/core/runtime/bindings.rs @@ -13,7 +13,6 @@ use crate::error::callsite_fns; use crate::error::has_call_site; use crate::error::is_instance_of_error; use crate::error::CoreError; -use crate::error::JsErrorClass; use crate::error::JsNativeError; use crate::error::JsStackFrame; use crate::extension_set::LoadedSources; @@ -607,12 +606,18 @@ fn import_meta_resolve( mut rv: v8::ReturnValue, ) { if args.length() > 1 { - return JsNativeError::type_error("Invalid arguments").throw(scope); + return crate::error::throw_js_error_class( + scope, + &JsNativeError::type_error("Invalid arguments"), + ); } let maybe_arg_str = args.get(0).to_string(scope); if maybe_arg_str.is_none() { - return JsNativeError::type_error("Invalid arguments").throw(scope); + return crate::error::throw_js_error_class( + scope, + &JsNativeError::type_error("Invalid arguments"), + ); } let specifier = maybe_arg_str.unwrap(); let referrer = { @@ -635,7 +640,7 @@ fn import_meta_resolve( rv.set(resolved_val); } Err(err) => { - err.throw(scope); + crate::error::throw_js_error_class(scope, &err); } }; } @@ -658,9 +663,9 @@ fn catch_dynamic_import_promise_error( let arg = args.get(0); if is_instance_of_error(scope, arg) { let e: crate::error::NativeJsError = serde_v8::from_v8(scope, arg).unwrap(); - let name = e - .name - .unwrap_or_else(|| crate::error::GENERIC_ERROR.to_string()); + let name = e.name.unwrap_or_else(|| { + deno_error::builtin_classes::GENERIC_ERROR.to_string() + }); if !has_call_site(scope, arg) { let msg = v8::Exception::create_message(scope, arg); let arg: v8::Local = arg.try_into().unwrap(); @@ -675,12 +680,16 @@ fn catch_dynamic_import_promise_error( } } let exception = match name.as_str() { - crate::error::RANGE_ERROR => v8::Exception::range_error(scope, message), - crate::error::TYPE_ERROR => v8::Exception::type_error(scope, message), - crate::error::SYNTAX_ERROR => { + deno_error::builtin_classes::RANGE_ERROR => { + v8::Exception::range_error(scope, message) + } + deno_error::builtin_classes::TYPE_ERROR => { + v8::Exception::type_error(scope, message) + } + deno_error::builtin_classes::SYNTAX_ERROR => { v8::Exception::syntax_error(scope, message) } - crate::error::REFERENCE_ERROR => { + deno_error::builtin_classes::REFERENCE_ERROR => { v8::Exception::reference_error(scope, message) } _ => v8::Exception::error(scope, message), @@ -741,7 +750,10 @@ fn call_console( || !args.get(0).is_function() || !args.get(1).is_function() { - return JsNativeError::type_error("Invalid arguments").throw(scope); + return crate::error::throw_js_error_class( + scope, + &JsNativeError::type_error("Invalid arguments"), + ); } let mut call_args = vec![]; diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index 351bc6e08..2dc0a3df8 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -7,6 +7,7 @@ use crate::PromiseId; use serde::ser::SerializeStruct; use serde::Serialize; use std::borrow::Cow; +use std::error::Error; const MAX_RESULT_SIZE: usize = 32; @@ -263,6 +264,12 @@ impl OpResult { #[derive(Debug)] pub struct OpError(Box); +impl std::error::Error for OpError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + todo!() + } +} + impl std::fmt::Display for OpError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}: {}", self.0.get_class(), self.0.get_message()) @@ -274,11 +281,6 @@ impl From for OpError { Self(Box::new(err)) } } -impl From> for OpError { - fn from(err: Box) -> Self { - Self(err) - } -} impl Serialize for OpError { fn serialize(&self, serializer: S) -> Result @@ -297,15 +299,10 @@ impl Serialize for OpError { } /// Wrapper type to avoid circular trait implementation error due to From implementation -#[derive(Debug)] +#[derive(Debug, thiserror::Error)] +#[error(transparent)] pub struct OpErrorWrapper(pub OpError); -impl std::fmt::Display for OpErrorWrapper { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.0.fmt(f) - } -} - impl JsErrorClass for OpErrorWrapper { fn get_class(&self) -> &'static str { self.0 .0.get_class() diff --git a/core/runtime/ops.rs b/core/runtime/ops.rs index 596edba63..078dd1dc8 100644 --- a/core/runtime/ops.rs +++ b/core/runtime/ops.rs @@ -531,7 +531,6 @@ mod tests { use crate::OpState; use crate::RuntimeOptions; use crate::ToV8; - use anyhow::anyhow; use bytes::BytesMut; use futures::Future; use serde::Deserialize; @@ -2155,7 +2154,7 @@ mod tests { #[op2(async)] pub async fn op_async_sleep_error() -> Result<(), OpError> { tokio::time::sleep(Duration::from_millis(500)).await; - Err(anyhow!("whoops").into()) + Err(JsNativeError::generic("whoops").into()) } #[tokio::test] @@ -2177,7 +2176,7 @@ mod tests { #[op2(async(deferred), fast)] pub async fn op_async_deferred_error() -> Result<(), OpError> { - Err(anyhow!("whoops").into()) + Err(JsNativeError::generic("whoops").into()) } #[tokio::test] @@ -2205,7 +2204,7 @@ mod tests { #[op2(async(lazy), fast)] pub async fn op_async_lazy_error() -> Result<(), OpError> { - Err(anyhow!("whoops").into()) + Err(JsNativeError::generic("whoops").into()) } #[tokio::test] diff --git a/core/runtime/tests/ops.rs b/core/runtime/tests/ops.rs index 5357a406a..c6e224087 100644 --- a/core/runtime/tests/ops.rs +++ b/core/runtime/tests/ops.rs @@ -2,13 +2,13 @@ #![allow(clippy::print_stdout, clippy::print_stderr, clippy::unused_async)] -use crate::error::OpError; +use crate::error::{JsNativeError}; +use crate::error::{OpError}; use crate::extensions::OpDecl; use crate::modules::StaticModuleLoader; use crate::runtime::tests::setup; use crate::runtime::tests::Mode; use crate::*; -use anyhow::anyhow; use futures::Future; use pretty_assertions::assert_eq; use std::cell::RefCell; @@ -542,7 +542,7 @@ pub async fn op_async() { #[allow(unreachable_code)] pub fn op_async_impl_future_error() -> Result, OpError> { - return Err(anyhow!("dead").into()); + return Err(JsNativeError::generic("dead").into()); Ok(async {}) } @@ -556,13 +556,13 @@ pub async fn op_async_yield() { pub async fn op_async_yield_error() -> Result<(), OpError> { tokio::task::yield_now().await; println!("op_async_yield_error!"); - Err(anyhow!("dead").into()) + Err(JsNativeError::generic("dead").into()) } #[op2(async)] pub async fn op_async_error() -> Result<(), OpError> { println!("op_async_error!"); - Err(anyhow!("dead").into()) + Err(JsNativeError::generic("dead").into()) } #[op2(async(deferred), fast)] @@ -582,7 +582,7 @@ pub fn op_sync() { #[op2(fast)] pub fn op_sync_error() -> Result<(), OpError> { - Err(anyhow::anyhow!("Always fails").into()) + Err(JsNativeError::generic("Always fails").into()) } #[op2(fast)] diff --git a/js_error/Cargo.toml b/js_error/Cargo.toml deleted file mode 100644 index e17df0f67..000000000 --- a/js_error/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. - -[package] -name = "deno_js_error" -version = "0.1.0" -authors.workspace = true -edition.workspace = true -license.workspace = true -readme = "README.md" -repository.workspace = true -description = "derive macro for writing Deno Errors" - -[lib] -path = "./lib.rs" -proc-macro = true - -[dependencies] -proc-macro-rules.workspace = true -proc-macro2.workspace = true -quote.workspace = true -strum.workspace = true -strum_macros.workspace = true -syn.workspace = true - -[dev-dependencies] -pretty_assertions.workspace = true -prettyplease.workspace = true -testing_macros.workspace = true diff --git a/js_error/js_error/mod.rs b/js_error/js_error/mod.rs deleted file mode 100644 index 1a1046cac..000000000 --- a/js_error/js_error/mod.rs +++ /dev/null @@ -1,326 +0,0 @@ -use proc_macro2::Ident; -use proc_macro2::TokenStream; -use quote::format_ident; -use quote::quote; -use quote::ToTokens; -use syn::parse::Parse; -use syn::parse::ParseStream; -use syn::parse2; -use syn::spanned::Spanned; -use syn::Data; -use syn::DeriveInput; -use syn::Error; -use syn::Fields; -use syn::LitStr; -use syn::Meta; - -pub(crate) fn js_error(item: TokenStream) -> Result { - let input = parse2::(item)?; - - let (class, get_message, out_properties) = match input.data { - Data::Enum(data) => { - let top_class_attr = input - .attrs - .into_iter() - .find_map(|attr| ClassAttrValue::from_attribute(attr).transpose()) - .transpose()?; - if let Some(top_class_attr) = &top_class_attr { - if matches!(top_class_attr, ClassAttrValue::Inherit(_)) { - return Err(Error::new( - top_class_attr.span(), - "top level class attribute cannot be inherit", - )); - } - } - - let mut get_class = vec![]; - let mut get_message = vec![]; - let mut get_properties = vec![]; - - for variant in data.variants { - let class_attr = variant - .attrs - .into_iter() - .find_map(|attr| ClassAttrValue::from_attribute(attr).transpose()) - .unwrap_or_else(|| { - top_class_attr.clone().ok_or_else(|| { - Error::new(variant.ident.span(), "class attribute is missing") - }) - })?; - - let variant_ident = variant.ident; - - let properties = - properties_to_tokens(get_properties_from_fields(&variant.fields)?); - - let inherit_member = match variant.fields { - Fields::Named(fields_named) => fields_named - .named - .iter() - .find(get_inherit_attr_field) - .map(|field| syn::Member::Named(field.ident.clone().unwrap())), - Fields::Unnamed(fields_unnamed) => fields_unnamed - .unnamed - .iter() - .enumerate() - .find(|(_, field)| get_inherit_attr_field(field)) - .map(|(i, _)| syn::Member::Unnamed(syn::Index::from(i))), - Fields::Unit => None, - }; - - let match_arm = if let Some(member) = &inherit_member { - quote!(Self::#variant_ident { #member: inherit, .. }) - } else { - quote!(Self::#variant_ident { .. }) - }; - - let class = if matches!(class_attr, ClassAttrValue::Inherit(_)) { - if inherit_member.is_some() { - quote!(::deno_core::error::JsErrorClass::get_class(inherit)) - } else { - return Err(Error::new( - class_attr.span(), - "class attribute was set to inherit, but no field was marked as inherit", - )); - } - } else { - quote!(#class_attr) - }; - get_class.push(quote! { - #match_arm => #class, - }); - - let message = if inherit_member.is_some() { - quote!(::deno_core::error::JsErrorClass::get_message(inherit)) - } else { - quote!(self.to_string().into()) - }; - get_message.push(quote! { - #match_arm => #message, - }); - - // TODO: handle adding properties in addition to inherited ones - let properties = if inherit_member.is_some() { - quote!(::deno_core::error::JsErrorClass::get_additional_properties( - inherit - )) - } else { - properties - }; - get_properties.push(quote! { - #match_arm => { - #properties - } - }); - } - - ( - quote! { - match self { - #(#get_class)* - } - }, - quote! { - match self { - #(#get_message)* - } - }, - quote! { - match self { - #(#get_properties)* - } - }, - ) - } - Data::Struct(data) => { - todo!(); - let class = input - .attrs - .into_iter() - .find_map(|attr| ClassAttrValue::from_attribute(attr).transpose()) - .transpose()? - .ok_or_else(|| { - Error::new(input.ident.span(), "class attribute is missing") - })?; - let properties = get_properties_from_fields(&data.fields)?; - - let out_properties = properties_to_tokens(properties); - - (class.into_token_stream(), quote!(""), out_properties) - } - Data::Union(_) => { - return Err(Error::new(input.span(), "Unions are not supported")) - } - }; - - let ident = input.ident; - - Ok(quote! { - #[allow(unused_qualifications)] - impl ::deno_core::error::JsErrorClass for #ident { - fn get_class(&self) -> &'static str { - #class - } - fn get_message(&self) -> ::std::borrow::Cow<'static, str> { - #get_message - } - fn get_additional_properties( - &self - ) -> Option, ::std::borrow::Cow<'static, str>)>> { - #out_properties - } - } - }) -} - -fn get_inherit_attr_field(field: &&syn::Field) -> bool { - field - .attrs - .iter() - .any(|attr| attr.path().is_ident("inherit")) -} - -mod kw { - syn::custom_keyword!(class); - syn::custom_keyword!(property); - syn::custom_keyword!(inherit); -} - -#[derive(Debug, Clone)] -enum ClassAttrValue { - Lit(syn::LitStr), - Ident(Ident), - Inherit(kw::inherit), -} - -impl ClassAttrValue { - fn from_attribute(attr: syn::Attribute) -> Result, Error> { - if attr.path().is_ident("class") { - let list = attr.meta.require_list()?; - let value = list.parse_args::()?; - return Ok(Some(value)); - } - - Ok(None) - } -} - -impl ToTokens for ClassAttrValue { - fn to_tokens(&self, tokens: &mut TokenStream) { - let class_tokens = match self { - ClassAttrValue::Lit(lit) => quote!(#lit), - ClassAttrValue::Ident(ident) => { - let error_name = format_ident!("{}_ERROR", ident); - quote!(::deno_core::error::builtin_classes::#error_name) - } - ClassAttrValue::Inherit(_) => unreachable!(), - }; - - class_tokens.to_tokens(tokens) - } -} - -impl Parse for ClassAttrValue { - fn parse(input: ParseStream) -> syn::Result { - let lookahead = input.lookahead1(); - - if lookahead.peek(syn::LitStr) { - Ok(Self::Lit(input.parse()?)) - } else if lookahead.peek(kw::inherit) { - Ok(Self::Inherit(input.parse()?)) - } else if lookahead.peek(syn::Ident) { - Ok(Self::Ident(input.parse()?)) - } else { - Err(lookahead.error()) - } - } -} - -#[derive(Debug)] -struct ParsedProperty { - ident: syn::Member, - name: String, -} - -fn get_properties_from_fields( - fields: &Fields, -) -> Result, Error> { - const PROPERTY_IDENT: &str = "property"; - let mut out_fields = vec![]; - - match fields { - Fields::Named(named) => { - for field in &named.named { - for attr in &field.attrs { - if attr.path().is_ident(PROPERTY_IDENT) { - let name = match &attr.meta { - Meta::Path(_) => None, - Meta::List(list) => { - return Err(Error::new( - list.delimiter.span().open(), - "expected `=`", - )); - } - Meta::NameValue(meta) => { - Some(parse2::(meta.value.to_token_stream())?.value()) - } - }; - - let ident = field.ident.clone().unwrap(); - let name = name.unwrap_or_else(|| ident.to_string()); - let ident = syn::Member::Named(field.ident.clone().unwrap()); - out_fields.push(ParsedProperty { name, ident }); - - break; - } - } - } - } - Fields::Unnamed(unnamed) => { - for (i, field) in unnamed.unnamed.iter().enumerate() { - for attr in &field.attrs { - if attr.path().is_ident(PROPERTY_IDENT) { - let name_value = attr.meta.require_name_value()?; - let name = - parse2::(name_value.value.to_token_stream())?.value(); - - let ident = syn::Member::Unnamed(syn::Index::from(i)); - out_fields.push(ParsedProperty { name, ident }); - - break; - } - } - } - } - Fields::Unit => {} - } - - Ok(out_fields) -} - -fn properties_to_tokens(properties: Vec) -> TokenStream { - if !properties.is_empty() { - let properties = properties - .into_iter() - .map(|property| { - let ident = property.ident; - let ident_str = property.name; - - quote! { - ( - ::std::borrow::Cow::Borrowed(#ident_str), - ::std::borrow::Cow::Owned(self.#ident.to_string()), - ), - } - }) - .collect::>(); - - quote! { - Some(vec![ - #(#properties),* - ]) - } - } else { - quote!(None) - } -} diff --git a/js_error/lib.rs b/js_error/lib.rs deleted file mode 100644 index f283ef7c4..000000000 --- a/js_error/lib.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -#![deny(clippy::unnecessary_wraps)] - -mod js_error; - -use proc_macro::TokenStream; - -#[proc_macro_derive(JsError, attributes(class, property, inherit))] -pub fn derive_js_error(item: TokenStream) -> TokenStream { - js_error_macro(item) -} - -fn js_error_macro(item: TokenStream) -> TokenStream { - match js_error::js_error(item.into()) { - Ok(output) => output.into(), - Err(err) => err.into_compile_error().into(), - } -} diff --git a/serde_v8/Cargo.toml b/serde_v8/Cargo.toml index 1a52a1a45..b931e76aa 100644 --- a/serde_v8/Cargo.toml +++ b/serde_v8/Cargo.toml @@ -19,6 +19,7 @@ serde.workspace = true smallvec = { workspace = true, features = ["union"] } thiserror.workspace = true v8.workspace = true +deno_error.workspace = true [dev-dependencies] bencher.workspace = true diff --git a/serde_v8/error.rs b/serde_v8/error.rs index ec1f38e1d..84d220d9a 100644 --- a/serde_v8/error.rs +++ b/serde_v8/error.rs @@ -3,7 +3,8 @@ use std::fmt::Display; pub type Result = std::result::Result; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, deno_error::JsError)] +#[class(type)] #[non_exhaustive] pub enum Error { #[error("{0}")] diff --git a/testing/Cargo.toml b/testing/Cargo.toml index 11df31420..335f14138 100644 --- a/testing/Cargo.toml +++ b/testing/Cargo.toml @@ -18,6 +18,7 @@ anyhow.workspace = true deno_ast.workspace = true deno_core.workspace = true deno_core.features = ["unsafe_use_unprotected_platform", "snapshot_flags_eager_parse"] +deno_error.workspace = true futures.workspace = true tokio.workspace = true url.workspace = true diff --git a/testing/checkin/runner/ts_module_loader.rs b/testing/checkin/runner/ts_module_loader.rs index 26e838852..62cea4a2d 100644 --- a/testing/checkin/runner/ts_module_loader.rs +++ b/testing/checkin/runner/ts_module_loader.rs @@ -36,13 +36,13 @@ pub struct TypescriptModuleLoader { source_maps: SourceMapStore, } -deno_core::js_error_wrapper!( +deno_error::js_error_wrapper!( deno_ast::ParseDiagnostic, JsParseDiagnostic, "TypeError" ); -deno_core::js_error_wrapper!( +deno_error::js_error_wrapper!( deno_ast::TranspileError, JsTranspileError, "TypeError" From be75ffb2cd7b3a6d1b2739d4083c713a68352821 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sat, 23 Nov 2024 08:02:18 +0100 Subject: [PATCH 36/52] fix --- Cargo.lock | 3132 --------------------------------- core/Cargo.toml | 4 +- core/io/resource.rs | 10 +- core/modules/map.rs | 22 +- core/modules/mod.rs | 15 +- core/runtime/tests/ops.rs | 4 +- testing/checkin/runner/ops.rs | 4 +- 7 files changed, 33 insertions(+), 3158 deletions(-) delete mode 100644 Cargo.lock diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index ae206e692..000000000 --- a/Cargo.lock +++ /dev/null @@ -1,3132 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "Inflector" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" -dependencies = [ - "lazy_static", - "regex", -] - -[[package]] -name = "addr2line" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" - -[[package]] -name = "ahash" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" -dependencies = [ - "cfg-if", - "getrandom", - "once_cell", - "version_check", - "zerocopy", -] - -[[package]] -name = "aho-corasick" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" -dependencies = [ - "memchr", -] - -[[package]] -name = "anes" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" - -[[package]] -name = "anstream" -version = "0.6.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b" - -[[package]] -name = "anstyle-parse" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a64c907d4e79225ac72e2a354c9ce84d50ebb4586dee56c82b3ee73004f537f5" -dependencies = [ - "windows-sys 0.52.0", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" -dependencies = [ - "anstyle", - "windows-sys 0.52.0", -] - -[[package]] -name = "anyhow" -version = "1.0.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25bdb32cbbdce2b519a9cd7df3a678443100e265d5e25ca763b7572a5104f5f3" - -[[package]] -name = "ast_node" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab31376d309dd3bfc9cfb3c11c93ce0e0741bbe0354b20e7f8c60b044730b79" -dependencies = [ - "proc-macro2", - "quote", - "swc_macros_common", - "syn", -] - -[[package]] -name = "autocfg" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" - -[[package]] -name = "backtrace" -version = "0.3.71" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d" -dependencies = [ - "addr2line", - "cc", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", -] - -[[package]] -name = "base64" -version = "0.21.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" - -[[package]] -name = "base64-simd" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "781dd20c3aff0bd194fe7d2a977dd92f21c173891f3a03b677359e5fa457e5d5" -dependencies = [ - "simd-abstraction", -] - -[[package]] -name = "bencher" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dfdb4953a096c551ce9ace855a604d702e6e62d77fac690575ae347571717f5" - -[[package]] -name = "better_scoped_tls" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "794edcc9b3fb07bb4aecaa11f093fd45663b4feadb782d68303a2268bc2701de" -dependencies = [ - "scoped-tls", -] - -[[package]] -name = "bincode" -version = "1.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" -dependencies = [ - "serde", -] - -[[package]] -name = "bindgen" -version = "0.70.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" -dependencies = [ - "bitflags", - "cexpr", - "clang-sys", - "itertools", - "log", - "prettyplease", - "proc-macro2", - "quote", - "regex", - "rustc-hash", - "shlex", - "syn", -] - -[[package]] -name = "bit-set" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "bitflags" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" - -[[package]] -name = "bitvec" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" -dependencies = [ - "funty", - "radium", - "tap", - "wyz", -] - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "build-your-own-js-snapshot" -version = "0.1.0" -dependencies = [ - "deno_core", - "tokio", -] - -[[package]] -name = "bumpalo" -version = "3.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" - -[[package]] -name = "bytes" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" - -[[package]] -name = "cast" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" - -[[package]] -name = "cc" -version = "1.0.97" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "099a5357d84c4c61eb35fc8eafa9a79a902c2f76911e5747ced4e032edd8d9b4" - -[[package]] -name = "cexpr" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" -dependencies = [ - "nom", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "ciborium" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" -dependencies = [ - "ciborium-io", - "ciborium-ll", - "serde", -] - -[[package]] -name = "ciborium-io" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" - -[[package]] -name = "ciborium-ll" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" -dependencies = [ - "ciborium-io", - "half", -] - -[[package]] -name = "clang-sys" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" -dependencies = [ - "glob", - "libc", - "libloading", -] - -[[package]] -name = "clap" -version = "4.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" -dependencies = [ - "clap_builder", -] - -[[package]] -name = "clap_builder" -version = "4.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_lex" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" - -[[package]] -name = "colorchoice" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" - -[[package]] -name = "cooked-waker" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147be55d677052dabc6b22252d5dd0fd4c29c8c27aa4f2fbef0f94aa003b406f" - -[[package]] -name = "cpufeatures" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504" -dependencies = [ - "libc", -] - -[[package]] -name = "crc32fast" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3855a8a784b474f333699ef2bbca9db2c4a1f6d9088a90a2d25b1eb53111eaa" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "criterion" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" -dependencies = [ - "anes", - "cast", - "ciborium", - "clap", - "criterion-plot", - "is-terminal", - "itertools", - "num-traits", - "once_cell", - "oorandom", - "plotters", - "rayon", - "regex", - "serde", - "serde_derive", - "serde_json", - "tinytemplate", - "walkdir", -] - -[[package]] -name = "criterion-plot" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" -dependencies = [ - "cast", - "itertools", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345" - -[[package]] -name = "crunchy" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" - -[[package]] -name = "crypto-common" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "dashmap" -version = "5.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" -dependencies = [ - "cfg-if", - "hashbrown", - "lock_api", - "once_cell", - "parking_lot_core", -] - -[[package]] -name = "data-encoding" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2" - -[[package]] -name = "data-url" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c297a1c74b71ae29df00c3e22dd9534821d60eb9af5a0192823fa2acea70c2a" - -[[package]] -name = "dcore" -version = "0.1.0" -dependencies = [ - "anyhow", - "clap", - "deno_core", - "deno_core_testing", - "fastwebsockets", - "http", - "http-body-util", - "hyper", - "hyper-util", - "serde_json", - "tokio", - "uuid", -] - -[[package]] -name = "debugid" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" -dependencies = [ - "serde", - "uuid", -] - -[[package]] -name = "deno_ast" -version = "0.40.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d08372522975cce97fe0efbe42fea508c76eea4421619de6d63baae32792f7d" -dependencies = [ - "anyhow", - "base64", - "deno_media_type", - "deno_terminal", - "dprint-swc-ext", - "once_cell", - "percent-encoding", - "serde", - "swc_atoms", - "swc_common", - "swc_config", - "swc_config_macro", - "swc_ecma_ast", - "swc_ecma_codegen", - "swc_ecma_codegen_macros", - "swc_ecma_loader", - "swc_ecma_parser", - "swc_ecma_transforms_base", - "swc_ecma_transforms_classes", - "swc_ecma_transforms_macros", - "swc_ecma_transforms_proposal", - "swc_ecma_transforms_react", - "swc_ecma_transforms_typescript", - "swc_ecma_utils", - "swc_ecma_visit", - "swc_eq_ignore_macros", - "swc_macros_common", - "swc_visit", - "swc_visit_macros", - "text_lines", - "thiserror 1.0.60", - "unicode-width", - "url", -] - -[[package]] -name = "deno_core" -version = "0.322.0" -dependencies = [ - "anyhow", - "bencher", - "bincode", - "bit-set", - "bit-vec", - "bytes", - "cooked-waker", - "criterion", - "deno_ast", - "deno_core_icudata", - "deno_error", - "deno_ops", - "deno_unsync", - "fastrand", - "futures", - "indexmap", - "libc", - "memoffset", - "parking_lot", - "percent-encoding", - "pin-project", - "pretty_assertions", - "rstest", - "serde", - "serde_json", - "serde_v8", - "smallvec", - "sourcemap", - "static_assertions", - "thiserror 1.0.60", - "tokio", - "twox-hash", - "unicycle", - "url", - "v8", - "wasm_dep_analyzer", -] - -[[package]] -name = "deno_core_icudata" -version = "0.74.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe4dccb6147bb3f3ba0c7a48e993bfeb999d2c2e47a81badee80e2b370c8d695" - -[[package]] -name = "deno_core_testing" -version = "0.0.0" -dependencies = [ - "anyhow", - "deno_ast", - "deno_core", - "deno_error", - "futures", - "pretty_assertions", - "prettyplease", - "testing_macros", - "tokio", - "url", -] - -[[package]] -name = "deno_error" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7212b2c7eab654fa8856f7d0c5ad6c805f9e32982079735ca3a0fee1381e101" -dependencies = [ - "deno_error_macro", - "libc", - "serde", - "serde_json", - "tokio", - "url", -] - -[[package]] -name = "deno_error_macro" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23a3cd1a50eed6696671493663fa1d2542a487350527b133ef8db0765bc83334" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "deno_media_type" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8978229b82552bf8457a0125aa20863f023619cfc21ebb007b1e571d68fd85b" -dependencies = [ - "data-url", - "serde", - "url", -] - -[[package]] -name = "deno_ops" -version = "0.198.0" -dependencies = [ - "pretty_assertions", - "prettyplease", - "proc-macro-rules", - "proc-macro2", - "quote", - "stringcase", - "strum", - "strum_macros", - "syn", - "testing_macros", - "thiserror 2.0.3", -] - -[[package]] -name = "deno_ops_compile_test_runner" -version = "0.2.0" -dependencies = [ - "bytes", - "deno_core", - "deno_ops", - "pretty_assertions", - "prettyplease", - "rustversion", - "serde", - "syn", - "testing_macros", - "trybuild", -] - -[[package]] -name = "deno_terminal" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e6337d4e7f375f8b986409a76fbeecfa4bd8a1343e63355729ae4befa058eaf" -dependencies = [ - "once_cell", - "termcolor", -] - -[[package]] -name = "deno_unsync" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f36b4ef61a04ce201b925a5dffa90f88437d37fee4836c758470dd15ba7f05e" -dependencies = [ - "parking_lot", - "tokio", -] - -[[package]] -name = "diff" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", -] - -[[package]] -name = "dprint-swc-ext" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a0d5b63e52434314e3d767c463b1f68c467c31e61d279bc019227016c44e535" -dependencies = [ - "num-bigint", - "rustc-hash", - "swc_atoms", - "swc_common", - "swc_ecma_ast", - "swc_ecma_parser", - "text_lines", -] - -[[package]] -name = "either" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a47c1c47d2f5964e29c61246e81db715514cd532db6b5116a25ea3c03d6780a2" - -[[package]] -name = "equivalent" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" - -[[package]] -name = "errno" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "fastrand" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" - -[[package]] -name = "fastwebsockets" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f63dd7b57f9b33b1741fa631c9522eb35d43e96dcca4a6a91d5e4ca7c93acdc1" -dependencies = [ - "base64", - "http-body-util", - "hyper", - "hyper-util", - "pin-project", - "rand", - "sha1", - "simdutf8", - "thiserror 1.0.60", - "tokio", - "utf-8", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "from_variant" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdc9cc75639b041067353b9bce2450d6847e547276c6fbe4487d7407980e07db" -dependencies = [ - "proc-macro2", - "swc_macros_common", - "syn", -] - -[[package]] -name = "fslock" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "funty" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" - -[[package]] -name = "futures" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" - -[[package]] -name = "futures-executor" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" - -[[package]] -name = "futures-macro" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "futures-sink" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" - -[[package]] -name = "futures-task" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" - -[[package]] -name = "futures-timer" -version = "3.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" - -[[package]] -name = "futures-util" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "pin-utils", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "gimli" -version = "0.28.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" - -[[package]] -name = "glob" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" - -[[package]] -name = "gzip-header" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95cc527b92e6029a62960ad99aa8a6660faa4555fe5f731aab13aa6a921795a2" -dependencies = [ - "crc32fast", -] - -[[package]] -name = "h2" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "816ec7294445779408f36fe57bc5b7fc1cf59664059096c65f905c1c61f58069" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "half" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dd08c532ae367adf81c312a4580bc67f1d0fe8bc9c460520283f4c0ff277888" -dependencies = [ - "cfg-if", - "crunchy", -] - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "hermit-abi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" - -[[package]] -name = "home" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" -dependencies = [ - "windows-sys 0.52.0", -] - -[[package]] -name = "hstr" -version = "0.2.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96274be293b8877e61974a607105d09c84caebe9620b47774aa8a6b942042dd4" -dependencies = [ - "hashbrown", - "new_debug_unreachable", - "once_cell", - "phf", - "rustc-hash", - "triomphe", -] - -[[package]] -name = "http" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - -[[package]] -name = "http-body" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0475f8b2ac86659c21b64320d5d653f9efe42acd2a4e560073ec61a155a34f1d" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" - -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - -[[package]] -name = "hyper" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5aa53871fc917b1a9ed87b683a5d86db645e23acb32c2e0785a353e522fb75" -dependencies = [ - "bytes", - "futures-channel", - "futures-util", - "h2", - "http", - "http-body", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "tokio", - "want", -] - -[[package]] -name = "hyper-util" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdea9aac0dbe5a9240d68cfd9501e2db94222c6dc06843e06640b9e07f0fdc67" -dependencies = [ - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "hyper", - "pin-project-lite", - "socket2", - "tokio", - "tracing", -] - -[[package]] -name = "idna" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" -dependencies = [ - "unicode-bidi", - "unicode-normalization", -] - -[[package]] -name = "if_chain" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" - -[[package]] -name = "indexmap" -version = "2.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" -dependencies = [ - "equivalent", - "hashbrown", -] - -[[package]] -name = "is-macro" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a85abdc13717906baccb5a1e435556ce0df215f242892f721dff62bf25288f" -dependencies = [ - "Inflector", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "is-terminal" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b" -dependencies = [ - "hermit-abi", - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" - -[[package]] -name = "itertools" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" - -[[package]] -name = "js-sys" -version = "0.3.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" -dependencies = [ - "wasm-bindgen", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.162" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18d287de67fe55fd7e1581fe933d965a5a9477b38e949cfa9f8574ef01506398" - -[[package]] -name = "libloading" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d" -dependencies = [ - "cfg-if", - "windows-targets 0.52.5", -] - -[[package]] -name = "linux-raw-sys" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" - -[[package]] -name = "lock_api" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" - -[[package]] -name = "memchr" -version = "2.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" - -[[package]] -name = "memoffset" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" -dependencies = [ - "autocfg", -] - -[[package]] -name = "minimal-lexical" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" - -[[package]] -name = "miniz_oxide" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7" -dependencies = [ - "adler", -] - -[[package]] -name = "mio" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.48.0", -] - -[[package]] -name = "new_debug_unreachable" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" - -[[package]] -name = "nom" -version = "7.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" -dependencies = [ - "memchr", - "minimal-lexical", -] - -[[package]] -name = "num-bigint" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c165a9ab64cf766f73521c0dd2cfdff64f488b8f0b3e621face3462d3db536d7" -dependencies = [ - "num-integer", - "num-traits", - "rand", - "serde", -] - -[[package]] -name = "num-integer" -version = "0.1.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "object" -version = "0.32.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441" -dependencies = [ - "memchr", -] - -[[package]] -name = "once_cell" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" - -[[package]] -name = "oorandom" -version = "11.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" - -[[package]] -name = "outref" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f222829ae9293e33a9f5e9f440c6760a3d450a64affe1846486b140db81c1f4" - -[[package]] -name = "parking_lot" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-targets 0.52.5", -] - -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - -[[package]] -name = "pathdiff" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" - -[[package]] -name = "percent-encoding" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" - -[[package]] -name = "phf" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" -dependencies = [ - "phf_macros", - "phf_shared", -] - -[[package]] -name = "phf_generator" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" -dependencies = [ - "phf_shared", - "rand", -] - -[[package]] -name = "phf_macros" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3444646e286606587e49f3bcf1679b8cef1dc2c5ecc29ddacaffc305180d464b" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "phf_shared" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "plotters" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2c224ba00d7cadd4d5c660deaf2098e5e80e07846537c51f9cfa4be50c1fd45" -dependencies = [ - "num-traits", - "plotters-backend", - "plotters-svg", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "plotters-backend" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e76628b4d3a7581389a35d5b6e2139607ad7c75b17aed325f210aa91f4a9609" - -[[package]] -name = "plotters-svg" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38f6d39893cca0701371e3c27294f09797214b86f1fb951b89ade8ec04e2abab" -dependencies = [ - "plotters-backend", -] - -[[package]] -name = "ppv-lite86" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" - -[[package]] -name = "pretty_assertions" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af7cee1a6c8a5b9208b3cb1061f10c0cb689087b3d8ce85fb9d2dd7a29b6ba66" -dependencies = [ - "diff", - "yansi", -] - -[[package]] -name = "prettyplease" -version = "0.2.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e" -dependencies = [ - "proc-macro2", - "syn", -] - -[[package]] -name = "proc-macro-rules" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07c277e4e643ef00c1233393c673f655e3672cf7eb3ba08a00bdd0ea59139b5f" -dependencies = [ - "proc-macro-rules-macros", - "proc-macro2", - "syn", -] - -[[package]] -name = "proc-macro-rules-macros" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "207fffb0fe655d1d47f6af98cc2793405e85929bdbc420d685554ff07be27ac7" -dependencies = [ - "once_cell", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "proc-macro2" -version = "1.0.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "psm" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5787f7cda34e3033a72192c018bc5883100330f362ef279a8cbccfce8bb4e874" -dependencies = [ - "cc", -] - -[[package]] -name = "quote" -version = "1.0.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "radium" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rayon" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - -[[package]] -name = "redox_syscall" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "469052894dcb553421e483e4209ee581a45100d31b4018de03e5a7ad86374a7e" -dependencies = [ - "bitflags", -] - -[[package]] -name = "regex" -version = "1.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" - -[[package]] -name = "relative-path" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" - -[[package]] -name = "rstest" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d5316d2a1479eeef1ea21e7f9ddc67c191d497abc8fc3ba2467857abbb68330" -dependencies = [ - "futures", - "futures-timer", - "rstest_macros", - "rustc_version 0.4.0", -] - -[[package]] -name = "rstest_macros" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04a9df72cc1f67020b0d63ad9bfe4a323e459ea7eb68e03bd9824db49f9a4c25" -dependencies = [ - "cfg-if", - "glob", - "proc-macro2", - "quote", - "regex", - "relative-path", - "rustc_version 0.4.0", - "syn", - "unicode-ident", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -dependencies = [ - "semver 0.9.0", -] - -[[package]] -name = "rustc_version" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" -dependencies = [ - "semver 1.0.23", -] - -[[package]] -name = "rustix" -version = "0.38.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.52.0", -] - -[[package]] -name = "rustversion" -version = "1.0.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "092474d1a01ea8278f69e6a358998405fae5b8b963ddaeb2b0b04a128bf1dfb0" - -[[package]] -name = "ryu" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" - -[[package]] -name = "ryu-js" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad97d4ce1560a5e27cec89519dc8300d1aa6035b099821261c651486a19e44d5" - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "scoped-tls" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -dependencies = [ - "semver-parser", -] - -[[package]] -name = "semver" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" - -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - -[[package]] -name = "serde" -version = "1.0.201" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "780f1cebed1629e4753a1a38a3c72d30b97ec044f0aef68cb26650a3c5cf363c" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_bytes" -version = "0.11.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b8497c313fd43ab992087548117643f6fcd935cbf36f176ffda0aacf9591734" -dependencies = [ - "serde", -] - -[[package]] -name = "serde_derive" -version = "1.0.201" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e405930b9796f1c00bee880d03fc7e0bb4b9a11afc776885ffe84320da2865" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3" -dependencies = [ - "indexmap", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_spanned" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb3622f419d1296904700073ea6cc23ad690adbd66f13ea683df73298736f0c1" -dependencies = [ - "serde", -] - -[[package]] -name = "serde_v8" -version = "0.231.0" -dependencies = [ - "bencher", - "deno_error", - "num-bigint", - "serde", - "serde_bytes", - "serde_json", - "serde_v8_utilities", - "smallvec", - "thiserror 2.0.3", - "v8", -] - -[[package]] -name = "serde_v8_utilities" -version = "0.3.0" -dependencies = [ - "v8", -] - -[[package]] -name = "sha1" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "signal-hook-registry" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" -dependencies = [ - "libc", -] - -[[package]] -name = "simd-abstraction" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cadb29c57caadc51ff8346233b5cec1d240b68ce55cf1afc764818791876987" -dependencies = [ - "outref", -] - -[[package]] -name = "simdutf8" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f27f6278552951f1f2b8cf9da965d10969b2efdea95a6ec47987ab46edfe263a" - -[[package]] -name = "siphasher" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" - -[[package]] -name = "slab" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" -dependencies = [ - "autocfg", -] - -[[package]] -name = "smallvec" -version = "1.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" - -[[package]] -name = "smartstring" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29" -dependencies = [ - "autocfg", - "static_assertions", - "version_check", -] - -[[package]] -name = "socket2" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "sourcemap" -version = "8.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "208d40b9e8cad9f93613778ea295ed8f3c2b1824217c6cfc7219d3f6f45b96d4" -dependencies = [ - "base64-simd", - "bitvec", - "data-encoding", - "debugid", - "if_chain", - "rustc-hash", - "rustc_version 0.2.3", - "serde", - "serde_json", - "unicode-id-start", - "url", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - -[[package]] -name = "stacker" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c886bd4480155fd3ef527d45e9ac8dd7118a898a46530b7b94c3e21866259fce" -dependencies = [ - "cc", - "cfg-if", - "libc", - "psm", - "winapi", -] - -[[package]] -name = "static_assertions" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" - -[[package]] -name = "string_enum" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05e383308aebc257e7d7920224fa055c632478d92744eca77f99be8fa1545b90" -dependencies = [ - "proc-macro2", - "quote", - "swc_macros_common", - "syn", -] - -[[package]] -name = "stringcase" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04028eeb851ed08af6aba5caa29f2d59a13ed168cee4d6bd753aeefcf1d636b0" - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "strum" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" -dependencies = [ - "strum_macros", -] - -[[package]] -name = "strum_macros" -version = "0.25.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "rustversion", - "syn", -] - -[[package]] -name = "swc_atoms" -version = "0.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb6567e4e67485b3e7662b486f1565bdae54bd5b9d6b16b2ba1a9babb1e42125" -dependencies = [ - "hstr", - "once_cell", - "rustc-hash", - "serde", -] - -[[package]] -name = "swc_cached" -version = "0.3.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83406221c501860fce9c27444f44125eafe9e598b8b81be7563d7036784cd05c" -dependencies = [ - "ahash", - "anyhow", - "dashmap", - "once_cell", - "regex", - "serde", -] - -[[package]] -name = "swc_common" -version = "0.34.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9087befec6b63911f9d2f239e4f91c9b21589c169b86ed2d616944d23cf4a243" -dependencies = [ - "ast_node", - "better_scoped_tls", - "cfg-if", - "either", - "from_variant", - "new_debug_unreachable", - "num-bigint", - "once_cell", - "rustc-hash", - "serde", - "siphasher", - "sourcemap", - "swc_atoms", - "swc_eq_ignore_macros", - "swc_visit", - "tracing", - "unicode-width", - "url", -] - -[[package]] -name = "swc_config" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84b67e115ab136fe0eb03558bb0508ca7782eeb446a96d165508c48617e3fd94" -dependencies = [ - "anyhow", - "indexmap", - "serde", - "serde_json", - "swc_cached", - "swc_config_macro", -] - -[[package]] -name = "swc_config_macro" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c5f56139042c1a95b54f5ca48baa0e0172d369bcc9d3d473dad1de36bae8399" -dependencies = [ - "proc-macro2", - "quote", - "swc_macros_common", - "syn", -] - -[[package]] -name = "swc_ecma_ast" -version = "0.115.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7be1306930c235435a892104c00c2b5e16231043c085d5a10bd3e7537b15659b" -dependencies = [ - "bitflags", - "is-macro", - "num-bigint", - "phf", - "scoped-tls", - "serde", - "string_enum", - "swc_atoms", - "swc_common", - "unicode-id-start", -] - -[[package]] -name = "swc_ecma_codegen" -version = "0.151.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5141a8cb4eb69e090e6aea5d49061b46919be5210f3d084f9d9ad63d30f5cff" -dependencies = [ - "memchr", - "num-bigint", - "once_cell", - "rustc-hash", - "serde", - "sourcemap", - "swc_atoms", - "swc_common", - "swc_ecma_ast", - "swc_ecma_codegen_macros", - "tracing", -] - -[[package]] -name = "swc_ecma_codegen_macros" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "090e409af49c8d1a3c13b3aab1ed09dd4eda982207eb3e63c2ad342f072b49c8" -dependencies = [ - "proc-macro2", - "quote", - "swc_macros_common", - "syn", -] - -[[package]] -name = "swc_ecma_loader" -version = "0.46.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a9febebf047d1286e7b723fa2758f3229da2c103834f3eaee69833f46692612" -dependencies = [ - "anyhow", - "pathdiff", - "serde", - "swc_atoms", - "swc_common", - "tracing", -] - -[[package]] -name = "swc_ecma_parser" -version = "0.146.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a4e0c2e85f12c63b85c805e923079b04d1fb3e25edd069d638eed5f2098de74" -dependencies = [ - "either", - "new_debug_unreachable", - "num-bigint", - "num-traits", - "phf", - "serde", - "smallvec", - "smartstring", - "stacker", - "swc_atoms", - "swc_common", - "swc_ecma_ast", - "tracing", - "typed-arena", -] - -[[package]] -name = "swc_ecma_transforms_base" -version = "0.140.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d37dc505c92af56d0f77cf6f31a6ccd37ac40cad1e01ff77277e0b1c70e8f8ff" -dependencies = [ - "better_scoped_tls", - "bitflags", - "indexmap", - "once_cell", - "phf", - "rustc-hash", - "serde", - "smallvec", - "swc_atoms", - "swc_common", - "swc_ecma_ast", - "swc_ecma_parser", - "swc_ecma_utils", - "swc_ecma_visit", - "tracing", -] - -[[package]] -name = "swc_ecma_transforms_classes" -version = "0.129.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3eab5f8179e5b0aedf385eacc2c033691c6d211a7babd1bbbff12cf794a824e" -dependencies = [ - "swc_atoms", - "swc_common", - "swc_ecma_ast", - "swc_ecma_transforms_base", - "swc_ecma_utils", - "swc_ecma_visit", -] - -[[package]] -name = "swc_ecma_transforms_macros" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "500a1dadad1e0e41e417d633b3d6d5de677c9e0d3159b94ba3348436cdb15aab" -dependencies = [ - "proc-macro2", - "quote", - "swc_macros_common", - "syn", -] - -[[package]] -name = "swc_ecma_transforms_proposal" -version = "0.174.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6df8aa6752cc2fcf3d78ac67827542fb666e52283f2b26802aa058906bb750d3" -dependencies = [ - "either", - "rustc-hash", - "serde", - "smallvec", - "swc_atoms", - "swc_common", - "swc_ecma_ast", - "swc_ecma_transforms_base", - "swc_ecma_transforms_classes", - "swc_ecma_transforms_macros", - "swc_ecma_utils", - "swc_ecma_visit", -] - -[[package]] -name = "swc_ecma_transforms_react" -version = "0.186.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446da32cac8299973aaf1d37496562bfd0c1e4f3c3ab5d0af6f07f42e8184102" -dependencies = [ - "base64", - "dashmap", - "indexmap", - "once_cell", - "serde", - "sha1", - "string_enum", - "swc_atoms", - "swc_common", - "swc_config", - "swc_ecma_ast", - "swc_ecma_parser", - "swc_ecma_transforms_base", - "swc_ecma_transforms_macros", - "swc_ecma_utils", - "swc_ecma_visit", -] - -[[package]] -name = "swc_ecma_transforms_typescript" -version = "0.191.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1ce8af2865449e714ae56dacb6b54b3f6dc4cc25074da4e39b878bd93c5e39c" -dependencies = [ - "ryu-js", - "serde", - "swc_atoms", - "swc_common", - "swc_ecma_ast", - "swc_ecma_transforms_base", - "swc_ecma_transforms_react", - "swc_ecma_utils", - "swc_ecma_visit", -] - -[[package]] -name = "swc_ecma_utils" -version = "0.130.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13e62b199454a576c5fdbd7e1bef8ab88a395427456d8a713d994b7d469833aa" -dependencies = [ - "indexmap", - "num_cpus", - "once_cell", - "rustc-hash", - "ryu-js", - "swc_atoms", - "swc_common", - "swc_ecma_ast", - "swc_ecma_visit", - "tracing", - "unicode-id", -] - -[[package]] -name = "swc_ecma_visit" -version = "0.101.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce0d997f0c9b4e181225f603d161f6757c2a97022258170982cfe005ec69ec92" -dependencies = [ - "num-bigint", - "swc_atoms", - "swc_common", - "swc_ecma_ast", - "swc_visit", - "tracing", -] - -[[package]] -name = "swc_eq_ignore_macros" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "695a1d8b461033d32429b5befbf0ad4d7a2c4d6ba9cd5ba4e0645c615839e8e4" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "swc_macros_common" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91745f3561057493d2da768437c427c0e979dff7396507ae02f16c981c4a8466" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "swc_visit" -version = "0.5.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "043d11fe683dcb934583ead49405c0896a5af5face522e4682c16971ef7871b9" -dependencies = [ - "either", - "swc_visit_macros", -] - -[[package]] -name = "swc_visit_macros" -version = "0.5.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae9ef18ff8daffa999f729db056d2821cd2f790f3a11e46422d19f46bb193e7" -dependencies = [ - "Inflector", - "proc-macro2", - "quote", - "swc_macros_common", - "syn", -] - -[[package]] -name = "syn" -version = "2.0.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "tap" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" - -[[package]] -name = "termcolor" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "testing_macros" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32d8d51dafe71c966464b06d3b5c1eca715590e952d20a908d003fd34791a773" -dependencies = [ - "anyhow", - "glob", - "once_cell", - "proc-macro2", - "quote", - "regex", - "relative-path", - "syn", -] - -[[package]] -name = "text_lines" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fd5828de7deaa782e1dd713006ae96b3bee32d3279b79eb67ecf8072c059bcf" -dependencies = [ - "serde", -] - -[[package]] -name = "thiserror" -version = "1.0.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "579e9083ca58dd9dcf91a9923bb9054071b9ebbd800b342194c9feb0ee89fc18" -dependencies = [ - "thiserror-impl 1.0.60", -] - -[[package]] -name = "thiserror" -version = "2.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c006c85c7651b3cf2ada4584faa36773bd07bac24acfb39f3c431b36d7e667aa" -dependencies = [ - "thiserror-impl 2.0.3", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2470041c06ec3ac1ab38d0356a6119054dedaea53e12fbefc0de730a1c08524" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tinytemplate" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "tinyvec" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokio" -version = "1.37.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787" -dependencies = [ - "backtrace", - "bytes", - "libc", - "mio", - "num_cpus", - "parking_lot", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.48.0", -] - -[[package]] -name = "tokio-macros" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tokio-util" -version = "0.7.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf6b47b3771c49ac75ad09a6162f53ad4b8088b76ac60e8ec1455b31a189fe1" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "toml" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9dd1545e8208b4a5af1aa9bbd0b4cf7e9ea08fabc5d0a5c67fcaafa17433aa3" -dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", -] - -[[package]] -name = "toml_datetime" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_edit" -version = "0.22.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3328d4f68a705b2a4498da1d580585d39a6510f98318a2cec3018a7ec61ddef" -dependencies = [ - "indexmap", - "serde", - "serde_spanned", - "toml_datetime", - "winnow", -] - -[[package]] -name = "tracing" -version = "0.1.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" -dependencies = [ - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" -dependencies = [ - "once_cell", -] - -[[package]] -name = "triomphe" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "859eb650cfee7434994602c3a68b25d77ad9e68c8a6cd491616ef86661382eb3" -dependencies = [ - "serde", - "stable_deref_trait", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "trybuild" -version = "1.0.95" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ddb747392ea12569d501a5bbca08852e4c8cd88b92566074b2243b8846f09e6" -dependencies = [ - "glob", - "serde", - "serde_derive", - "serde_json", - "termcolor", - "toml", -] - -[[package]] -name = "twox-hash" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d09466de2fbca05ea830e16e62943f26607ab2148fb72b642505541711d99ad2" - -[[package]] -name = "typed-arena" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a" - -[[package]] -name = "typenum" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" - -[[package]] -name = "unicode-bidi" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" - -[[package]] -name = "unicode-id" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1b6def86329695390197b82c1e244a54a131ceb66c996f2088a3876e2ae083f" - -[[package]] -name = "unicode-id-start" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02aebfa694eccbbbffdd92922c7de136b9fe764396d2f10e21bce1681477cfc1" - -[[package]] -name = "unicode-ident" -version = "1.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" - -[[package]] -name = "unicode-normalization" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-width" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68f5e5f3158ecfd4b8ff6fe086db7c8467a2dfdac97fe420f2b7c4aa97af66d6" - -[[package]] -name = "unicycle" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ca7c60c63c67acf573ef612b410c42b351c1028216085fd72fb43e2b1abd2fc" -dependencies = [ - "futures-core", - "lock_api", - "parking_lot", - "uniset", -] - -[[package]] -name = "uniset" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40789245bbff5f31eb773c9ac4ee5c4e15eab9640d975e124d6ce4c34a6410d7" - -[[package]] -name = "url" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf-8" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" - -[[package]] -name = "utf8parse" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" - -[[package]] -name = "uuid" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a183cf7feeba97b4dd1c0d46788634f6221d87fa961b305bed08c851829efcc0" -dependencies = [ - "getrandom", -] - -[[package]] -name = "v8" -version = "130.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c23b5c2caff00209b03a716609b275acae94b02dd3b63c4648e7232a84a8402f" -dependencies = [ - "bindgen", - "bitflags", - "fslock", - "gzip-header", - "home", - "miniz_oxide", - "once_cell", - "paste", - "which", -] - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "walkdir" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" -dependencies = [ - "same-file", - "winapi-util", -] - -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" - -[[package]] -name = "wasm-bindgen" -version = "0.2.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" -dependencies = [ - "cfg-if", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" -dependencies = [ - "bumpalo", - "log", - "once_cell", - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" - -[[package]] -name = "wasm_dep_analyzer" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f270206a91783fd90625c8bb0d8fbd459d0b1d1bf209b656f713f01ae7c04b8" -dependencies = [ - "thiserror", -] - -[[package]] -name = "web-sys" -version = "0.3.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "which" -version = "6.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8211e4f58a2b2805adfbefbc07bab82958fc91e3836339b1ab7ae32465dce0d7" -dependencies = [ - "either", - "home", - "rustix", - "winsafe", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b" -dependencies = [ - "windows-sys 0.52.0", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.5", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - -[[package]] -name = "windows-targets" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" -dependencies = [ - "windows_aarch64_gnullvm 0.52.5", - "windows_aarch64_msvc 0.52.5", - "windows_i686_gnu 0.52.5", - "windows_i686_gnullvm", - "windows_i686_msvc 0.52.5", - "windows_x86_64_gnu 0.52.5", - "windows_x86_64_gnullvm 0.52.5", - "windows_x86_64_msvc 0.52.5", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" - -[[package]] -name = "winnow" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3c52e9c97a68071b23e836c9380edae937f17b9c4667bd021973efc689f618d" -dependencies = [ - "memchr", -] - -[[package]] -name = "winsafe" -version = "0.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" - -[[package]] -name = "wyz" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" -dependencies = [ - "tap", -] - -[[package]] -name = "yansi" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" - -[[package]] -name = "zerocopy" -version = "0.7.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae87e3fcd617500e5d106f0380cf7b77f3c6092aae37191433159dda23cfb087" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.7.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15e934569e47891f7d9411f1a451d947a60e000ab3bd24fbb970f000387d1b3b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] diff --git a/core/Cargo.toml b/core/Cargo.toml index 011199b24..629242b29 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -30,6 +30,7 @@ bit-vec.workspace = true bytes.workspace = true cooked-waker.workspace = true deno_core_icudata = { workspace = true, optional = true } +deno_error.workspace = true deno_ops.workspace = true deno_unsync.workspace = true futures.workspace = true @@ -46,9 +47,10 @@ smallvec.workspace = true sourcemap.workspace = true static_assertions.workspace = true tokio.workspace = true +thiserror.workspace = true url.workspace = true v8.workspace = true -wasm_dep_analyzer = "0.1.0" +wasm_dep_analyzer = "0.2.0" [dev-dependencies] bencher.workspace = true diff --git a/core/io/resource.rs b/core/io/resource.rs index 4f59dd485..9be32d959 100644 --- a/core/io/resource.rs +++ b/core/io/resource.rs @@ -260,7 +260,10 @@ macro_rules! impl_writable { view: $crate::BufView, ) -> $crate::AsyncResult<$crate::WriteOutcome> { ::std::boxed::Box::pin(async move { - let nwritten = self.write(&view).await.map_err(::deno_core::error::JsNativeError::from_err)?; + let nwritten = self + .write(&view) + .await + .map_err(::deno_core::error::JsNativeError::from_err)?; ::std::result::Result::Ok($crate::WriteOutcome::Partial { nwritten, view, @@ -274,7 +277,10 @@ macro_rules! impl_writable { view: $crate::BufView, ) -> $crate::AsyncResult<()> { ::std::boxed::Box::pin(async move { - self.write_all(&view).await.map_err(::deno_core::error::JsNativeError::from_err)?; + self + .write_all(&view) + .await + .map_err(::deno_core::error::JsNativeError::from_err)?; ::std::result::Result::Ok(()) }) } diff --git a/core/modules/map.rs b/core/modules/map.rs index e1c30c214..6ec0ea317 100644 --- a/core/modules/map.rs +++ b/core/modules/map.rs @@ -384,9 +384,7 @@ impl ModuleMap { } ModuleType::Wasm => { let ModuleSourceCode::Bytes(code) = code else { - return Err(ModuleError::Other(generic_error( - "Source code for Wasm module must be provided as bytes", - ))); + return Err(ModuleError::Concrete(ModuleConcreteError::WasmNotBytes)); }; self.new_wasm_module(scope, module_url_found, code, dynamic)? } @@ -751,16 +749,10 @@ impl ModuleMap { bytes, wasm_dep_analyzer::ParseOptions { skip_types: true }, ) - .map_err(|e| { - let err = Error::from(e); - ModuleError::Other(err) - })?; + .map_err(ModuleConcreteError::WasmParse)?; let Some(wasm_module) = v8::WasmModuleObject::compile(scope, bytes) else { - return Err(ModuleError::Other(generic_error(format!( - "Failed to compile Wasm module '{}'", - name.as_str() - )))); + return Err(ModuleConcreteError::WasmCompile(name.to_string()).into()); }; let wasm_module_value: v8::Local = wasm_module.into(); @@ -773,12 +765,8 @@ impl ModuleMap { let (name1, name2) = name.into_cheap_copy(); let value = v8::Local::new(scope, wasm_module_value); let exports = vec![(ascii_str!("default"), value)]; - let _synthetic_mod_id = self.new_synthetic_module( - scope, - name1, - synthetic_module_type, - exports, - )?; + let _synthetic_mod_id = + self.new_synthetic_module(scope, name1, synthetic_module_type, exports); self.new_module_from_js_source( scope, diff --git a/core/modules/mod.rs b/core/modules/mod.rs index 18ce8f316..10aa29258 100644 --- a/core/modules/mod.rs +++ b/core/modules/mod.rs @@ -637,8 +637,13 @@ pub enum ModuleConcreteError { }, #[error("Unable to get code cache from unbound module script")] UnboundModuleScriptCodeCache, - #[error("Importing Wasm modules is currently not supported")] - WasmUnsupported, + #[class(inherit)] + #[error("{0}")] + WasmParse(wasm_dep_analyzer::ParseError), + #[error("Source code for Wasm module must be provided as bytes")] + WasmNotBytes, + #[error("Failed to compile Wasm module '{0}'")] + WasmCompile(String), #[error("Importing '{0}' modules is not supported")] UnsupportedKind(String), } @@ -668,3 +673,9 @@ impl ModuleError { } } } + +impl From for ModuleError { + fn from(value: ModuleConcreteError) -> Self { + ModuleError::Concrete(value) + } +} diff --git a/core/runtime/tests/ops.rs b/core/runtime/tests/ops.rs index c6e224087..9a39615b0 100644 --- a/core/runtime/tests/ops.rs +++ b/core/runtime/tests/ops.rs @@ -2,8 +2,8 @@ #![allow(clippy::print_stdout, clippy::print_stderr, clippy::unused_async)] -use crate::error::{JsNativeError}; -use crate::error::{OpError}; +use crate::error::JsNativeError; +use crate::error::OpError; use crate::extensions::OpDecl; use crate::modules::StaticModuleLoader; use crate::runtime::tests::setup; diff --git a/testing/checkin/runner/ops.rs b/testing/checkin/runner/ops.rs index 042f49e3c..ba8643b42 100644 --- a/testing/checkin/runner/ops.rs +++ b/testing/checkin/runner/ops.rs @@ -2,7 +2,7 @@ use std::cell::RefCell; use std::rc::Rc; -use deno_core::error::AnyError; +use deno_core::error::JsNativeError; use deno_core::op2; use deno_core::stats::RuntimeActivityDiff; use deno_core::stats::RuntimeActivitySnapshot; @@ -103,7 +103,7 @@ impl DOMPoint { fn from_point( scope: &mut v8::HandleScope, other: v8::Local, - ) -> Result { + ) -> Result { fn get( scope: &mut v8::HandleScope, other: v8::Local, From 060e6bc55b6e6af8c5725c0432f491d8d52cea04 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sat, 23 Nov 2024 08:02:25 +0100 Subject: [PATCH 37/52] fix --- Cargo.lock | 3384 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 3384 insertions(+) create mode 100644 Cargo.lock diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 000000000..f73191944 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,3384 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "Inflector" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" +dependencies = [ + "lazy_static", + "regex", +] + +[[package]] +name = "addr2line" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "adler2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" + +[[package]] +name = "ahash" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + +[[package]] +name = "anstream" +version = "0.6.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" + +[[package]] +name = "anstyle-parse" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2109dbce0e72be3ec00bed26e6a7479ca384ad226efdd66db8fa2e3a38c83125" +dependencies = [ + "anstyle", + "windows-sys 0.59.0", +] + +[[package]] +name = "anyhow" +version = "1.0.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" + +[[package]] +name = "ast_node" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9184f2b369b3e8625712493c89b785881f27eedc6cde480a81883cef78868b2" +dependencies = [ + "proc-macro2", + "quote", + "swc_macros_common", + "syn", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" + +[[package]] +name = "backtrace" +version = "0.3.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide 0.8.0", + "object", + "rustc-demangle", + "windows-targets", +] + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64-simd" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "781dd20c3aff0bd194fe7d2a977dd92f21c173891f3a03b677359e5fa457e5d5" +dependencies = [ + "simd-abstraction", +] + +[[package]] +name = "bencher" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dfdb4953a096c551ce9ace855a604d702e6e62d77fac690575ae347571717f5" + +[[package]] +name = "better_scoped_tls" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "297b153aa5e573b5863108a6ddc9d5c968bd0b20e75cc614ee9821d2f45679c7" +dependencies = [ + "scoped-tls", +] + +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bindgen" +version = "0.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn", +] + +[[package]] +name = "bit-set" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" + +[[package]] +name = "bitflags" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" + +[[package]] +name = "bitvec" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "build-your-own-js-snapshot" +version = "0.1.0" +dependencies = [ + "deno_core", + "tokio", +] + +[[package]] +name = "bumpalo" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" + +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + +[[package]] +name = "cc" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9de9f2205d5ef3fd67e685b0df337994ddd4495e2a28d185500d0e1edfea47" +dependencies = [ + "shlex", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + +[[package]] +name = "clang-sys" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clap" +version = "4.5.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb3b4b9e5a7c7514dfa52869339ee98b3156b0bfb4e8a77c4ff4babb64b1604f" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.5.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b17a95aa67cc7b5ebd32aa5370189aa0d79069ef1c64ce893bd30fb24bff20ec" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_lex" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afb84c814227b90d6895e01398aee0d8033c00e7466aca416fb6a8e0eb19d8a7" + +[[package]] +name = "colorchoice" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" + +[[package]] +name = "cooked-waker" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147be55d677052dabc6b22252d5dd0fd4c29c8c27aa4f2fbef0f94aa003b406f" + +[[package]] +name = "cpufeatures" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b80225097f2e5ae4e7179dd2266824648f3e2f49d9134d584b76389d31c4c3" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "criterion" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" +dependencies = [ + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "is-terminal", + "itertools 0.10.5", + "num-traits", + "once_cell", + "oorandom", + "plotters", + "rayon", + "regex", + "serde", + "serde_derive", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" +dependencies = [ + "cast", + "itertools 0.10.5", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" + +[[package]] +name = "crunchy" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "dashmap" +version = "5.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +dependencies = [ + "cfg-if", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "data-encoding" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2" + +[[package]] +name = "data-url" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c297a1c74b71ae29df00c3e22dd9534821d60eb9af5a0192823fa2acea70c2a" + +[[package]] +name = "dcore" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "deno_core", + "deno_core_testing", + "fastwebsockets", + "http", + "http-body-util", + "hyper", + "hyper-util", + "serde_json", + "tokio", + "uuid", +] + +[[package]] +name = "debugid" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" +dependencies = [ + "serde", + "uuid", +] + +[[package]] +name = "deno_ast" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d08372522975cce97fe0efbe42fea508c76eea4421619de6d63baae32792f7d" +dependencies = [ + "anyhow", + "base64", + "deno_media_type", + "deno_terminal", + "dprint-swc-ext", + "once_cell", + "percent-encoding", + "serde", + "swc_atoms", + "swc_common", + "swc_config", + "swc_config_macro", + "swc_ecma_ast", + "swc_ecma_codegen", + "swc_ecma_codegen_macros", + "swc_ecma_loader", + "swc_ecma_parser", + "swc_ecma_transforms_base", + "swc_ecma_transforms_classes", + "swc_ecma_transforms_macros", + "swc_ecma_transforms_proposal", + "swc_ecma_transforms_react", + "swc_ecma_transforms_typescript", + "swc_ecma_utils", + "swc_ecma_visit", + "swc_eq_ignore_macros", + "swc_macros_common", + "swc_visit", + "swc_visit_macros", + "text_lines", + "thiserror 1.0.69", + "unicode-width", + "url", +] + +[[package]] +name = "deno_core" +version = "0.322.0" +dependencies = [ + "anyhow", + "bencher", + "bincode", + "bit-set", + "bit-vec", + "bytes", + "cooked-waker", + "criterion", + "deno_ast", + "deno_core_icudata", + "deno_error", + "deno_ops", + "deno_unsync", + "fastrand", + "futures", + "indexmap", + "libc", + "memoffset", + "parking_lot", + "percent-encoding", + "pin-project", + "pretty_assertions", + "rstest", + "serde", + "serde_json", + "serde_v8", + "smallvec", + "sourcemap", + "static_assertions", + "thiserror 2.0.3", + "tokio", + "twox-hash", + "unicycle", + "url", + "v8", + "wasm_dep_analyzer", +] + +[[package]] +name = "deno_core_icudata" +version = "0.74.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe4dccb6147bb3f3ba0c7a48e993bfeb999d2c2e47a81badee80e2b370c8d695" + +[[package]] +name = "deno_core_testing" +version = "0.0.0" +dependencies = [ + "anyhow", + "deno_ast", + "deno_core", + "deno_error", + "futures", + "pretty_assertions", + "prettyplease", + "testing_macros", + "tokio", + "url", +] + +[[package]] +name = "deno_error" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17093059f04120895ee7bad790f074b1e4a0aa7c68511dbe8355ad0b092a4910" +dependencies = [ + "deno_error_macro", + "libc", + "serde", + "serde_json", + "tokio", + "url", +] + +[[package]] +name = "deno_error_macro" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3a5d888391b76dc9b53e35651d2d11086fa05110beba167f08294920dd9059" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "deno_media_type" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8978229b82552bf8457a0125aa20863f023619cfc21ebb007b1e571d68fd85b" +dependencies = [ + "data-url", + "serde", + "url", +] + +[[package]] +name = "deno_ops" +version = "0.198.0" +dependencies = [ + "pretty_assertions", + "prettyplease", + "proc-macro-rules", + "proc-macro2", + "quote", + "stringcase", + "strum", + "strum_macros", + "syn", + "testing_macros", + "thiserror 2.0.3", +] + +[[package]] +name = "deno_ops_compile_test_runner" +version = "0.2.0" +dependencies = [ + "bytes", + "deno_core", + "deno_ops", + "pretty_assertions", + "prettyplease", + "rustversion", + "serde", + "syn", + "testing_macros", + "trybuild", +] + +[[package]] +name = "deno_terminal" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e6337d4e7f375f8b986409a76fbeecfa4bd8a1343e63355729ae4befa058eaf" +dependencies = [ + "once_cell", + "termcolor", +] + +[[package]] +name = "deno_unsync" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f36b4ef61a04ce201b925a5dffa90f88437d37fee4836c758470dd15ba7f05e" +dependencies = [ + "parking_lot", + "tokio", +] + +[[package]] +name = "diff" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "dprint-swc-ext" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b909f9f9b22a6265839887544dce97b0b8e2b2635abf622f45613deb3de63e0" +dependencies = [ + "num-bigint", + "rustc-hash", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_parser", + "text_lines", +] + +[[package]] +name = "either" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" + +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "errno" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "fastrand" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "486f806e73c5707928240ddc295403b1b93c96a02038563881c4a2fd84b81ac4" + +[[package]] +name = "fastwebsockets" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63dd7b57f9b33b1741fa631c9522eb35d43e96dcca4a6a91d5e4ca7c93acdc1" +dependencies = [ + "base64", + "http-body-util", + "hyper", + "hyper-util", + "pin-project", + "rand", + "sha1", + "simdutf8", + "thiserror 1.0.69", + "tokio", + "utf-8", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "form_urlencoded" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "from_variant" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32016f1242eb82af5474752d00fd8ebcd9004bd69b462b1c91de833972d08ed4" +dependencies = [ + "proc-macro2", + "swc_macros_common", + "syn", +] + +[[package]] +name = "fslock" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-executor" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" + +[[package]] +name = "futures-macro" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-timer" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "gimli" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" + +[[package]] +name = "glob" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" + +[[package]] +name = "gzip-header" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95cc527b92e6029a62960ad99aa8a6660faa4555fe5f731aab13aa6a921795a2" +dependencies = [ + "crc32fast", +] + +[[package]] +name = "h2" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccae279728d634d083c00f6099cb58f01cc99c145b84b8be2f6c74618d79922e" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "half" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dd08c532ae367adf81c312a4580bc67f1d0fe8bc9c460520283f4c0ff277888" +dependencies = [ + "cfg-if", + "crunchy", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a9bfc1af68b1726ea47d3d5109de126281def866b33970e10fbab11b5dafab3" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" + +[[package]] +name = "home" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "hstr" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dae404c0c5d4e95d4858876ab02eecd6a196bb8caa42050dfa809938833fc412" +dependencies = [ + "hashbrown 0.14.5", + "new_debug_unreachable", + "once_cell", + "phf", + "rustc-hash", + "triomphe", +] + +[[package]] +name = "http" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" +dependencies = [ + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d71d3574edd2771538b901e6549113b4006ece66150fb69c0fb6d9a2adae946" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5aa53871fc917b1a9ed87b683a5d86db645e23acb32c2e0785a353e522fb75" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "tokio", + "want", +] + +[[package]] +name = "hyper-util" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdea9aac0dbe5a9240d68cfd9501e2db94222c6dc06843e06640b9e07f0fdc67" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "pin-project-lite", + "socket2", + "tokio", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locid" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locid_transform" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_locid_transform_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locid_transform_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" + +[[package]] +name = "icu_normalizer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" + +[[package]] +name = "icu_properties" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locid_transform", + "icu_properties_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" + +[[package]] +name = "icu_provider" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_provider_macros", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_provider_macros" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "idna" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "if_chain" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" + +[[package]] +name = "indexmap" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" +dependencies = [ + "equivalent", + "hashbrown 0.15.1", +] + +[[package]] +name = "is-macro" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d57a3e447e24c22647738e4607f1df1e0ec6f72e16182c4cd199f647cdfb0e4" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "is-terminal" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b" +dependencies = [ + "hermit-abi 0.4.0", + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "540654e97a3f4470a492cd30ff187bc95d89557a903a2bbf112e2fae98104ef2" + +[[package]] +name = "js-sys" +version = "0.3.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.164" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "433bfe06b8c75da9b2e3fbea6e5329ff87748f0b144ef75306e674c3f6f7c13f" + +[[package]] +name = "libloading" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" +dependencies = [ + "cfg-if", + "windows-targets", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" + +[[package]] +name = "litemap" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ee93343901ab17bd981295f2cf0026d4ad018c7c31ba84549a4ddbb47a45104" + +[[package]] +name = "lock_api" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" + +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" +dependencies = [ + "adler", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" +dependencies = [ + "adler2", +] + +[[package]] +name = "mio" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" +dependencies = [ + "hermit-abi 0.3.9", + "libc", + "wasi", + "windows-sys 0.52.0", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", + "rand", + "serde", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +dependencies = [ + "hermit-abi 0.3.9", + "libc", +] + +[[package]] +name = "object" +version = "0.36.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" + +[[package]] +name = "oorandom" +version = "11.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b410bbe7e14ab526a0e86877eb47c6996a2bd7746f027ba551028c925390e4e9" + +[[package]] +name = "outref" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f222829ae9293e33a9f5e9f440c6760a3d450a64affe1846486b140db81c1f4" + +[[package]] +name = "parking_lot" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pathdiff" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d61c5ce1153ab5b689d0c074c4e7fc613e942dfb7dd9eea5ab202d2ad91fe361" + +[[package]] +name = "percent-encoding" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" + +[[package]] +name = "phf" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +dependencies = [ + "phf_macros", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_macros" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3444646e286606587e49f3bcf1679b8cef1dc2c5ecc29ddacaffc305180d464b" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "phf_shared" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be57f64e946e500c8ee36ef6331845d40a93055567ec57e8fae13efd33759b95" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915a1e146535de9163f3987b8944ed8cf49a18bb0056bcebcdcece385cece4ff" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "plotters" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" +dependencies = [ + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "plotters-backend" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" + +[[package]] +name = "plotters-svg" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" +dependencies = [ + "plotters-backend", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "pretty_assertions" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" +dependencies = [ + "diff", + "yansi", +] + +[[package]] +name = "prettyplease" +version = "0.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d1ec885c64d0457d564db4ec299b2dae3f9c02808b8ad9c3a089c591b18033" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro-crate" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecf48c7ca261d60b74ab1a7b20da18bede46776b2e55535cb958eb595c5fa7b" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro-rules" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07c277e4e643ef00c1233393c673f655e3672cf7eb3ba08a00bdd0ea59139b5f" +dependencies = [ + "proc-macro-rules-macros", + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro-rules-macros" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "207fffb0fe655d1d47f6af98cc2793405e85929bdbc420d685554ff07be27ac7" +dependencies = [ + "once_cell", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "psm" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200b9ff220857e53e184257720a14553b2f4aa02577d2ed9842d45d4b9654810" +dependencies = [ + "cc", +] + +[[package]] +name = "quote" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rayon" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" + +[[package]] +name = "relative-path" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" + +[[package]] +name = "rstest" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a2c585be59b6b5dd66a9d2084aa1d8bd52fbdb806eafdeffb52791147862035" +dependencies = [ + "futures", + "futures-timer", + "rstest_macros", + "rustc_version 0.4.1", +] + +[[package]] +name = "rstest_macros" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "825ea780781b15345a146be27eaefb05085e337e869bff01b4306a4fd4a9ad5a" +dependencies = [ + "cfg-if", + "glob", + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version 0.4.1", + "syn", + "unicode-ident", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +dependencies = [ + "semver 0.9.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver 1.0.23", +] + +[[package]] +name = "rustix" +version = "0.38.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7f649912bc1495e167a6edee79151c84b1bad49748cb4f1f1167f459f6224f6" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustversion" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" + +[[package]] +name = "ryu" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" + +[[package]] +name = "ryu-js" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad97d4ce1560a5e27cec89519dc8300d1aa6035b099821261c651486a19e44d5" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +dependencies = [ + "semver-parser", +] + +[[package]] +name = "semver" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" + +[[package]] +name = "serde" +version = "1.0.215" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_bytes" +version = "0.11.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "387cc504cb06bb40a96c8e04e951fe01854cf6bc921053c954e4a606d9675c6a" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_derive" +version = "1.0.215" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.133" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" +dependencies = [ + "indexmap", + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "serde_spanned" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_v8" +version = "0.231.0" +dependencies = [ + "bencher", + "deno_error", + "num-bigint", + "serde", + "serde_bytes", + "serde_json", + "serde_v8_utilities", + "smallvec", + "thiserror 2.0.3", + "v8", +] + +[[package]] +name = "serde_v8_utilities" +version = "0.3.0" +dependencies = [ + "v8", +] + +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook-registry" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" +dependencies = [ + "libc", +] + +[[package]] +name = "simd-abstraction" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cadb29c57caadc51ff8346233b5cec1d240b68ce55cf1afc764818791876987" +dependencies = [ + "outref", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + +[[package]] +name = "slab" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" +dependencies = [ + "autocfg", +] + +[[package]] +name = "smallvec" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" + +[[package]] +name = "smartstring" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29" +dependencies = [ + "autocfg", + "static_assertions", + "version_check", +] + +[[package]] +name = "socket2" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "sourcemap" +version = "8.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "208d40b9e8cad9f93613778ea295ed8f3c2b1824217c6cfc7219d3f6f45b96d4" +dependencies = [ + "base64-simd", + "bitvec", + "data-encoding", + "debugid", + "if_chain", + "rustc-hash", + "rustc_version 0.2.3", + "serde", + "serde_json", + "unicode-id-start", + "url", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + +[[package]] +name = "stacker" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799c883d55abdb5e98af1a7b3f23b9b6de8ecada0ecac058672d7635eb48ca7b" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.59.0", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "string_enum" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05e383308aebc257e7d7920224fa055c632478d92744eca77f99be8fa1545b90" +dependencies = [ + "proc-macro2", + "quote", + "swc_macros_common", + "syn", +] + +[[package]] +name = "stringcase" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04028eeb851ed08af6aba5caa29f2d59a13ed168cee4d6bd753aeefcf1d636b0" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.25.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "rustversion", + "syn", +] + +[[package]] +name = "swc_atoms" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb6567e4e67485b3e7662b486f1565bdae54bd5b9d6b16b2ba1a9babb1e42125" +dependencies = [ + "hstr", + "once_cell", + "rustc-hash", + "serde", +] + +[[package]] +name = "swc_cached" +version = "0.3.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83406221c501860fce9c27444f44125eafe9e598b8b81be7563d7036784cd05c" +dependencies = [ + "ahash", + "anyhow", + "dashmap", + "once_cell", + "regex", + "serde", +] + +[[package]] +name = "swc_common" +version = "0.34.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9087befec6b63911f9d2f239e4f91c9b21589c169b86ed2d616944d23cf4a243" +dependencies = [ + "ast_node", + "better_scoped_tls", + "cfg-if", + "either", + "from_variant", + "new_debug_unreachable", + "num-bigint", + "once_cell", + "rustc-hash", + "serde", + "siphasher", + "sourcemap", + "swc_atoms", + "swc_eq_ignore_macros", + "swc_visit", + "tracing", + "unicode-width", + "url", +] + +[[package]] +name = "swc_config" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84b67e115ab136fe0eb03558bb0508ca7782eeb446a96d165508c48617e3fd94" +dependencies = [ + "anyhow", + "indexmap", + "serde", + "serde_json", + "swc_cached", + "swc_config_macro", +] + +[[package]] +name = "swc_config_macro" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c5f56139042c1a95b54f5ca48baa0e0172d369bcc9d3d473dad1de36bae8399" +dependencies = [ + "proc-macro2", + "quote", + "swc_macros_common", + "syn", +] + +[[package]] +name = "swc_ecma_ast" +version = "0.115.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7be1306930c235435a892104c00c2b5e16231043c085d5a10bd3e7537b15659b" +dependencies = [ + "bitflags", + "is-macro", + "num-bigint", + "phf", + "scoped-tls", + "serde", + "string_enum", + "swc_atoms", + "swc_common", + "unicode-id-start", +] + +[[package]] +name = "swc_ecma_codegen" +version = "0.151.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5141a8cb4eb69e090e6aea5d49061b46919be5210f3d084f9d9ad63d30f5cff" +dependencies = [ + "memchr", + "num-bigint", + "once_cell", + "rustc-hash", + "serde", + "sourcemap", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_codegen_macros", + "tracing", +] + +[[package]] +name = "swc_ecma_codegen_macros" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "090e409af49c8d1a3c13b3aab1ed09dd4eda982207eb3e63c2ad342f072b49c8" +dependencies = [ + "proc-macro2", + "quote", + "swc_macros_common", + "syn", +] + +[[package]] +name = "swc_ecma_loader" +version = "0.46.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9febebf047d1286e7b723fa2758f3229da2c103834f3eaee69833f46692612" +dependencies = [ + "anyhow", + "pathdiff", + "serde", + "swc_atoms", + "swc_common", + "tracing", +] + +[[package]] +name = "swc_ecma_parser" +version = "0.146.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a4e0c2e85f12c63b85c805e923079b04d1fb3e25edd069d638eed5f2098de74" +dependencies = [ + "either", + "new_debug_unreachable", + "num-bigint", + "num-traits", + "phf", + "serde", + "smallvec", + "smartstring", + "stacker", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "tracing", + "typed-arena", +] + +[[package]] +name = "swc_ecma_transforms_base" +version = "0.140.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d37dc505c92af56d0f77cf6f31a6ccd37ac40cad1e01ff77277e0b1c70e8f8ff" +dependencies = [ + "better_scoped_tls", + "bitflags", + "indexmap", + "once_cell", + "phf", + "rustc-hash", + "serde", + "smallvec", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_parser", + "swc_ecma_utils", + "swc_ecma_visit", + "tracing", +] + +[[package]] +name = "swc_ecma_transforms_classes" +version = "0.129.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3eab5f8179e5b0aedf385eacc2c033691c6d211a7babd1bbbff12cf794a824e" +dependencies = [ + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_transforms_base", + "swc_ecma_utils", + "swc_ecma_visit", +] + +[[package]] +name = "swc_ecma_transforms_macros" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "500a1dadad1e0e41e417d633b3d6d5de677c9e0d3159b94ba3348436cdb15aab" +dependencies = [ + "proc-macro2", + "quote", + "swc_macros_common", + "syn", +] + +[[package]] +name = "swc_ecma_transforms_proposal" +version = "0.174.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df8aa6752cc2fcf3d78ac67827542fb666e52283f2b26802aa058906bb750d3" +dependencies = [ + "either", + "rustc-hash", + "serde", + "smallvec", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_transforms_base", + "swc_ecma_transforms_classes", + "swc_ecma_transforms_macros", + "swc_ecma_utils", + "swc_ecma_visit", +] + +[[package]] +name = "swc_ecma_transforms_react" +version = "0.186.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446da32cac8299973aaf1d37496562bfd0c1e4f3c3ab5d0af6f07f42e8184102" +dependencies = [ + "base64", + "dashmap", + "indexmap", + "once_cell", + "serde", + "sha1", + "string_enum", + "swc_atoms", + "swc_common", + "swc_config", + "swc_ecma_ast", + "swc_ecma_parser", + "swc_ecma_transforms_base", + "swc_ecma_transforms_macros", + "swc_ecma_utils", + "swc_ecma_visit", +] + +[[package]] +name = "swc_ecma_transforms_typescript" +version = "0.191.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1ce8af2865449e714ae56dacb6b54b3f6dc4cc25074da4e39b878bd93c5e39c" +dependencies = [ + "ryu-js", + "serde", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_transforms_base", + "swc_ecma_transforms_react", + "swc_ecma_utils", + "swc_ecma_visit", +] + +[[package]] +name = "swc_ecma_utils" +version = "0.130.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13e62b199454a576c5fdbd7e1bef8ab88a395427456d8a713d994b7d469833aa" +dependencies = [ + "indexmap", + "num_cpus", + "once_cell", + "rustc-hash", + "ryu-js", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_visit", + "tracing", + "unicode-id", +] + +[[package]] +name = "swc_ecma_visit" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce0d997f0c9b4e181225f603d161f6757c2a97022258170982cfe005ec69ec92" +dependencies = [ + "num-bigint", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_visit", + "tracing", +] + +[[package]] +name = "swc_eq_ignore_macros" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "695a1d8b461033d32429b5befbf0ad4d7a2c4d6ba9cd5ba4e0645c615839e8e4" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "swc_macros_common" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91745f3561057493d2da768437c427c0e979dff7396507ae02f16c981c4a8466" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "swc_visit" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "043d11fe683dcb934583ead49405c0896a5af5face522e4682c16971ef7871b9" +dependencies = [ + "either", + "swc_visit_macros", +] + +[[package]] +name = "swc_visit_macros" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ef18ff8daffa999f729db056d2821cd2f790f3a11e46422d19f46bb193e7" +dependencies = [ + "Inflector", + "proc-macro2", + "quote", + "swc_macros_common", + "syn", +] + +[[package]] +name = "syn" +version = "2.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d46482f1c1c87acd84dea20c1bf5ebff4c757009ed6bf19cfd36fb10e92c4e" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "target-triple" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42a4d50cdb458045afc8131fd91b64904da29548bcb63c7236e0844936c13078" + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "testing_macros" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a39660370116afe46d5ff8bcb01b7afe2140dda3137ef5cb1914681e37a4ee06" +dependencies = [ + "anyhow", + "glob", + "once_cell", + "proc-macro2", + "quote", + "regex", + "relative-path", + "syn", +] + +[[package]] +name = "text_lines" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd5828de7deaa782e1dd713006ae96b3bee32d3279b79eb67ecf8072c059bcf" +dependencies = [ + "serde", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c006c85c7651b3cf2ada4584faa36773bd07bac24acfb39f3c431b36d7e667aa" +dependencies = [ + "thiserror-impl 2.0.3", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "tokio" +version = "1.41.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cfb5bee7a6a52939ca9224d6ac897bb669134078daa8735560897f69de4d33" +dependencies = [ + "backtrace", + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.52.0", +] + +[[package]] +name = "tokio-macros" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-util" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61e7c3654c13bcd040d4a03abee2c75b1d14a37b423cf5a813ceae1cc903ec6a" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1ed1f98e3fdc28d6d910e6737ae6ab1a93bf1985935a1193e68f93eeb68d24e" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" +dependencies = [ + "once_cell", +] + +[[package]] +name = "triomphe" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8f7726da4807b58ea5c96fdc122f80702030edc33b35aff9190a51148ccc85" +dependencies = [ + "serde", + "stable_deref_trait", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "trybuild" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dcd332a5496c026f1e14b7f3d2b7bd98e509660c04239c58b0ba38a12daded4" +dependencies = [ + "glob", + "serde", + "serde_derive", + "serde_json", + "target-triple", + "termcolor", + "toml", +] + +[[package]] +name = "twox-hash" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6db6856664807f43c17fbaf2718e2381ac1476a449aa104f5f64622defa1245" + +[[package]] +name = "typed-arena" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a" + +[[package]] +name = "typenum" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" + +[[package]] +name = "unicode-id" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10103c57044730945224467c09f71a4db0071c123a0648cc3e818913bde6b561" + +[[package]] +name = "unicode-id-start" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02aebfa694eccbbbffdd92922c7de136b9fe764396d2f10e21bce1681477cfc1" + +[[package]] +name = "unicode-ident" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicycle" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53ccbaf192caef9a758b9cd7ea2e5d98ffd0e40eb62e5e3fbaa50049df8b841f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", + "uniset", +] + +[[package]] +name = "uniset" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40789245bbff5f31eb773c9ac4ee5c4e15eab9640d975e124d6ce4c34a6410d7" + +[[package]] +name = "url" +version = "2.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8c5f0a0af699448548ad1a2fbf920fb4bee257eae39953ba95cb84891a0446a" +dependencies = [ + "getrandom", +] + +[[package]] +name = "v8" +version = "130.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c23b5c2caff00209b03a716609b275acae94b02dd3b63c4648e7232a84a8402f" +dependencies = [ + "bindgen", + "bitflags", + "fslock", + "gzip-header", + "home", + "miniz_oxide 0.7.4", + "once_cell", + "paste", + "which", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" +dependencies = [ + "cfg-if", + "once_cell", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" + +[[package]] +name = "wasm_dep_analyzer" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eeee3bdea6257cc36d756fa745a70f9d393571e47d69e0ed97581676a5369ca" +dependencies = [ + "deno_error", + "thiserror 2.0.3", +] + +[[package]] +name = "web-sys" +version = "0.3.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6488b90108c040df0fe62fa815cbdee25124641df01814dd7282749234c6112" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "which" +version = "6.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f" +dependencies = [ + "either", + "home", + "rustix", + "winsafe", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.6.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b" +dependencies = [ + "memchr", +] + +[[package]] +name = "winsafe" +version = "0.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" + +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "yoke" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40" +dependencies = [ + "serde", + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +dependencies = [ + "byteorder", + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cff3ee08c995dee1859d998dea82f7374f2826091dd9cd47def953cae446cd2e" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerovec" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] From f65f3dc0a9caedd702c82e7ee5a2b85bfc803c4d Mon Sep 17 00:00:00 2001 From: crowlkats Date: Thu, 12 Dec 2024 07:41:47 +0100 Subject: [PATCH 38/52] fix --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- core/async_cancel.rs | 2 +- core/error.rs | 13 +++++-------- core/io/resource.rs | 2 +- core/runtime/op_driver/op_results.rs | 2 +- ops/op2/README.md | 2 +- 7 files changed, 14 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f73191944..c9ad03b58 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -644,9 +644,9 @@ dependencies = [ [[package]] name = "deno_error" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17093059f04120895ee7bad790f074b1e4a0aa7c68511dbe8355ad0b092a4910" +checksum = "199c66ffd17ee1a948904d33f3d3f364573951c1f9fb3f859bfe7770bf33862a" dependencies = [ "deno_error_macro", "libc", @@ -658,9 +658,9 @@ dependencies = [ [[package]] name = "deno_error_macro" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c3a5d888391b76dc9b53e35651d2d11086fa05110beba167f08294920dd9059" +checksum = "3cd99df6ae75443907e1f959fc42ec6dcea67a7bd083e76cf23a117102c9a2ce" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 51e4a54f4..5eec5448d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,7 @@ v8 = { version = "130.0.1", default-features = false } deno_ast = { version = "=0.40.0", features = ["transpiling"] } deno_unsync = "0.4.1" deno_core_icudata = "0.74.0" -deno_error = { version = "0.5.1", features = ["serde_json", "serde", "url", "tokio"] } +deno_error = { version = "0.5.2", features = ["serde_json", "serde", "url", "tokio"] } anyhow = "1" bencher = "0.1" diff --git a/core/async_cancel.rs b/core/async_cancel.rs index 1323372f7..8e7cb1ff6 100644 --- a/core/async_cancel.rs +++ b/core/async_cancel.rs @@ -10,9 +10,9 @@ use std::io; use std::pin::Pin; use std::rc::Rc; -use crate::error::JsErrorClass; use crate::RcLike; use crate::Resource; +use deno_error::JsErrorClass; use futures::future::FusedFuture; use futures::future::Future; use futures::future::TryFuture; diff --git a/core/error.rs b/core/error.rs index cd2ee5246..bbf4f0e10 100644 --- a/core/error.rs +++ b/core/error.rs @@ -12,6 +12,7 @@ use crate::source_map::SourceMapApplication; use crate::url::Url; use crate::FastStaticString; use deno_error::builtin_classes::*; +use deno_error::JsErrorClass; use std::borrow::Cow; use std::collections::HashSet; use std::error::Error; @@ -21,10 +22,6 @@ use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write as _; -pub use deno_error; -pub use deno_error::JsError; -pub use deno_error::JsErrorClass; - /// A generic wrapper that can encapsulate any concrete error type. // TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead. pub type AnyError = anyhow::Error; @@ -246,7 +243,7 @@ fn js_class_and_message_to_exception<'s>( pub struct JsNativeError { class: &'static str, message: Cow<'static, str>, - pub source: Option>, + pub inner: Option>, } impl Display for JsNativeError { @@ -270,7 +267,7 @@ impl JsErrorClass for JsNativeError { &self, ) -> Option, Cow<'static, str>)>> { self - .source + .inner .as_ref() .and_then(|source| source.get_additional_properties()) } @@ -284,7 +281,7 @@ impl JsNativeError { JsNativeError { class, message: message.into(), - source: None, + inner: None, } } @@ -292,7 +289,7 @@ impl JsNativeError { Self { class: err.get_class(), message: err.get_message(), - source: Some(Box::new(err)), + inner: Some(Box::new(err)), } } diff --git a/core/io/resource.rs b/core/io/resource.rs index 9be32d959..7b1b9d566 100644 --- a/core/io/resource.rs +++ b/core/io/resource.rs @@ -6,7 +6,6 @@ // resources. Resources may or may not correspond to a real operating system // file descriptor (hence the different name). -use crate::error::JsErrorClass; use crate::error::JsNativeError; use crate::io::AsyncResult; use crate::io::BufMutView; @@ -14,6 +13,7 @@ use crate::io::BufView; use crate::io::WriteOutcome; use crate::ResourceHandle; use crate::ResourceHandleFd; +use deno_error::JsErrorClass; use std::any::type_name; use std::any::Any; use std::any::TypeId; diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index 2dc0a3df8..60777f937 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -1,9 +1,9 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use super::erased_future::TypeErased; use super::future_arena::FutureContextMapper; -use crate::error::JsErrorClass; use crate::OpId; use crate::PromiseId; +use deno_error::JsErrorClass; use serde::ser::SerializeStruct; use serde::Serialize; use std::borrow::Cow; diff --git a/ops/op2/README.md b/ops/op2/README.md index d955dec82..934f98813 100644 --- a/ops/op2/README.md +++ b/ops/op2/README.md @@ -18,7 +18,7 @@ buffer. ## Fallible `op`s An `op` function may be declared to return `Result` to indicate that the `op` is -fallible. The error type must implement `deno_core::error::JsErrorClass`. When +fallible. The error type must implement `deno_error::JsErrorClass`. When the function returns `Err`, an exception is thrown. ## `async` calls From c4eac5c9daed6273ac7840fc13281fa4010d2ec6 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 13 Dec 2024 13:41:31 +0100 Subject: [PATCH 39/52] clean --- Cargo.lock | 74 ++++++++++++++++++++++++++++++++++++++++++--------- core/error.rs | 27 ------------------- core/lib.rs | 1 + 3 files changed, 63 insertions(+), 39 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 06e5ab15f..804cc2c2d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -567,7 +567,7 @@ dependencies = [ "swc_visit", "swc_visit_macros", "text_lines", - "thiserror", + "thiserror 1.0.60", "unicode-width", "url", ] @@ -588,6 +588,7 @@ dependencies = [ "criterion", "deno_ast", "deno_core_icudata", + "deno_error", "deno_ops", "deno_unsync", "fastrand", @@ -606,6 +607,7 @@ dependencies = [ "smallvec", "sourcemap", "static_assertions", + "thiserror 2.0.6", "tokio", "twox-hash", "unicycle", @@ -627,6 +629,7 @@ dependencies = [ "anyhow", "deno_ast", "deno_core", + "deno_error", "futures", "pretty_assertions", "prettyplease", @@ -635,6 +638,31 @@ dependencies = [ "url", ] +[[package]] +name = "deno_error" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "199c66ffd17ee1a948904d33f3d3f364573951c1f9fb3f859bfe7770bf33862a" +dependencies = [ + "deno_error_macro", + "libc", + "serde", + "serde_json", + "tokio", + "url", +] + +[[package]] +name = "deno_error_macro" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cd99df6ae75443907e1f959fc42ec6dcea67a7bd083e76cf23a117102c9a2ce" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "deno_media_type" version = "0.1.4" @@ -660,7 +688,7 @@ dependencies = [ "strum_macros", "syn", "testing_macros", - "thiserror", + "thiserror 2.0.6", ] [[package]] @@ -772,7 +800,7 @@ dependencies = [ "rand", "sha1", "simdutf8", - "thiserror", + "thiserror 1.0.60", "tokio", "utf-8", ] @@ -1551,9 +1579,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.82" +version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ad3d49ab951a01fbaafe34f2ec74122942fe18a3f9814c3268f1bb72042131b" +checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" dependencies = [ "unicode-ident", ] @@ -1863,13 +1891,14 @@ name = "serde_v8" version = "0.234.0" dependencies = [ "bencher", + "deno_error", "num-bigint", "serde", "serde_bytes", "serde_json", "serde_v8_utilities", "smallvec", - "thiserror", + "thiserror 2.0.6", "v8", ] @@ -2406,9 +2435,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.61" +version = "2.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c993ed8ccba56ae856363b1845da7266a7cb78e1d146c8a32d54b45a8b831fc9" +checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31" dependencies = [ "proc-macro2", "quote", @@ -2461,7 +2490,16 @@ version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "579e9083ca58dd9dcf91a9923bb9054071b9ebbd800b342194c9feb0ee89fc18" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.60", +] + +[[package]] +name = "thiserror" +version = "2.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec2a1820ebd077e2b90c4df007bebf344cd394098a13c563957d0afc83ea47" +dependencies = [ + "thiserror-impl 2.0.6", ] [[package]] @@ -2475,6 +2513,17 @@ dependencies = [ "syn", ] +[[package]] +name = "thiserror-impl" +version = "2.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d65750cab40f4ff1929fb1ba509e9914eb756131cef4210da8d5d700d26f6312" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "tinytemplate" version = "1.2.1" @@ -2850,11 +2899,12 @@ checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" [[package]] name = "wasm_dep_analyzer" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f270206a91783fd90625c8bb0d8fbd459d0b1d1bf209b656f713f01ae7c04b8" +checksum = "2eeee3bdea6257cc36d756fa745a70f9d393571e47d69e0ed97581676a5369ca" dependencies = [ - "thiserror", + "deno_error", + "thiserror 2.0.6", ] [[package]] diff --git a/core/error.rs b/core/error.rs index 918f1863a..c1f243f46 100644 --- a/core/error.rs +++ b/core/error.rs @@ -321,33 +321,6 @@ impl From for JsNativeError { } } -/// A wrapper around `anyhow::Error` that implements `std::error::Error` -#[repr(transparent)] -pub struct StdAnyError(pub anyhow::Error); -impl std::fmt::Debug for StdAnyError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self.0) - } -} - -impl std::fmt::Display for StdAnyError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.0) - } -} - -impl std::error::Error for StdAnyError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - self.0.source() - } -} - -impl From for StdAnyError { - fn from(err: anyhow::Error) -> Self { - Self(err) - } -} - pub fn to_v8_error<'a>( scope: &mut v8::HandleScope<'a>, error: &impl JsErrorClass, diff --git a/core/lib.rs b/core/lib.rs index 307be2037..290518909 100644 --- a/core/lib.rs +++ b/core/lib.rs @@ -83,6 +83,7 @@ pub use crate::external::ExternalPointer; pub use crate::external::Externalizable; pub use crate::fast_string::FastStaticString; pub use crate::fast_string::FastString; +pub use crate::fast_string::FastStringV8AllocationError; pub use crate::feature_checker::FeatureChecker; pub use crate::flags::v8_set_flags; pub use crate::inspector::InspectorMsg; From 2e40c1b742451cab85d00c01efdc5832e5d04475 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Fri, 20 Dec 2024 19:15:18 +0100 Subject: [PATCH 40/52] fixes --- Cargo.lock | 5 +- Cargo.toml | 3 + core/00_infra.js | 2 +- core/async_cancel.rs | 14 +++- core/benches/ops/async.rs | 4 +- core/benches/ops/sync.rs | 2 +- core/benches/snapshot/snapshot.rs | 8 +- core/convert.rs | 23 +++-- core/error.rs | 97 +++------------------- core/examples/snapshot/src/main.rs | 4 +- core/inspector.rs | 4 +- core/io/mod.rs | 3 +- core/io/resource.rs | 26 +++--- core/modules/loaders.rs | 8 +- core/modules/map.rs | 6 +- core/modules/mod.rs | 4 +- core/modules/tests.rs | 10 +-- core/ops_builtin.rs | 13 +-- core/ops_builtin_v8.rs | 46 +++++----- core/runtime/bindings.rs | 8 +- core/runtime/jsruntime.rs | 5 +- core/runtime/op_driver/op_results.rs | 7 +- core/runtime/ops.rs | 42 +++++----- core/runtime/snapshot.rs | 6 +- core/runtime/tests/error.rs | 4 +- core/runtime/tests/misc.rs | 2 +- core/runtime/tests/ops.rs | 10 +-- testing/checkin/runner/mod.rs | 10 +-- testing/checkin/runner/ops.rs | 8 +- testing/checkin/runner/ops_error.rs | 18 ++-- testing/checkin/runner/ops_io.rs | 7 +- testing/checkin/runner/ops_worker.rs | 4 +- testing/checkin/runner/ts_module_loader.rs | 8 +- 33 files changed, 174 insertions(+), 247 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a22826fa2..602ffb178 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -641,13 +641,12 @@ dependencies = [ [[package]] name = "deno_error" version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "199c66ffd17ee1a948904d33f3d3f364573951c1f9fb3f859bfe7770bf33862a" dependencies = [ "deno_error_macro", "libc", "serde", "serde_json", + "thiserror 2.0.6", "tokio", "url", ] @@ -655,8 +654,6 @@ dependencies = [ [[package]] name = "deno_error_macro" version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cd99df6ae75443907e1f959fc42ec6dcea67a7bd083e76cf23a117102c9a2ce" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 760a642d1..21f141c7f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -93,3 +93,6 @@ codegen-units = 1 incremental = true lto = true opt-level = 'z' # Optimize for size + +[patch.crates-io] +deno_error = { path = "../deno_error" } \ No newline at end of file diff --git a/core/00_infra.js b/core/00_infra.js index bd5f478da..d6e570a4e 100644 --- a/core/00_infra.js +++ b/core/00_infra.js @@ -183,7 +183,7 @@ if (res.additional_properties) { for (const [key, value] of res.additional_properties) { - res[key] = value; + err[key] = value; } } // Strip eventLoopTick() calls from stack trace diff --git a/core/async_cancel.rs b/core/async_cancel.rs index 8e7cb1ff6..9ee7ac5c0 100644 --- a/core/async_cancel.rs +++ b/core/async_cancel.rs @@ -1,6 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use std::any::type_name; +use std::any::{type_name, Any}; use std::borrow::Cow; use std::error::Error; use std::fmt; @@ -242,6 +242,12 @@ impl From for io::Error { } } +impl From for deno_error::JsErrorBox { + fn from(value: Canceled) -> Self { + deno_error::JsErrorBox::from_err(value) + } +} + impl JsErrorClass for Canceled { fn get_class(&self) -> &'static str { let io_err: io::Error = self.to_owned().into(); @@ -255,10 +261,14 @@ impl JsErrorClass for Canceled { fn get_additional_properties( &self, - ) -> Option, Cow<'static, str>)>> { + ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> { let io_err: io::Error = self.to_owned().into(); io_err.get_additional_properties() } + + fn as_any(&self) -> &dyn Any { + self + } } mod internal { diff --git a/core/benches/ops/async.rs b/core/benches/ops/async.rs index 19282c3b7..284412fdd 100644 --- a/core/benches/ops/async.rs +++ b/core/benches/ops/async.rs @@ -1,7 +1,7 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use bencher::*; -use deno_core::error::JsNativeError; use deno_core::*; +use deno_error::JsErrorBox; use std::ffi::c_void; use tokio::runtime::Runtime; @@ -118,7 +118,7 @@ fn bench_op( ..Default::default() }); let err_mapper = - |err| JsNativeError::generic(format!("{op} test failed ({call}): {err:?}")); + |err| JsErrorBox::generic(format!("{op} test failed ({call}): {err:?}")); let args = (0..arg_count) .map(|n| format!("arg{n}")) diff --git a/core/benches/ops/sync.rs b/core/benches/ops/sync.rs index 0959a0f7f..60cb23112 100644 --- a/core/benches/ops/sync.rs +++ b/core/benches/ops/sync.rs @@ -183,7 +183,7 @@ fn bench_op( ..Default::default() }); let err_mapper = |err| { - error::JsNativeError::generic(format!("{op} test failed ({call}): {err:?}")) + error::JsErrorBox::generic(format!("{op} test failed ({call}): {err:?}")) }; let args = (0..arg_count) diff --git a/core/benches/snapshot/snapshot.rs b/core/benches/snapshot/snapshot.rs index 4bbc246eb..f6eb0c20f 100644 --- a/core/benches/snapshot/snapshot.rs +++ b/core/benches/snapshot/snapshot.rs @@ -3,7 +3,6 @@ use criterion::*; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; -use deno_core::error::JsNativeError; use deno_core::Extension; use deno_core::JsRuntime; use deno_core::JsRuntimeForSnapshot; @@ -11,6 +10,7 @@ use deno_core::ModuleCodeString; use deno_core::ModuleName; use deno_core::RuntimeOptions; use deno_core::SourceMapData; +use deno_error::JsErrorBox; use std::rc::Rc; use std::time::Duration; use std::time::Instant; @@ -64,7 +64,7 @@ deno_core::js_error_wrapper!( pub fn maybe_transpile_source( specifier: ModuleName, source: ModuleCodeString, -) -> Result<(ModuleCodeString, Option), JsNativeError> { +) -> Result<(ModuleCodeString, Option), JsErrorBox> { let media_type = MediaType::TypeScript; let parsed = deno_ast::parse_module(ParseParams { @@ -75,7 +75,7 @@ pub fn maybe_transpile_source( scope_analysis: false, maybe_syntax: None, }) - .map_err(|e| JsNativeError::from_err(JsParseDiagnostic(e)))?; + .map_err(|e| JsErrorBox::from_err(JsParseDiagnostic(e)))?; let transpiled_source = parsed .transpile( &deno_ast::TranspileOptions { @@ -88,7 +88,7 @@ pub fn maybe_transpile_source( ..Default::default() }, ) - .map_err(|e| JsNativeError::from_err(JsTranspileError(e)))? + .map_err(|e| JsErrorBox::from_err(JsTranspileError(e)))? .into_source(); Ok(( String::from_utf8(transpiled_source.source).unwrap().into(), diff --git a/core/convert.rs b/core/convert.rs index eecbc6af1..20461fb86 100644 --- a/core/convert.rs +++ b/core/convert.rs @@ -1,7 +1,7 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::JsNativeError; use crate::runtime::ops; +use deno_error::JsErrorBox; use std::convert::Infallible; /// A conversion from a rust value to a v8 value. @@ -87,16 +87,16 @@ pub trait ToV8<'a> { /// /// ```ignore /// use deno_core::FromV8; -/// use deno_core::error::JsNativeError; +/// use deno_error::JsErrorBox; /// use deno_core::convert::Smi; /// use deno_core::op2; /// /// struct Foo(i32); /// /// impl<'a> FromV8<'a> for Foo { -/// // This conversion can fail, so we use `JsNativeError` as the error type. +/// // This conversion can fail, so we use `JsErrorBox` as the error type. /// // Any error type that implements `std::error::Error` can be used here. -/// type Error = JsNativeError; +/// type Error = JsErrorBox; /// /// fn from_v8(scope: &mut v8::HandleScope<'a>, value: v8::Local<'a, v8::Value>) -> Result { /// /// We expect this value to be a `v8::Integer`, so we use the [`Smi`][deno_core::convert::Smi] wrapper type to convert it. @@ -171,16 +171,15 @@ impl<'a, T: SmallInt> ToV8<'a> for Smi { } impl<'a, T: SmallInt> FromV8<'a> for Smi { - type Error = JsNativeError; + type Error = JsErrorBox; #[inline] fn from_v8( _scope: &mut v8::HandleScope<'a>, value: v8::Local<'a, v8::Value>, ) -> Result { - let v = ops::to_i32_option(&value).ok_or_else(|| { - JsNativeError::type_error(format!("Expected {}", T::NAME)) - })?; + let v = ops::to_i32_option(&value) + .ok_or_else(|| JsErrorBox::type_error(format!("Expected {}", T::NAME)))?; Ok(Smi(T::from_i32(v))) } } @@ -241,7 +240,7 @@ impl<'a, T: Numeric> ToV8<'a> for Number { } impl<'a, T: Numeric> FromV8<'a> for Number { - type Error = JsNativeError; + type Error = JsErrorBox; #[inline] fn from_v8( _scope: &mut v8::HandleScope<'a>, @@ -249,7 +248,7 @@ impl<'a, T: Numeric> FromV8<'a> for Number { ) -> Result { T::from_value(&value) .map(Number) - .ok_or_else(|| JsNativeError::type_error(format!("Expected {}", T::NAME))) + .ok_or_else(|| JsErrorBox::type_error(format!("Expected {}", T::NAME))) } } @@ -265,7 +264,7 @@ impl<'a> ToV8<'a> for bool { } impl<'a> FromV8<'a> for bool { - type Error = JsNativeError; + type Error = JsErrorBox; #[inline] fn from_v8( _scope: &mut v8::HandleScope<'a>, @@ -274,6 +273,6 @@ impl<'a> FromV8<'a> for bool { value .try_cast::() .map(|v| v.is_true()) - .map_err(|_| JsNativeError::type_error("Expected boolean")) + .map_err(|_| JsErrorBox::type_error("Expected boolean")) } } diff --git a/core/error.rs b/core/error.rs index c1f243f46..86c1ae68d 100644 --- a/core/error.rs +++ b/core/error.rs @@ -13,6 +13,7 @@ use crate::url::Url; use crate::FastStaticString; use deno_error::builtin_classes::*; use deno_error::JsErrorClass; +use std::any::Any; use std::borrow::Cow; use std::collections::HashSet; use std::error::Error; @@ -37,7 +38,7 @@ pub enum CoreError { #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] - ExtensionTranspiler(JsNativeError), + ExtensionTranspiler(deno_error::JsErrorBox), #[error("Failed to parse {0}")] Parse(FastStaticString), #[error("Failed to execute {0}")] @@ -63,7 +64,7 @@ pub enum CoreError { specifier: String, }, #[error(transparent)] - JsNative(#[from] JsNativeError), + JsNative(#[from] deno_error::JsErrorBox), #[error(transparent)] Url(#[from] url::ParseError), #[error(transparent)] @@ -207,8 +208,12 @@ impl JsErrorClass for CoreError { fn get_additional_properties( &self, - ) -> Option, Cow<'static, str>)>> { - None // TODO + ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> { + vec![] // TODO + } + + fn as_any(&self) -> &dyn Any { + self } } @@ -239,88 +244,6 @@ fn js_class_and_message_to_exception<'s>( } } -#[derive(Debug)] -pub struct JsNativeError { - class: &'static str, - message: Cow<'static, str>, - pub inner: Option>, -} - -impl Display for JsNativeError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.message) - } -} - -impl Error for JsNativeError {} - -impl JsErrorClass for JsNativeError { - fn get_class(&self) -> &'static str { - self.class - } - - fn get_message(&self) -> Cow<'static, str> { - self.message.clone() - } - - fn get_additional_properties( - &self, - ) -> Option, Cow<'static, str>)>> { - self - .inner - .as_ref() - .and_then(|source| source.get_additional_properties()) - } -} - -impl JsNativeError { - pub fn new( - class: &'static str, - message: impl Into>, - ) -> JsNativeError { - JsNativeError { - class, - message: message.into(), - inner: None, - } - } - - pub fn from_err(err: T) -> Self { - Self { - class: err.get_class(), - message: err.get_message(), - inner: Some(Box::new(err)), - } - } - - pub fn generic(message: impl Into>) -> JsNativeError { - Self::new(GENERIC_ERROR, message) - } - - pub fn type_error(message: impl Into>) -> JsNativeError { - Self::new(TYPE_ERROR, message) - } - - pub fn range_error(message: impl Into>) -> JsNativeError { - Self::new(RANGE_ERROR, message) - } - - pub fn uri_error(message: impl Into>) -> JsNativeError { - Self::new(URI_ERROR, message) - } - - // Non-standard errors - pub fn not_supported() -> JsNativeError { - Self::new(NOT_SUPPORTED_ERROR, "The operation is not supported") - } -} - -impl From for JsNativeError { - fn from(value: crate::Canceled) -> Self { - Self::from_err(value) - } -} - pub fn to_v8_error<'a>( scope: &mut v8::HandleScope<'a>, error: &impl JsErrorClass, @@ -1145,7 +1068,7 @@ pub(crate) fn exception_to_err_result( } scope.set_microtasks_policy(v8::MicrotasksPolicy::Auto); - Err(js_error.into()) + Err(CoreError::Js(js_error)) } v8_static_strings::v8_static_strings! { diff --git a/core/examples/snapshot/src/main.rs b/core/examples/snapshot/src/main.rs index edef4fa68..8d2abb227 100644 --- a/core/examples/snapshot/src/main.rs +++ b/core/examples/snapshot/src/main.rs @@ -2,7 +2,7 @@ use std::env::current_dir; use std::rc::Rc; -use deno_core::error::AnyError; +use deno_core::anyhow; use deno_core::extension; use deno_core::op2; use deno_core::FsModuleLoader; @@ -27,7 +27,7 @@ fn op_call_rust(#[string] value: String) { extension!(runjs_extension, ops = [op_call_rust,],); -async fn run_js(file_path: &str) -> Result<(), AnyError> { +async fn run_js(file_path: &str) -> Result<(), anyhow::Error> { let cwd = current_dir()?; let main_module = deno_core::resolve_path(file_path, &cwd)?; diff --git a/core/inspector.rs b/core/inspector.rs index c6084f5e0..cd6993411 100644 --- a/core/inspector.rs +++ b/core/inspector.rs @@ -19,7 +19,7 @@ use crate::futures::task::Context; use crate::futures::task::Poll; use crate::serde_json::json; use crate::serde_json::Value; -use deno_core::error::JsNativeError; +use deno_error::JsErrorBox; use parking_lot::Mutex; use std::cell::BorrowMutError; use std::cell::RefCell; @@ -857,7 +857,7 @@ impl LocalInspectorSession { Either::Right((result, _)) => { let response = result?; if let Some(error) = response.get("error") { - return Err(JsNativeError::generic(error.to_string()).into()); + return Err(JsErrorBox::generic(error.to_string()).into()); } let result = response.get("result").unwrap().clone(); diff --git a/core/io/mod.rs b/core/io/mod.rs index 87999ade0..189123688 100644 --- a/core/io/mod.rs +++ b/core/io/mod.rs @@ -15,7 +15,6 @@ mod resource; mod resource_handle; mod resource_table; -use crate::error::JsNativeError; pub use buffer_strategy::AdaptiveBufferStrategy; pub use buffers::BufMutView; pub use buffers::BufView; @@ -29,7 +28,7 @@ pub use resource_table::ResourceTable; /// Returned by resource shutdown methods pub type AsyncResult = - Pin>>>; + Pin>>>; pub enum WriteOutcome { Partial { nwritten: usize, view: BufView }, diff --git a/core/io/resource.rs b/core/io/resource.rs index 7b1b9d566..59a252105 100644 --- a/core/io/resource.rs +++ b/core/io/resource.rs @@ -6,13 +6,13 @@ // resources. Resources may or may not correspond to a real operating system // file descriptor (hence the different name). -use crate::error::JsNativeError; use crate::io::AsyncResult; use crate::io::BufMutView; use crate::io::BufView; use crate::io::WriteOutcome; use crate::ResourceHandle; use crate::ResourceHandleFd; +use deno_error::JsErrorBox; use deno_error::JsErrorClass; use std::any::type_name; use std::any::Any; @@ -85,7 +85,7 @@ pub trait Resource: Any + 'static { /// implement `read_byob()`. fn read(self: Rc, limit: usize) -> AsyncResult { _ = limit; - Box::pin(futures::future::err(JsNativeError::not_supported())) + Box::pin(futures::future::err(JsErrorBox::not_supported())) } /// Read a single chunk of data from the resource into the provided `BufMutView`. @@ -111,7 +111,7 @@ pub trait Resource: Any + 'static { /// Write an error state to this resource, if the resource supports it. fn write_error(self: Rc, _error: &dyn JsErrorClass) -> AsyncResult<()> { - Box::pin(futures::future::err(JsNativeError::not_supported())) + Box::pin(futures::future::err(JsErrorBox::not_supported())) } /// Write a single chunk of data to the resource. The operation may not be @@ -123,7 +123,7 @@ pub trait Resource: Any + 'static { /// with a "not supported" error. fn write(self: Rc, buf: BufView) -> AsyncResult { _ = buf; - Box::pin(futures::future::err(JsNativeError::not_supported())) + Box::pin(futures::future::err(JsErrorBox::not_supported())) } /// Write an entire chunk of data to the resource. Unlike `write()`, this will @@ -158,15 +158,15 @@ pub trait Resource: Any + 'static { fn read_byob_sync( self: Rc, data: &mut [u8], - ) -> Result { + ) -> Result { _ = data; - Err(JsNativeError::not_supported()) + Err(JsErrorBox::not_supported()) } /// The same as [`write()`][Resource::write], but synchronous. - fn write_sync(self: Rc, data: &[u8]) -> Result { + fn write_sync(self: Rc, data: &[u8]) -> Result { _ = data; - Err(JsNativeError::not_supported()) + Err(JsErrorBox::not_supported()) } /// The shutdown method can be used to asynchronously close the resource. It @@ -175,7 +175,7 @@ pub trait Resource: Any + 'static { /// If this method is not implemented, the default implementation will error /// with a "not supported" error. fn shutdown(self: Rc) -> AsyncResult<()> { - Box::pin(futures::future::err(JsNativeError::not_supported())) + Box::pin(futures::future::err(JsErrorBox::not_supported())) } /// Resources may implement the `close()` trait method if they need to do @@ -231,7 +231,7 @@ macro_rules! impl_readable_byob { ) -> AsyncResult<$crate::BufView> { ::std::boxed::Box::pin(async move { let mut vec = ::std::vec![0; limit]; - let nread = self.read(&mut vec).await.map_err(::deno_core::error::JsNativeError::from_err)?; + let nread = self.read(&mut vec).await.map_err(::deno_error::JsErrorBox::from_err)?; if nread != vec.len() { vec.truncate(nread); } @@ -245,7 +245,7 @@ macro_rules! impl_readable_byob { mut buf: $crate::BufMutView, ) -> AsyncResult<(::core::primitive::usize, $crate::BufMutView)> { ::std::boxed::Box::pin(async move { - let nread = self.read(buf.as_mut()).await.map_err(::deno_core::error::JsNativeError::from_err)?; + let nread = self.read(buf.as_mut()).await.map_err(::deno_error::JsErrorBox::from_err)?; ::std::result::Result::Ok((nread, buf)) }) } @@ -263,7 +263,7 @@ macro_rules! impl_writable { let nwritten = self .write(&view) .await - .map_err(::deno_core::error::JsNativeError::from_err)?; + .map_err(::deno_error::JsErrorBox::from_err)?; ::std::result::Result::Ok($crate::WriteOutcome::Partial { nwritten, view, @@ -280,7 +280,7 @@ macro_rules! impl_writable { self .write_all(&view) .await - .map_err(::deno_core::error::JsNativeError::from_err)?; + .map_err(::deno_error::JsErrorBox::from_err)?; ::std::result::Result::Ok(()) }) } diff --git a/core/modules/loaders.rs b/core/modules/loaders.rs index cd3cf1ae1..62d3f4847 100644 --- a/core/modules/loaders.rs +++ b/core/modules/loaders.rs @@ -1,5 +1,4 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::JsNativeError; use crate::module_specifier::ModuleSpecifier; use crate::modules::IntoModuleCodeString; use crate::modules::ModuleCodeString; @@ -11,6 +10,7 @@ use crate::modules::RequestedModuleType; use crate::modules::ResolutionKind; use crate::resolve_import; use crate::ModuleSourceCode; +use deno_error::JsErrorBox; use anyhow::Context; use deno_core::error::CoreError; @@ -75,8 +75,8 @@ impl From for ModuleLoaderError { ModuleLoaderError::Core(CoreError::Io(err)) } } -impl From for ModuleLoaderError { - fn from(err: JsNativeError) -> Self { +impl From for ModuleLoaderError { + fn from(err: JsErrorBox) -> Self { ModuleLoaderError::Core(CoreError::JsNative(err)) } } @@ -406,7 +406,7 @@ impl ModuleLoader for FsModuleLoader { let module_specifier = module_specifier.clone(); let fut = async move { let path = module_specifier.to_file_path().map_err(|_| { - JsNativeError::generic(format!( + JsErrorBox::generic(format!( "Provided module specifier \"{module_specifier}\" is not a file URL." )) })?; diff --git a/core/modules/map.rs b/core/modules/map.rs index f4718cddf..fd66fb844 100644 --- a/core/modules/map.rs +++ b/core/modules/map.rs @@ -6,7 +6,6 @@ use super::ModuleConcreteError; use crate::ascii_str; use crate::error::exception_to_err_result; use crate::error::JsError; -use crate::error::JsNativeError; use crate::modules::get_requested_module_type_from_attributes; use crate::modules::parse_import_attributes; use crate::modules::recursive_load::RecursiveModuleLoad; @@ -32,6 +31,7 @@ use crate::ModuleSource; use crate::ModuleSourceCode; use crate::ModuleSpecifier; use capacity_builder::StringBuilder; +use deno_error::JsErrorBox; use futures::future::FutureExt; use futures::stream::FuturesUnordered; use futures::stream::StreamFuture; @@ -886,7 +886,7 @@ impl ModuleMap { crate::error::throw_js_error_class( scope, - &JsNativeError::type_error(format!( + &JsErrorBox::type_error(format!( r#"Cannot resolve module "{specifier_str}" from "{referrer_name}""# )), ); @@ -915,7 +915,7 @@ impl ModuleMap { referrer }; let msg = format!("Importing ext: modules is only allowed from ext: and node: modules. Tried to import {} from {}", specifier, referrer); - return Err(JsNativeError::type_error(msg).into()); + return Err(JsErrorBox::type_error(msg).into()); } self diff --git a/core/modules/mod.rs b/core/modules/mod.rs index 10aa29258..c04a4ed61 100644 --- a/core/modules/mod.rs +++ b/core/modules/mod.rs @@ -210,7 +210,7 @@ pub type CustomModuleEvaluationCb = Box< Cow<'_, str>, &FastString, ModuleSourceCode, - ) -> Result, + ) -> Result, >; /// A callback to get the code cache for a script. @@ -219,7 +219,7 @@ pub type EvalContextGetCodeCacheCb = Box< dyn Fn( &Url, &v8::String, - ) -> Result, + ) -> Result, >; /// Callback when the code cache is ready. diff --git a/core/modules/tests.rs b/core/modules/tests.rs index 29f4718e0..5d65ba13c 100644 --- a/core/modules/tests.rs +++ b/core/modules/tests.rs @@ -3,7 +3,6 @@ #![allow(clippy::print_stderr)] use crate::ascii_str; -use crate::error::JsNativeError; use crate::error::{exception_to_err_result, CoreError}; use crate::modules::loaders::ModuleLoadEventCounts; use crate::modules::loaders::TestingModuleLoader; @@ -29,6 +28,7 @@ use crate::ModuleType; use crate::ResolutionKind; use crate::RuntimeOptions; use anyhow::anyhow; +use deno_error::JsErrorBox; use deno_ops::op2; use futures::future::poll_fn; use futures::future::FutureExt; @@ -794,9 +794,9 @@ fn test_custom_module_type_callback_synthetic() { module_type: Cow<'_, str>, _module_name: &FastString, module_code: ModuleSourceCode, - ) -> Result { + ) -> Result { if module_type != "bytes" { - return Err(JsNativeError::generic(format!( + return Err(JsErrorBox::generic(format!( "Can't load '{}' module", module_type ))); @@ -878,9 +878,9 @@ fn test_custom_module_type_callback_computed() { module_type: Cow<'_, str>, module_name: &FastString, module_code: ModuleSourceCode, - ) -> Result { + ) -> Result { if module_type != "foobar" { - return Err(JsNativeError::generic(format!( + return Err(JsErrorBox::generic(format!( "Can't load '{}' module", module_type ))); diff --git a/core/ops_builtin.rs b/core/ops_builtin.rs index ec5cff1b0..08a5f2275 100644 --- a/core/ops_builtin.rs +++ b/core/ops_builtin.rs @@ -1,7 +1,7 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +use crate::error::exception_to_err_result; use crate::error::format_file_name; use crate::error::OpError; -use crate::error::{exception_to_err_result, JsNativeError}; use crate::io::AdaptiveBufferStrategy; use crate::io::BufMutView; use crate::io::BufView; @@ -19,6 +19,7 @@ use crate::OpDecl; use crate::OpState; use crate::Resource; use bytes::BytesMut; +use deno_error::JsErrorBox; use futures::StreamExt; use serde_v8::ByteString; use std::cell::RefCell; @@ -175,13 +176,13 @@ pub async fn op_void_async() {} #[allow(clippy::unused_async)] #[op2(async)] pub async fn op_error_async() -> Result<(), OpError> { - Err(JsNativeError::generic("error").into()) + Err(JsErrorBox::generic("error").into()) } #[allow(clippy::unused_async)] #[op2(async(deferred), fast)] pub async fn op_error_async_deferred() -> Result<(), OpError> { - Err(JsNativeError::generic("error").into()) + Err(JsErrorBox::generic("error").into()) } #[allow(clippy::unused_async)] @@ -373,7 +374,7 @@ async fn op_write_type_error( ) -> Result<(), OpError> { let resource = state.borrow().resource_table.get_any(rid)?; resource - .write_error(&super::error::JsNativeError::type_error(error)) + .write_error(&deno_error::JsErrorBox::type_error(error)) .await?; Ok(()) } @@ -468,7 +469,7 @@ async fn do_load_job<'s>( | v8::ModuleStatus::Instantiating | v8::ModuleStatus::Evaluating => { return Err( - JsNativeError::generic(format!( + JsErrorBox::generic(format!( "Cannot require() ES Module {specifier} in a cycle." )) .into(), @@ -572,7 +573,7 @@ fn op_import_sync<'s>( | v8::ModuleStatus::Instantiating | v8::ModuleStatus::Evaluating => { return Err( - JsNativeError::generic(format!( + JsErrorBox::generic(format!( "Cannot require() ES Module {specifier} in a cycle." )) .into(), diff --git a/core/ops_builtin_v8.rs b/core/ops_builtin_v8.rs index 3c65098cd..1090623ad 100644 --- a/core/ops_builtin_v8.rs +++ b/core/ops_builtin_v8.rs @@ -1,7 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::error::is_instance_of_error; use crate::error::JsError; -use crate::error::JsNativeError; use crate::error::OpError; use crate::modules::script_origin; use crate::op2; @@ -14,6 +13,7 @@ use crate::stats::RuntimeActivityType; use crate::JsBuffer; use crate::JsRuntime; use crate::OpState; +use deno_error::JsErrorBox; use serde::Deserialize; use serde::Serialize; use std::cell::RefCell; @@ -268,7 +268,7 @@ pub fn op_eval_context<'a>( let state = JsRuntime::state_from(scope); let tc_scope = &mut v8::TryCatch::new(scope); let source = v8::Local::::try_from(source) - .map_err(|_| JsNativeError::type_error("Invalid source"))?; + .map_err(|_| JsErrorBox::type_error("Invalid source"))?; let specifier = resolve_url(&specifier)?; let specifier_v8 = v8::String::new(tc_scope, specifier.as_str()).unwrap(); let host_defined_options = match host_defined_options { @@ -346,7 +346,7 @@ pub fn op_eval_context<'a>( if let Some(cb) = state.eval_context_code_cache_ready_cb.as_ref() { let unbound_script = script.get_unbound_script(tc_scope); let code_cache = unbound_script.create_code_cache().ok_or_else(|| { - JsNativeError::type_error( + JsErrorBox::type_error( "Unable to get code cache from unbound module script", ) })?; @@ -382,7 +382,7 @@ pub fn op_encode<'a>( text: v8::Local<'a, v8::Value>, ) -> Result, OpError> { let text = v8::Local::::try_from(text) - .map_err(|_| JsNativeError::type_error("Invalid argument"))?; + .map_err(|_| JsErrorBox::type_error("Invalid argument"))?; let text_str = serde_v8::to_utf8(text, scope); let bytes = text_str.into_bytes(); let len = bytes.len(); @@ -418,7 +418,7 @@ pub fn op_decode<'a>( // - https://github.com/v8/v8/blob/d68fb4733e39525f9ff0a9222107c02c28096e2a/include/v8.h#L3277-L3278 match v8::String::new_from_utf8(scope, buf, v8::NewStringType::Normal) { Some(text) => Ok(text), - None => Err(JsNativeError::range_error("string too long").into()), + None => Err(JsErrorBox::range_error("string too long").into()), } } @@ -602,21 +602,21 @@ pub fn op_serialize( let error_callback = match error_callback { Some(cb) => Some( v8::Local::::try_from(cb) - .map_err(|_| JsNativeError::type_error("Invalid error callback"))?, + .map_err(|_| JsErrorBox::type_error("Invalid error callback"))?, ), None => None, }; let host_objects = match host_objects { Some(value) => Some( v8::Local::::try_from(value) - .map_err(|_| JsNativeError::type_error("hostObjects not an array"))?, + .map_err(|_| JsErrorBox::type_error("hostObjects not an array"))?, ), None => None, }; let transferred_array_buffers = match transferred_array_buffers { Some(value) => { Some(v8::Local::::try_from(value).map_err(|_| { - JsNativeError::type_error("transferredArrayBuffers not an array") + JsErrorBox::type_error("transferredArrayBuffers not an array") })?) } None => None, @@ -641,7 +641,7 @@ pub fn op_serialize( let i = v8::Number::new(scope, index as f64).into(); let buf = transferred_array_buffers.get(scope, i).unwrap(); let buf = v8::Local::::try_from(buf).map_err(|_| { - JsNativeError::type_error( + JsErrorBox::type_error( "item in transferredArrayBuffers not an ArrayBuffer", ) })?; @@ -649,7 +649,7 @@ pub fn op_serialize( { if !buf.is_detachable() { return Err( - JsNativeError::type_error( + JsErrorBox::type_error( "item in transferredArrayBuffers is not transferable", ) .into(), @@ -658,7 +658,7 @@ pub fn op_serialize( if buf.was_detached() { return Err( - JsNativeError::new( + JsErrorBox::new( "DOMExceptionOperationError", format!("ArrayBuffer at index {index} is already detached"), ) @@ -686,7 +686,7 @@ pub fn op_serialize( let vector = value_serializer.release(); Ok(vector) } else { - Err(JsNativeError::type_error("Failed to serialize response").into()) + Err(JsErrorBox::type_error("Failed to serialize response").into()) } } @@ -701,14 +701,14 @@ pub fn op_deserialize<'a>( let host_objects = match host_objects { Some(value) => Some( v8::Local::::try_from(value) - .map_err(|_| JsNativeError::type_error("hostObjects not an array"))?, + .map_err(|_| JsErrorBox::type_error("hostObjects not an array"))?, ), None => None, }; let transferred_array_buffers = match transferred_array_buffers { Some(value) => { Some(v8::Local::::try_from(value).map_err(|_| { - JsNativeError::type_error("transferredArrayBuffers not an array") + JsErrorBox::type_error("transferredArrayBuffers not an array") })?) } None => None, @@ -726,9 +726,7 @@ pub fn op_deserialize<'a>( .read_header(scope.get_current_context()) .unwrap_or_default(); if !parsed_header { - return Err( - JsNativeError::range_error("could not deserialize value").into(), - ); + return Err(JsErrorBox::range_error("could not deserialize value").into()); } if let Some(transferred_array_buffers) = transferred_array_buffers { @@ -741,7 +739,7 @@ pub fn op_deserialize<'a>( Some(id) => id as u32, None => { return Err( - JsNativeError::type_error( + JsErrorBox::type_error( "item in transferredArrayBuffers not number", ) .into(), @@ -754,7 +752,7 @@ pub fn op_deserialize<'a>( value_deserializer.transfer_array_buffer(id, array_buffer); transferred_array_buffers.set(scope, i, array_buffer.into()); } else { - return Err(JsNativeError::type_error( + return Err(JsErrorBox::type_error( "transferred array buffer not present in shared_array_buffer_store", ).into()); } @@ -765,9 +763,7 @@ pub fn op_deserialize<'a>( let value = value_deserializer.read_value(scope.get_current_context()); match value { Some(deserialized) => Ok(deserialized), - None => { - Err(JsNativeError::range_error("could not deserialize value").into()) - } + None => Err(JsErrorBox::range_error("could not deserialize value").into()), } } @@ -956,10 +952,8 @@ pub fn op_set_wasm_streaming_callback( // callback in a JsRuntimeState slot. if context_state_rc.js_wasm_streaming_cb.borrow().is_some() { return Err( - JsNativeError::type_error( - "op_set_wasm_streaming_callback already called", - ) - .into(), + JsErrorBox::type_error("op_set_wasm_streaming_callback already called") + .into(), ); } *context_state_rc.js_wasm_streaming_cb.borrow_mut() = Some(Rc::new(cb)); diff --git a/core/runtime/bindings.rs b/core/runtime/bindings.rs index bc171e046..31f084fc8 100644 --- a/core/runtime/bindings.rs +++ b/core/runtime/bindings.rs @@ -15,7 +15,6 @@ use crate::error::callsite_fns; use crate::error::has_call_site; use crate::error::is_instance_of_error; use crate::error::CoreError; -use crate::error::JsNativeError; use crate::error::JsStackFrame; use crate::extension_set::LoadedSources; use crate::modules::get_requested_module_type_from_attributes; @@ -32,6 +31,7 @@ use crate::FastStaticString; use crate::FastString; use crate::JsRuntime; use crate::ModuleType; +use deno_error::JsErrorBox; pub(crate) fn create_external_references( ops: &[OpCtx], @@ -759,7 +759,7 @@ fn import_meta_resolve( if args.length() > 1 { return crate::error::throw_js_error_class( scope, - &JsNativeError::type_error("Invalid arguments"), + &JsErrorBox::type_error("Invalid arguments"), ); } @@ -767,7 +767,7 @@ fn import_meta_resolve( if maybe_arg_str.is_none() { return crate::error::throw_js_error_class( scope, - &JsNativeError::type_error("Invalid arguments"), + &JsErrorBox::type_error("Invalid arguments"), ); } let specifier = maybe_arg_str.unwrap(); @@ -903,7 +903,7 @@ fn call_console( { return crate::error::throw_js_error_class( scope, - &JsNativeError::type_error("Invalid arguments"), + &JsErrorBox::type_error("Invalid arguments"), ); } diff --git a/core/runtime/jsruntime.rs b/core/runtime/jsruntime.rs index 832e9e1af..262dc5f47 100644 --- a/core/runtime/jsruntime.rs +++ b/core/runtime/jsruntime.rs @@ -14,9 +14,9 @@ use super::SnapshottedData; use crate::ascii_str; use crate::ascii_str_include; use crate::cppgc::FunctionTemplateData; +use crate::error::exception_to_err_result; use crate::error::CoreError; use crate::error::JsError; -use crate::error::{exception_to_err_result, JsNativeError}; use crate::extension_set; use crate::extension_set::LoadedSources; use crate::extensions::GlobalObjectMiddlewareFn; @@ -59,6 +59,7 @@ use crate::OpMetadata; use crate::OpMetricsEvent; use crate::OpStackTraceCallback; use crate::OpState; +use deno_error::JsErrorBox; use futures::future::poll_fn; use futures::task::AtomicWaker; use futures::Future; @@ -91,7 +92,7 @@ pub type ExtensionTranspiler = dyn Fn( ModuleName, ModuleCodeString, - ) -> Result<(ModuleCodeString, Option), JsNativeError>; + ) -> Result<(ModuleCodeString, Option), JsErrorBox>; /// Objects that need to live as long as the isolate #[derive(Default)] diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index 60777f937..39cee2ac8 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -6,6 +6,7 @@ use crate::PromiseId; use deno_error::JsErrorClass; use serde::ser::SerializeStruct; use serde::Serialize; +use std::any::Any; use std::borrow::Cow; use std::error::Error; @@ -314,7 +315,11 @@ impl JsErrorClass for OpErrorWrapper { fn get_additional_properties( &self, - ) -> Option, Cow<'static, str>)>> { + ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> { self.0 .0.get_additional_properties() } + + fn as_any(&self) -> &dyn Any { + self.0 .0.as_any() + } } diff --git a/core/runtime/ops.rs b/core/runtime/ops.rs index 9c9b4b4f1..9ece3c3e7 100644 --- a/core/runtime/ops.rs +++ b/core/runtime/ops.rs @@ -539,7 +539,6 @@ mod tests { use crate::convert::Number; use crate::convert::Smi; use crate::error::CoreError; - use crate::error::JsNativeError; use crate::error::OpError; use crate::external; use crate::external::ExternalPointer; @@ -552,6 +551,7 @@ mod tests { use crate::RuntimeOptions; use crate::ToV8; use bytes::BytesMut; + use deno_error::JsErrorBox; use futures::Future; use serde::Deserialize; use serde::Serialize; @@ -689,9 +689,8 @@ mod tests { extensions: vec![testing::init_ops_and_esm()], ..Default::default() }); - let err_mapper = |err| { - JsNativeError::generic(format!("{op} test failed ({test}): {err:?}")) - }; + let err_mapper = + |err| JsErrorBox::generic(format!("{op} test failed ({test}): {err:?}")); runtime .execute_script( "", @@ -725,7 +724,7 @@ mod tests { ), )?; if FAIL.with(|b| b.get()) { - Err(JsNativeError::generic(format!("{op} test failed ({test})")).into()) + Err(JsErrorBox::generic(format!("{op} test failed ({test})")).into()) } else { Ok(()) } @@ -741,9 +740,8 @@ mod tests { extensions: vec![testing::init_ops_and_esm()], ..Default::default() }); - let err_mapper = |err| { - JsNativeError::generic(format!("{op} test failed ({test}): {err:?}")) - }; + let err_mapper = + |err| JsErrorBox::generic(format!("{op} test failed ({test}): {err:?}")); runtime .execute_script( "", @@ -781,7 +779,7 @@ mod tests { runtime.run_event_loop(Default::default()).await?; if FAIL.with(|b| b.get()) { - Err(JsNativeError::generic(format!("{op} test failed ({test})")).into()) + Err(JsErrorBox::generic(format!("{op} test failed ({test})")).into()) } else { Ok(()) } @@ -890,7 +888,7 @@ mod tests { new }); if count > 5000 { - Err(JsNativeError::generic("failed!!!").into()) + Err(JsErrorBox::generic("failed!!!").into()) } else { Ok(()) } @@ -898,7 +896,7 @@ mod tests { #[op2(fast)] pub fn op_test_result_void_err() -> Result<(), OpError> { - Err(JsNativeError::generic("failed!!!").into()) + Err(JsErrorBox::generic("failed!!!").into()) } #[allow(clippy::unnecessary_wraps)] @@ -943,7 +941,7 @@ mod tests { #[op2(fast)] pub fn op_test_result_primitive_err() -> Result { - Err(JsNativeError::generic("failed!!!").into()) + Err(JsErrorBox::generic("failed!!!").into()) } #[allow(clippy::unnecessary_wraps)] @@ -978,7 +976,7 @@ mod tests { if b { Ok(true) } else { - Err(JsNativeError::generic("false!!!").into()) + Err(JsErrorBox::generic("false!!!").into()) } } @@ -1013,7 +1011,7 @@ mod tests { if a + b >= 0. { Ok(a + b) } else { - Err(JsNativeError::generic("negative!!!").into()) + Err(JsErrorBox::generic("negative!!!").into()) } } @@ -1325,7 +1323,7 @@ mod tests { let key = v8::String::new(scope, "key").unwrap().into(); o.get(scope, key) .filter(|v| !v.is_null_or_undefined()) - .ok_or(JsNativeError::generic("error!!!").into()) + .ok_or(JsErrorBox::generic("error!!!").into()) } #[tokio::test] @@ -2174,7 +2172,7 @@ mod tests { #[op2(async)] pub async fn op_async_sleep_error() -> Result<(), OpError> { tokio::time::sleep(Duration::from_millis(500)).await; - Err(JsNativeError::generic("whoops").into()) + Err(JsErrorBox::generic("whoops").into()) } #[tokio::test] @@ -2196,7 +2194,7 @@ mod tests { #[op2(async(deferred), fast)] pub async fn op_async_deferred_error() -> Result<(), OpError> { - Err(JsNativeError::generic("whoops").into()) + Err(JsErrorBox::generic("whoops").into()) } #[tokio::test] @@ -2224,7 +2222,7 @@ mod tests { #[op2(async(lazy), fast)] pub async fn op_async_lazy_error() -> Result<(), OpError> { - Err(JsNativeError::generic("whoops").into()) + Err(JsErrorBox::generic("whoops").into()) } #[tokio::test] @@ -2251,15 +2249,15 @@ mod tests { mode: u8, ) -> Result>, OpError> { if mode == 0 { - return Err(JsNativeError::generic("early exit").into()); + return Err(JsErrorBox::generic("early exit").into()); } Ok(async move { if mode == 1 { - return Err(JsNativeError::generic("early async exit").into()); + return Err(JsErrorBox::generic("early async exit").into()); } tokio::time::sleep(Duration::from_millis(500)).await; if mode == 2 { - return Err(JsNativeError::generic("late async exit").into()); + return Err(JsErrorBox::generic("late async exit").into()); } Ok(()) }) @@ -2459,7 +2457,7 @@ mod tests { } impl<'a> FromV8<'a> for Bool { - type Error = JsNativeError; + type Error = JsErrorBox; fn from_v8( scope: &mut v8::HandleScope<'a>, diff --git a/core/runtime/snapshot.rs b/core/runtime/snapshot.rs index a5e5eb0ea..f487c5f32 100644 --- a/core/runtime/snapshot.rs +++ b/core/runtime/snapshot.rs @@ -1,10 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use crate::error::CoreError; -use crate::modules::ModuleMapSnapshotData; -use crate::Extension; -use crate::JsRuntimeForSnapshot; -use crate::RuntimeOptions; use serde::Deserialize; use serde::Serialize; use std::collections::HashMap; @@ -14,6 +9,7 @@ use std::rc::Rc; use std::time::Instant; use crate::cppgc::FunctionTemplateSnapshotData; +use crate::error::CoreError; use crate::modules::ModuleMapSnapshotData; use crate::Extension; use crate::JsRuntimeForSnapshot; diff --git a/core/runtime/tests/error.rs b/core/runtime/tests/error.rs index 1c4bdb291..ee0744bec 100644 --- a/core/runtime/tests/error.rs +++ b/core/runtime/tests/error.rs @@ -1,10 +1,10 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. use crate::error::CoreError; -use crate::error::JsNativeError; use crate::error::OpError; use crate::op2; use crate::JsRuntime; use crate::RuntimeOptions; +use deno_error::JsErrorBox; use futures::future::poll_fn; use std::task::Poll; @@ -12,7 +12,7 @@ use std::task::Poll; async fn test_error_builder() { #[op2(fast)] fn op_err() -> Result<(), OpError> { - Err(JsNativeError::new("DOMExceptionOperationError", "abc").into()) + Err(JsErrorBox::new("DOMExceptionOperationError", "abc").into()) } deno_core::extension!(test_ext, ops = [op_err]); diff --git a/core/runtime/tests/misc.rs b/core/runtime/tests/misc.rs index 8b70500f6..bd35732e8 100644 --- a/core/runtime/tests/misc.rs +++ b/core/runtime/tests/misc.rs @@ -981,7 +981,7 @@ async fn test_dynamic_import_module_error_stack() { #[op2(async)] async fn op_async_error() -> Result<(), OpError> { tokio::time::sleep(std::time::Duration::from_millis(1)).await; - Err(error::JsNativeError::type_error("foo").into()) + Err(deno_error::JsErrorBox::type_error("foo").into()) } deno_core::extension!(test_ext, ops = [op_async_error]); let loader = StaticModuleLoader::new([ diff --git a/core/runtime/tests/ops.rs b/core/runtime/tests/ops.rs index 9a39615b0..d6ffb2033 100644 --- a/core/runtime/tests/ops.rs +++ b/core/runtime/tests/ops.rs @@ -2,7 +2,7 @@ #![allow(clippy::print_stdout, clippy::print_stderr, clippy::unused_async)] -use crate::error::JsNativeError; +use deno_error::JsErrorBox; use crate::error::OpError; use crate::extensions::OpDecl; use crate::modules::StaticModuleLoader; @@ -542,7 +542,7 @@ pub async fn op_async() { #[allow(unreachable_code)] pub fn op_async_impl_future_error() -> Result, OpError> { - return Err(JsNativeError::generic("dead").into()); + return Err(JsErrorBox::generic("dead").into()); Ok(async {}) } @@ -556,13 +556,13 @@ pub async fn op_async_yield() { pub async fn op_async_yield_error() -> Result<(), OpError> { tokio::task::yield_now().await; println!("op_async_yield_error!"); - Err(JsNativeError::generic("dead").into()) + Err(JsErrorBox::generic("dead").into()) } #[op2(async)] pub async fn op_async_error() -> Result<(), OpError> { println!("op_async_error!"); - Err(JsNativeError::generic("dead").into()) + Err(JsErrorBox::generic("dead").into()) } #[op2(async(deferred), fast)] @@ -582,7 +582,7 @@ pub fn op_sync() { #[op2(fast)] pub fn op_sync_error() -> Result<(), OpError> { - Err(JsNativeError::generic("Always fails").into()) + Err(JsErrorBox::generic("Always fails").into()) } #[op2(fast)] diff --git a/testing/checkin/runner/mod.rs b/testing/checkin/runner/mod.rs index d567a174c..0026a5298 100644 --- a/testing/checkin/runner/mod.rs +++ b/testing/checkin/runner/mod.rs @@ -3,7 +3,6 @@ use self::ops_worker::worker_create; use self::ops_worker::WorkerCloseWatcher; use self::ops_worker::WorkerHostSide; use self::ts_module_loader::maybe_transpile_source; -use deno_core::error::JsNativeError; use deno_core::v8; use deno_core::CrossIsolateStore; use deno_core::CustomModuleEvaluationKind; @@ -13,6 +12,7 @@ use deno_core::ImportAssertionsSupport; use deno_core::JsRuntime; use deno_core::ModuleSourceCode; use deno_core::RuntimeOptions; +use deno_error::JsErrorBox; use futures::Future; use std::any::Any; use std::any::TypeId; @@ -178,11 +178,11 @@ fn custom_module_evaluation_cb( module_type: Cow<'_, str>, module_name: &FastString, code: ModuleSourceCode, -) -> Result { +) -> Result { match &*module_type { "bytes" => Ok(bytes_module(scope, code)), "text" => text_module(scope, module_name, code), - _ => Err(JsNativeError::generic(format!( + _ => Err(JsErrorBox::generic(format!( "Can't import {:?} because of unknown module type {}", module_name, module_type ))), @@ -211,14 +211,14 @@ fn text_module( scope: &mut v8::HandleScope, module_name: &FastString, code: ModuleSourceCode, -) -> Result { +) -> Result { // FsModuleLoader always returns bytes. let ModuleSourceCode::Bytes(buf) = code else { unreachable!() }; let code = std::str::from_utf8(buf.as_bytes()).map_err(|e| { - JsNativeError::generic(format!( + JsErrorBox::generic(format!( "Can't convert {module_name:?} source code to string: {e}" )) })?; diff --git a/testing/checkin/runner/ops.rs b/testing/checkin/runner/ops.rs index 5d20248ad..2c421e726 100644 --- a/testing/checkin/runner/ops.rs +++ b/testing/checkin/runner/ops.rs @@ -2,7 +2,6 @@ use std::cell::RefCell; use std::rc::Rc; -use deno_core::error::JsNativeError; use deno_core::op2; use deno_core::stats::RuntimeActivityDiff; use deno_core::stats::RuntimeActivitySnapshot; @@ -12,6 +11,7 @@ use deno_core::stats::RuntimeActivityStatsFilter; use deno_core::v8; use deno_core::GarbageCollected; use deno_core::OpState; +use deno_error::JsErrorBox; use super::extensions::SomeType; use super::Output; @@ -109,7 +109,7 @@ impl DOMPoint { fn from_point_inner( scope: &mut v8::HandleScope, other: v8::Local, - ) -> Result { + ) -> Result { fn get( scope: &mut v8::HandleScope, other: v8::Local, @@ -154,7 +154,7 @@ impl DOMPoint { fn from_point( scope: &mut v8::HandleScope, other: v8::Local, - ) -> Result { + ) -> Result { DOMPoint::from_point_inner(scope, other) } @@ -164,7 +164,7 @@ impl DOMPoint { &self, scope: &mut v8::HandleScope, other: v8::Local, - ) -> Result { + ) -> Result { DOMPoint::from_point_inner(scope, other) } diff --git a/testing/checkin/runner/ops_error.rs b/testing/checkin/runner/ops_error.rs index 96b671839..ebbdf30a2 100644 --- a/testing/checkin/runner/ops_error.rs +++ b/testing/checkin/runner/ops_error.rs @@ -1,25 +1,25 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use deno_core::error::JsNativeError; use deno_core::op2; +use deno_error::JsErrorBox; #[op2(async)] -pub async fn op_async_throw_error_eager() -> Result<(), JsNativeError> { - Err(JsNativeError::type_error("Error")) +pub async fn op_async_throw_error_eager() -> Result<(), JsErrorBox> { + Err(JsErrorBox::type_error("Error")) } #[op2(async(deferred), fast)] -pub async fn op_async_throw_error_deferred() -> Result<(), JsNativeError> { - Err(JsNativeError::type_error("Error")) +pub async fn op_async_throw_error_deferred() -> Result<(), JsErrorBox> { + Err(JsErrorBox::type_error("Error")) } #[op2(async(lazy), fast)] -pub async fn op_async_throw_error_lazy() -> Result<(), JsNativeError> { - Err(JsNativeError::type_error("Error")) +pub async fn op_async_throw_error_lazy() -> Result<(), JsErrorBox> { + Err(JsErrorBox::type_error("Error")) } #[op2(fast)] pub fn op_error_custom_sync( #[string] message: String, -) -> Result<(), JsNativeError> { - Err(JsNativeError::generic(message)) +) -> Result<(), JsErrorBox> { + Err(JsErrorBox::generic(message)) } diff --git a/testing/checkin/runner/ops_io.rs b/testing/checkin/runner/ops_io.rs index 0ac8ebc7c..b8697c83d 100644 --- a/testing/checkin/runner/ops_io.rs +++ b/testing/checkin/runner/ops_io.rs @@ -1,5 +1,5 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. -use deno_core::error::{JsNativeError, OpError}; +use deno_core::error::OpError; use deno_core::op2; use deno_core::AsyncRefCell; use deno_core::BufView; @@ -9,6 +9,7 @@ use deno_core::Resource; use deno_core::ResourceHandle; use deno_core::ResourceId; use deno_core::WriteOutcome; +use deno_error::JsErrorBox; use futures::FutureExt; use std::cell::RefCell; use std::rc::Rc; @@ -31,7 +32,7 @@ impl Resource for PipeResource { async { let mut lock = RcRef::map(self, |this| &this.rx).borrow_mut().await; // Note that we're holding a slice across an await point, so this code is very much not safe - let res = lock.read(&mut buf).await.map_err(JsNativeError::from_err)?; + let res = lock.read(&mut buf).await.map_err(JsErrorBox::from_err)?; Ok((res, buf)) } .boxed_local() @@ -43,7 +44,7 @@ impl Resource for PipeResource { ) -> deno_core::AsyncResult { async { let mut lock = RcRef::map(self, |this| &this.tx).borrow_mut().await; - let nwritten = lock.write(&buf).await.map_err(JsNativeError::from_err)?; + let nwritten = lock.write(&buf).await.map_err(JsErrorBox::from_err)?; Ok(WriteOutcome::Partial { nwritten, view: buf, diff --git a/testing/checkin/runner/ops_worker.rs b/testing/checkin/runner/ops_worker.rs index 4bcbb2cdb..2fc56c269 100644 --- a/testing/checkin/runner/ops_worker.rs +++ b/testing/checkin/runner/ops_worker.rs @@ -3,7 +3,6 @@ use super::create_runtime; use super::run_async; use super::Output; use anyhow::anyhow; -use deno_core::error::JsNativeError; use deno_core::error::OpError; use deno_core::op2; use deno_core::url::Url; @@ -12,6 +11,7 @@ use deno_core::GarbageCollected; use deno_core::JsRuntime; use deno_core::OpState; use deno_core::PollEventLoopOptions; +use deno_error::JsErrorBox; use std::cell::RefCell; use std::future::poll_fn; use std::rc::Rc; @@ -181,7 +181,7 @@ pub fn op_worker_parent( worker.parent_channel.lock().unwrap().take(), worker.parent_close_watcher.lock().unwrap().take(), ) else { - return Err(JsNativeError::generic("No parent worker is available").into()); + return Err(JsErrorBox::generic("No parent worker is available").into()); }; Ok(WorkerControl { worker_channel, diff --git a/testing/checkin/runner/ts_module_loader.rs b/testing/checkin/runner/ts_module_loader.rs index 8a7dc42af..5f648b1d3 100644 --- a/testing/checkin/runner/ts_module_loader.rs +++ b/testing/checkin/runner/ts_module_loader.rs @@ -12,7 +12,6 @@ use anyhow::Context; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; -use deno_core::error::JsNativeError; use deno_core::error::ModuleLoaderError; use deno_core::resolve_import; use deno_core::url::Url; @@ -28,6 +27,7 @@ use deno_core::ModuleType; use deno_core::RequestedModuleType; use deno_core::ResolutionKind; use deno_core::SourceMapData; +use deno_error::JsErrorBox; // TODO(bartlomieju): this is duplicated in `core/examples/ts_modules_loader.rs`. type SourceMapStore = Rc>>>; @@ -183,7 +183,7 @@ impl ModuleLoader for TypescriptModuleLoader { pub fn maybe_transpile_source( specifier: ModuleName, source: ModuleCodeString, -) -> Result<(ModuleCodeString, Option), JsNativeError> { +) -> Result<(ModuleCodeString, Option), JsErrorBox> { // Always transpile `checkin:` built-in modules, since they might be TypeScript. let media_type = if specifier.starts_with("checkin:") { MediaType::TypeScript @@ -209,7 +209,7 @@ pub fn maybe_transpile_source( scope_analysis: false, maybe_syntax: None, }) - .map_err(|err| JsNativeError::from_err(JsParseDiagnostic(err)))?; + .map_err(|err| JsErrorBox::from_err(JsParseDiagnostic(err)))?; let transpiled_source = parsed .transpile( &deno_ast::TranspileOptions { @@ -223,7 +223,7 @@ pub fn maybe_transpile_source( ..Default::default() }, ) - .map_err(|err| JsNativeError::from_err(JsTranspileError(err)))? + .map_err(|err| JsErrorBox::from_err(JsTranspileError(err)))? .into_source(); Ok(( From 3c2477d8a24aa12835c5eabf3ce74f543d2b292f Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sat, 21 Dec 2024 06:14:35 +0100 Subject: [PATCH 41/52] fixes --- core/00_infra.js | 19 ++++++++++++++----- core/error.rs | 21 ++++++++++++++++----- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/core/00_infra.js b/core/00_infra.js index d6e570a4e..5cceee85f 100644 --- a/core/00_infra.js +++ b/core/00_infra.js @@ -20,6 +20,7 @@ PromisePrototypeThen, RangeError, ReferenceError, + SafeArrayIterator, SafeMap, StringPrototypeSplit, SymbolFor, @@ -85,7 +86,7 @@ registerErrorClass("TypeError", TypeError); registerErrorClass("URIError", URIError); - function buildCustomError(className, message, code) { + function buildCustomError(className, message, additionalProperties) { let error; try { error = errorMap[className]?.(message); @@ -97,8 +98,10 @@ // Strip buildCustomError() calls from stack trace if (typeof error == "object") { ErrorCaptureStackTrace(error, buildCustomError); - if (code) { - error.code = code; + if (additionalProperties) { + for (const [key, value] of additionalProperties) { + error[key] = value; + } } } return error; @@ -182,8 +185,14 @@ ); if (res.additional_properties) { - for (const [key, value] of res.additional_properties) { - err[key] = value; + for (const property of new SafeArrayIterator(res.additional_properties)) { + const key = property[0]; + if (!(key in err)) { + ObjectDefineProperty(err, key, { + value: property[1], + writable: false, + }); + } } } // Strip eventLoopTick() calls from stack trace diff --git a/core/error.rs b/core/error.rs index 86c1ae68d..5cbb87e48 100644 --- a/core/error.rs +++ b/core/error.rs @@ -260,12 +260,23 @@ pub fn to_v8_error<'a>( let message = v8::String::new(tc_scope, &error.get_message()).unwrap(); let mut args = vec![class.into(), message.into()]; - if let Some(code) = (error as &dyn std::any::Any) - .downcast_ref::() - .and_then(deno_error::get_error_code) - { - args.push(v8::String::new(tc_scope, code).unwrap().into()); + let additional_properties = error + .get_additional_properties() + .into_iter() + .map(|(key, value)| { + let key = v8::String::new(tc_scope, &key).unwrap().into(); + let value = v8::String::new(tc_scope, &value).unwrap().into(); + + v8::Array::new_with_elements(tc_scope, &[key, value]).into() + }) + .collect::>(); + + if !additional_properties.is_empty() { + args.push( + v8::Array::new_with_elements(tc_scope, &additional_properties).into(), + ); } + let maybe_exception = cb.call(tc_scope, this, &args); match maybe_exception { From 0e54baf706733436507486e1f2856e7517815f4d Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sat, 21 Dec 2024 06:29:25 +0100 Subject: [PATCH 42/52] fix test --- testing/checkin/runner/ops_error.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/checkin/runner/ops_error.rs b/testing/checkin/runner/ops_error.rs index ebbdf30a2..79344a4d6 100644 --- a/testing/checkin/runner/ops_error.rs +++ b/testing/checkin/runner/ops_error.rs @@ -21,5 +21,5 @@ pub async fn op_async_throw_error_lazy() -> Result<(), JsErrorBox> { pub fn op_error_custom_sync( #[string] message: String, ) -> Result<(), JsErrorBox> { - Err(JsErrorBox::generic(message)) + Err(JsErrorBox::new("BadResource", message)) } From 4cec7a6d6dc7e0f19a94daaf86e11abde2cd6985 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Sun, 22 Dec 2024 04:48:07 +0100 Subject: [PATCH 43/52] fix --- core/00_infra.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/core/00_infra.js b/core/00_infra.js index 5cceee85f..7a3f79ab4 100644 --- a/core/00_infra.js +++ b/core/00_infra.js @@ -99,8 +99,14 @@ if (typeof error == "object") { ErrorCaptureStackTrace(error, buildCustomError); if (additionalProperties) { - for (const [key, value] of additionalProperties) { - error[key] = value; + for (const property of new SafeArrayIterator(additionalProperties)) { + const key = property[0]; + if (!(key in error)) { + ObjectDefineProperty(error, key, { + value: property[1], + writable: false, + }); + } } } } From 467b0d43e76a43874519d1309142708140d68bb4 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 6 Jan 2025 16:46:20 +0100 Subject: [PATCH 44/52] fix --- core/error.rs | 2 +- core/webidl.rs | 4 +++- ops/op2/dispatch_slow.rs | 2 +- testing/checkin/runner/ops.rs | 3 ++- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/core/error.rs b/core/error.rs index 261875f28..ecf00d3ed 100644 --- a/core/error.rs +++ b/core/error.rs @@ -1393,7 +1393,7 @@ pub mod callsite_fns { fn to_string_inner<'e>( scope: &mut v8::HandleScope<'e>, this: v8::Local<'e, v8::Object>, - orig: v8::Local<'e, Object>, + orig: v8::Local<'e, v8::Object>, orig_to_string_v8: v8::Local<'e, v8::String>, ) -> Option> { let orig_to_string = serde_v8::to_utf8(orig_to_string_v8, scope); diff --git a/core/webidl.rs b/core/webidl.rs index 5fe3cca2a..c6c028b0e 100644 --- a/core/webidl.rs +++ b/core/webidl.rs @@ -1,12 +1,14 @@ // Copyright 2018-2025 the Deno authors. MIT license. +use deno_error::JsError; use indexmap::IndexMap; use std::borrow::Cow; use v8::HandleScope; use v8::Local; use v8::Value; -#[derive(Debug)] +#[derive(Debug, JsError)] +#[class(type)] pub struct WebIdlError { pub prefix: Cow<'static, str>, pub context: Cow<'static, str>, diff --git a/ops/op2/dispatch_slow.rs b/ops/op2/dispatch_slow.rs index 9350159c7..c9d72a745 100644 --- a/ops/op2/dispatch_slow.rs +++ b/ops/op2/dispatch_slow.rs @@ -665,7 +665,7 @@ pub fn from_arg( syn::parse_str::(ty).expect("Failed to reparse state type"); let scope = scope.clone(); let err = format_ident!("{}_err", arg_ident); - let throw_exception = throw_type_error_string(generator_state, &err)?; + let throw_exception = throw_type_error_string(generator_state, &err); let prefix = get_prefix(generator_state); let context = format!("Argument {}", index + 1); diff --git a/testing/checkin/runner/ops.rs b/testing/checkin/runner/ops.rs index b2f23bc5f..7c8f31bd6 100644 --- a/testing/checkin/runner/ops.rs +++ b/testing/checkin/runner/ops.rs @@ -3,6 +3,7 @@ use std::cell::RefCell; use std::rc::Rc; +use deno_core::error::OpError; use deno_core::op2; use deno_core::stats::RuntimeActivityDiff; use deno_core::stats::RuntimeActivitySnapshot; @@ -97,7 +98,7 @@ impl TestObjectWrap { fn with_rename(&self) {} #[async_method] - async fn with_async_fn(&self, #[smi] ms: u32) -> Result<(), AnyError> { + async fn with_async_fn(&self, #[smi] ms: u32) -> Result<(), OpError> { tokio::time::sleep(std::time::Duration::from_millis(ms as u64)).await; Ok(()) } From 9b61216b7a28ca8f3b00feb33cb5fb9eddf2a3e8 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 6 Jan 2025 17:02:32 +0100 Subject: [PATCH 45/52] git dep --- Cargo.lock | 3 ++- Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 679653142..cd06fd566 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -641,12 +641,12 @@ dependencies = [ [[package]] name = "deno_error" version = "0.5.2" +source = "git+https://github.com/denoland/deno_error.git?branch=changes#3f2e4efeecce782251b7347a5ebb0ed21b02e661" dependencies = [ "deno_error_macro", "libc", "serde", "serde_json", - "thiserror 2.0.6", "tokio", "url", ] @@ -654,6 +654,7 @@ dependencies = [ [[package]] name = "deno_error_macro" version = "0.5.2" +source = "git+https://github.com/denoland/deno_error.git?branch=changes#3f2e4efeecce782251b7347a5ebb0ed21b02e661" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 91c0105e6..7233bed68 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -96,4 +96,4 @@ lto = true opt-level = 'z' # Optimize for size [patch.crates-io] -deno_error = { path = "../deno_error" } \ No newline at end of file +deno_error = { git = "https://github.com/denoland/deno_error.git", branch = "changes" } \ No newline at end of file From 92f935d40dec7fded77d7863298640aa75f26eb5 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 6 Jan 2025 17:04:15 +0100 Subject: [PATCH 46/52] fmt --- Cargo.toml | 2 +- core/00_infra.js | 4 +++- core/Cargo.toml | 2 +- core/async_cancel.rs | 3 ++- core/modules/tests.rs | 6 ++++-- core/runtime/tests/ops.rs | 2 +- ops/op2/README.md | 4 ++-- serde_v8/Cargo.toml | 2 +- 8 files changed, 15 insertions(+), 10 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 7233bed68..0603cb770 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -96,4 +96,4 @@ lto = true opt-level = 'z' # Optimize for size [patch.crates-io] -deno_error = { git = "https://github.com/denoland/deno_error.git", branch = "changes" } \ No newline at end of file +deno_error = { git = "https://github.com/denoland/deno_error.git", branch = "changes" } diff --git a/core/00_infra.js b/core/00_infra.js index 93ba5ac2a..0c5e1cde1 100644 --- a/core/00_infra.js +++ b/core/00_infra.js @@ -191,7 +191,9 @@ ); if (res.additional_properties) { - for (const property of new SafeArrayIterator(res.additional_properties)) { + for ( + const property of new SafeArrayIterator(res.additional_properties) + ) { const key = property[0]; if (!(key in err)) { ObjectDefineProperty(err, key, { diff --git a/core/Cargo.toml b/core/Cargo.toml index 8bdef713e..6dc6cab55 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -48,8 +48,8 @@ serde_v8.workspace = true smallvec.workspace = true sourcemap.workspace = true static_assertions.workspace = true -tokio.workspace = true thiserror.workspace = true +tokio.workspace = true url.workspace = true v8.workspace = true wasm_dep_analyzer = "0.2.0" diff --git a/core/async_cancel.rs b/core/async_cancel.rs index 80a486193..15f777535 100644 --- a/core/async_cancel.rs +++ b/core/async_cancel.rs @@ -1,6 +1,7 @@ // Copyright 2018-2025 the Deno authors. MIT license. -use std::any::{type_name, Any}; +use std::any::type_name; +use std::any::Any; use std::borrow::Cow; use std::error::Error; use std::fmt; diff --git a/core/modules/tests.rs b/core/modules/tests.rs index e9fcb945a..e053265c2 100644 --- a/core/modules/tests.rs +++ b/core/modules/tests.rs @@ -3,19 +3,21 @@ #![allow(clippy::print_stderr)] use crate::ascii_str; -use crate::error::{exception_to_err_result, CoreError}; +use crate::error::exception_to_err_result; +use crate::error::CoreError; use crate::modules::loaders::ModuleLoadEventCounts; use crate::modules::loaders::TestingModuleLoader; use crate::modules::loaders::*; +use crate::modules::CustomModuleEvaluationKind; use crate::modules::IntoModuleName; use crate::modules::ModuleCodeBytes; +use crate::modules::ModuleConcreteError; use crate::modules::ModuleError; use crate::modules::ModuleInfo; use crate::modules::ModuleRequest; use crate::modules::ModuleSourceCode; use crate::modules::RequestedModuleType; use crate::modules::SourceCodeCacheInfo; -use crate::modules::{CustomModuleEvaluationKind, ModuleConcreteError}; use crate::resolve_import; use crate::resolve_url; use crate::runtime::JsRuntime; diff --git a/core/runtime/tests/ops.rs b/core/runtime/tests/ops.rs index fc5f01cf2..70ad86308 100644 --- a/core/runtime/tests/ops.rs +++ b/core/runtime/tests/ops.rs @@ -2,13 +2,13 @@ #![allow(clippy::print_stdout, clippy::print_stderr, clippy::unused_async)] -use deno_error::JsErrorBox; use crate::error::OpError; use crate::extensions::OpDecl; use crate::modules::StaticModuleLoader; use crate::runtime::tests::setup; use crate::runtime::tests::Mode; use crate::*; +use deno_error::JsErrorBox; use futures::Future; use pretty_assertions::assert_eq; use std::cell::RefCell; diff --git a/ops/op2/README.md b/ops/op2/README.md index 934f98813..241e95f33 100644 --- a/ops/op2/README.md +++ b/ops/op2/README.md @@ -18,8 +18,8 @@ buffer. ## Fallible `op`s An `op` function may be declared to return `Result` to indicate that the `op` is -fallible. The error type must implement `deno_error::JsErrorClass`. When -the function returns `Err`, an exception is thrown. +fallible. The error type must implement `deno_error::JsErrorClass`. When the +function returns `Err`, an exception is thrown. ## `async` calls diff --git a/serde_v8/Cargo.toml b/serde_v8/Cargo.toml index e2ee18a17..217cc7f35 100644 --- a/serde_v8/Cargo.toml +++ b/serde_v8/Cargo.toml @@ -14,12 +14,12 @@ description = "Rust to V8 serialization and deserialization" path = "lib.rs" [dependencies] +deno_error.workspace = true num-bigint.workspace = true serde.workspace = true smallvec = { workspace = true, features = ["union"] } thiserror.workspace = true v8.workspace = true -deno_error.workspace = true [dev-dependencies] bencher.workspace = true From d8b5c23d14f1b4cf6ed0f08ef339286223e29afd Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 6 Jan 2025 17:08:02 +0100 Subject: [PATCH 47/52] fix --- core/benches/snapshot/snapshot.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/benches/snapshot/snapshot.rs b/core/benches/snapshot/snapshot.rs index e29ae9ea1..21549d7d1 100644 --- a/core/benches/snapshot/snapshot.rs +++ b/core/benches/snapshot/snapshot.rs @@ -50,13 +50,13 @@ fn make_extensions_ops() -> Vec { fake_extensions!(init_ops, a, b, c, d, e, f, g, h, i, j, k, l, m, n) } -deno_core::js_error_wrapper!( +deno_error::js_error_wrapper!( deno_ast::ParseDiagnostic, JsParseDiagnostic, "TypeError" ); -deno_core::js_error_wrapper!( +deno_error::js_error_wrapper!( deno_ast::TranspileError, JsTranspileError, "TypeError" From 9dda2122006d97332f80d010ea7fe2e13b3f5e53 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 6 Jan 2025 17:10:54 +0100 Subject: [PATCH 48/52] fix --- core/benches/ops/sync.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/benches/ops/sync.rs b/core/benches/ops/sync.rs index e2cdc1dd1..3f764a430 100644 --- a/core/benches/ops/sync.rs +++ b/core/benches/ops/sync.rs @@ -184,7 +184,9 @@ fn bench_op( ..Default::default() }); let err_mapper = |err| { - error::JsErrorBox::generic(format!("{op} test failed ({call}): {err:?}")) + deno_error::JsErrorBox::generic(format!( + "{op} test failed ({call}): {err:?}" + )) }; let args = (0..arg_count) From c45bfdbd6cd4aa45a7d704141e99d9bd6f64da6f Mon Sep 17 00:00:00 2001 From: crowlkats Date: Mon, 6 Jan 2025 17:19:32 +0100 Subject: [PATCH 49/52] fix copyrights --- core/modules/loaders.rs | 2 +- core/modules/recursive_load.rs | 2 +- core/ops_builtin_v8.rs | 2 +- core/runtime/bindings.rs | 2 +- core/runtime/ops.rs | 2 +- core/runtime/tests/snapshot.rs | 2 +- testing/checkin/runner/ops_error.rs | 2 +- testing/checkin/runner/ops_worker.rs | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/core/modules/loaders.rs b/core/modules/loaders.rs index a392553ce..91a89e113 100644 --- a/core/modules/loaders.rs +++ b/core/modules/loaders.rs @@ -1,4 +1,4 @@ -// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright 2018-2025 the Deno authors. MIT license. use crate::module_specifier::ModuleSpecifier; use crate::modules::IntoModuleCodeString; diff --git a/core/modules/recursive_load.rs b/core/modules/recursive_load.rs index 89cbb0e48..b57f64d15 100644 --- a/core/modules/recursive_load.rs +++ b/core/modules/recursive_load.rs @@ -1,4 +1,4 @@ -// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright 2018-2025 the Deno authors. MIT license. use crate::error::CoreError; use crate::module_specifier::ModuleSpecifier; diff --git a/core/ops_builtin_v8.rs b/core/ops_builtin_v8.rs index 97c04ed95..83e45dd11 100644 --- a/core/ops_builtin_v8.rs +++ b/core/ops_builtin_v8.rs @@ -1,4 +1,4 @@ -// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright 2018-2025 the Deno authors. MIT license. use crate::error::is_instance_of_error; use crate::error::JsError; diff --git a/core/runtime/bindings.rs b/core/runtime/bindings.rs index 4919df284..fcc9bb98c 100644 --- a/core/runtime/bindings.rs +++ b/core/runtime/bindings.rs @@ -1,4 +1,4 @@ -// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright 2018-2025 the Deno authors. MIT license. use std::collections::HashMap; use std::mem::MaybeUninit; diff --git a/core/runtime/ops.rs b/core/runtime/ops.rs index b95184e97..a5afefcbb 100644 --- a/core/runtime/ops.rs +++ b/core/runtime/ops.rs @@ -1,4 +1,4 @@ -// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright 2018-2025 the Deno authors. MIT license. use super::op_driver::OpDriver; use super::op_driver::OpScheduling; diff --git a/core/runtime/tests/snapshot.rs b/core/runtime/tests/snapshot.rs index 2447828e4..5843e4f7e 100644 --- a/core/runtime/tests/snapshot.rs +++ b/core/runtime/tests/snapshot.rs @@ -1,4 +1,4 @@ -// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright 2018-2025 the Deno authors. MIT license. use self::runtime::create_snapshot; use self::runtime::CreateSnapshotOptions; diff --git a/testing/checkin/runner/ops_error.rs b/testing/checkin/runner/ops_error.rs index 4450ed066..66d57fbcf 100644 --- a/testing/checkin/runner/ops_error.rs +++ b/testing/checkin/runner/ops_error.rs @@ -1,4 +1,4 @@ -// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright 2018-2025 the Deno authors. MIT license. use deno_core::op2; use deno_error::JsErrorBox; diff --git a/testing/checkin/runner/ops_worker.rs b/testing/checkin/runner/ops_worker.rs index a8b294786..160699543 100644 --- a/testing/checkin/runner/ops_worker.rs +++ b/testing/checkin/runner/ops_worker.rs @@ -1,4 +1,4 @@ -// Copyright 2018-2025 the Deno authors. MIT license. +// Copyright 2018-2025 the Deno authors. MIT license. use super::create_runtime; use super::run_async; From f1cbda9b32a1233846c65e1f1b591790f22f48c1 Mon Sep 17 00:00:00 2001 From: crowlkats Date: Tue, 7 Jan 2025 12:05:21 +0100 Subject: [PATCH 50/52] fixes --- Cargo.lock | 2 -- Cargo.toml | 2 +- core/async_cancel.rs | 2 +- core/error.rs | 24 ++++++++++++++++-------- core/runtime/op_driver/op_results.rs | 4 ++-- 5 files changed, 20 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cd06fd566..6791d274d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -641,7 +641,6 @@ dependencies = [ [[package]] name = "deno_error" version = "0.5.2" -source = "git+https://github.com/denoland/deno_error.git?branch=changes#3f2e4efeecce782251b7347a5ebb0ed21b02e661" dependencies = [ "deno_error_macro", "libc", @@ -654,7 +653,6 @@ dependencies = [ [[package]] name = "deno_error_macro" version = "0.5.2" -source = "git+https://github.com/denoland/deno_error.git?branch=changes#3f2e4efeecce782251b7347a5ebb0ed21b02e661" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 0603cb770..b35f75c1a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -96,4 +96,4 @@ lto = true opt-level = 'z' # Optimize for size [patch.crates-io] -deno_error = { git = "https://github.com/denoland/deno_error.git", branch = "changes" } +deno_error = { path = "../deno_error" } diff --git a/core/async_cancel.rs b/core/async_cancel.rs index 15f777535..8abf89401 100644 --- a/core/async_cancel.rs +++ b/core/async_cancel.rs @@ -250,7 +250,7 @@ impl From for deno_error::JsErrorBox { } impl JsErrorClass for Canceled { - fn get_class(&self) -> &'static str { + fn get_class(&self) -> Cow<'static, str> { let io_err: io::Error = self.to_owned().into(); io_err.get_class() } diff --git a/core/error.rs b/core/error.rs index ecf00d3ed..5608bce9f 100644 --- a/core/error.rs +++ b/core/error.rs @@ -134,7 +134,7 @@ impl CoreError { }; let exception = - js_class_and_message_to_exception(scope, self.get_class(), &message); + js_class_and_message_to_exception(scope, &self.get_class(), &message); v8::Global::new(scope, exception) } } @@ -152,10 +152,14 @@ impl From for CoreError { } impl JsErrorClass for CoreError { - fn get_class(&self) -> &'static str { + fn get_class(&self) -> Cow<'static, str> { match self { CoreError::Js(js_error) => { - unreachable!("JsError should not be reachable: {}", js_error) + if let Some(name) = &js_error.name { + Cow::Owned(name.clone()) + } else { + Cow::Borrowed(GENERIC_ERROR) + } } CoreError::Io(err) => err.get_class(), CoreError::ExtensionTranspiler(err) => err.get_class(), @@ -165,7 +169,7 @@ impl JsErrorClass for CoreError { CoreError::Url(err) => err.get_class(), CoreError::Module(err) => err.get_class(), CoreError::DataError(err) => err.get_class(), - CoreError::FutureCanceled(_) => "Interrupted", + CoreError::FutureCanceled(_) => Cow::Borrowed("Interrupted"), CoreError::TLA | CoreError::Parse(_) | CoreError::Execute(_) @@ -175,14 +179,18 @@ impl JsErrorClass for CoreError { | CoreError::ExecutionTerminated | CoreError::PendingPromiseResolution | CoreError::EvaluateDynamicImportedModule - | CoreError::Other(_) => GENERIC_ERROR, + | CoreError::Other(_) => Cow::Borrowed(GENERIC_ERROR), } } fn get_message(&self) -> Cow<'static, str> { match self { CoreError::Js(js_error) => { - unreachable!("JsError should not be reachable: {}", js_error) + if let Some(name) = &js_error.message { + Cow::Owned(name.clone()) + } else { + Cow::Borrowed("") + } } CoreError::Io(err) => err.get_message(), CoreError::ExtensionTranspiler(err) => err.get_message(), @@ -223,7 +231,7 @@ pub fn throw_js_error_class( ) { let exception = js_class_and_message_to_exception( scope, - error.get_class(), + &error.get_class(), &error.get_message(), ); scope.throw_exception(exception); @@ -256,7 +264,7 @@ pub fn to_v8_error<'a>( .expect("Custom error builder must be set"); let cb = cb.open(tc_scope); let this = v8::undefined(tc_scope).into(); - let class = v8::String::new(tc_scope, error.get_class()).unwrap(); + let class = v8::String::new(tc_scope, &error.get_class()).unwrap(); let message = v8::String::new(tc_scope, &error.get_message()).unwrap(); let mut args = vec![class.into(), message.into()]; diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index 7415be07d..3aa511ce9 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -290,7 +290,7 @@ impl Serialize for OpError { S: serde::Serializer, { let mut serde_state = serializer.serialize_struct("OpError", 3)?; - serde_state.serialize_field("$err_class_name", self.0.get_class())?; + serde_state.serialize_field("$err_class_name", &self.0.get_class())?; serde_state.serialize_field("message", &self.0.get_message())?; serde_state.serialize_field( "additional_properties", @@ -306,7 +306,7 @@ impl Serialize for OpError { pub struct OpErrorWrapper(pub OpError); impl JsErrorClass for OpErrorWrapper { - fn get_class(&self) -> &'static str { + fn get_class(&self) -> Cow<'static, str> { self.0 .0.get_class() } From 0ea6627a050b10d58f4a4a2a60a9a237d909baed Mon Sep 17 00:00:00 2001 From: crowlkats Date: Tue, 7 Jan 2025 21:31:27 +0100 Subject: [PATCH 51/52] update deno_error --- Cargo.lock | 8 ++++++-- Cargo.toml | 5 +---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6791d274d..c7d8526df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -640,7 +640,9 @@ dependencies = [ [[package]] name = "deno_error" -version = "0.5.2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4da6a58de6932a96f84e133c072fd3b525966ee122a71f3efd48bbff2eed5ac" dependencies = [ "deno_error_macro", "libc", @@ -652,7 +654,9 @@ dependencies = [ [[package]] name = "deno_error_macro" -version = "0.5.2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46351dff93aed2039407c91e2ded2a5591e42d2795ab3d111288625bb710d3d2" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index b35f75c1a..cfd601a38 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ serde_v8 = { version = "0.237.0", path = "./serde_v8" } deno_ast = { version = "=0.40.0", features = ["transpiling"] } deno_core_icudata = "0.74.0" -deno_error = { version = "0.5.2", features = ["serde_json", "serde", "url", "tokio"] } +deno_error = { version = "0.5.3", features = ["serde_json", "serde", "url", "tokio"] } deno_unsync = "0.4.1" v8 = { version = "130.0.5", default-features = false } @@ -94,6 +94,3 @@ codegen-units = 1 incremental = true lto = true opt-level = 'z' # Optimize for size - -[patch.crates-io] -deno_error = { path = "../deno_error" } From 2be487e7514317e5370fac7ecdc24bf5f93abafa Mon Sep 17 00:00:00 2001 From: crowlkats Date: Wed, 8 Jan 2025 00:33:12 +0100 Subject: [PATCH 52/52] address comments --- core/error.rs | 6 +++--- core/runtime/op_driver/op_results.rs | 7 +------ ops/op2/signature.rs | 24 ++++++++---------------- 3 files changed, 12 insertions(+), 25 deletions(-) diff --git a/core/error.rs b/core/error.rs index 5dd24a3d9..a0f329787 100644 --- a/core/error.rs +++ b/core/error.rs @@ -225,9 +225,9 @@ impl JsErrorClass for CoreError { } } -pub fn throw_js_error_class( +pub fn throw_js_error_class( scope: &mut v8::HandleScope, - error: &E, + error: &dyn JsErrorClass, ) { let exception = js_class_and_message_to_exception( scope, @@ -254,7 +254,7 @@ fn js_class_and_message_to_exception<'s>( pub fn to_v8_error<'a>( scope: &mut v8::HandleScope<'a>, - error: &impl JsErrorClass, + error: &dyn JsErrorClass, ) -> v8::Local<'a, v8::Value> { let tc_scope = &mut v8::TryCatch::new(scope); let cb = JsRealm::exception_state_from_scope(tc_scope) diff --git a/core/runtime/op_driver/op_results.rs b/core/runtime/op_driver/op_results.rs index 3aa511ce9..6b1ae6147 100644 --- a/core/runtime/op_driver/op_results.rs +++ b/core/runtime/op_driver/op_results.rs @@ -9,7 +9,6 @@ use serde::ser::SerializeStruct; use serde::Serialize; use std::any::Any; use std::borrow::Cow; -use std::error::Error; const MAX_RESULT_SIZE: usize = 32; @@ -266,11 +265,7 @@ impl OpResult { #[derive(Debug)] pub struct OpError(Box); -impl std::error::Error for OpError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - todo!() - } -} +impl std::error::Error for OpError {} impl std::fmt::Display for OpError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { diff --git a/ops/op2/signature.rs b/ops/op2/signature.rs index f272ce49b..733bc9be4 100644 --- a/ops/op2/signature.rs +++ b/ops/op2/signature.rs @@ -819,25 +819,19 @@ pub enum SignatureError { RetError(#[from] RetError), #[error("Only one lifetime is permitted")] TooManyLifetimes, - #[error("Generic '{0}' must have one and only bound (either and 'where T: Trait', or )" - )] + #[error("Generic '{0}' must have one and only bound (either and 'where T: Trait', or )")] GenericBoundCardinality(String), - #[error("Where clause predicate '{0}' (eg: where T: Trait) must appear in generics list (eg: )" - )] + #[error("Where clause predicate '{0}' (eg: where T: Trait) must appear in generics list (eg: )")] WherePredicateMustAppearInGenerics(String), - #[error("All generics must appear only once in the generics parameter list or where clause" - )] + #[error("All generics must appear only once in the generics parameter list or where clause")] DuplicateGeneric(String), #[error("Generic lifetime '{0}' may not have bounds (eg: <'a: 'b>)")] LifetimesMayNotHaveBounds(String), - #[error("Invalid generic: '{0}' Only simple generics bounds are allowed (eg: T: Trait)" - )] + #[error("Invalid generic: '{0}' Only simple generics bounds are allowed (eg: T: Trait)")] InvalidGeneric(String), - #[error("Invalid predicate: '{0}' Only simple where predicates are allowed (eg: T: Trait)" - )] + #[error("Invalid predicate: '{0}' Only simple where predicates are allowed (eg: T: Trait)")] InvalidWherePredicate(String), - #[error("State may be either a single OpState parameter, one mutable #[state], or multiple immultiple #[state]s" - )] + #[error("State may be either a single OpState parameter, one mutable #[state], or multiple immultiple #[state]s")] InvalidOpStateCombination, #[error("JsRuntimeState may only be used in one parameter")] InvalidMultipleJsRuntimeState, @@ -849,8 +843,7 @@ pub enum SignatureError { pub enum AttributeError { #[error("Unknown or invalid attribute '{0}'")] InvalidAttribute(String), - #[error("Invalid inner attribute (#![attr]) in this position. Use an equivalent outer attribute (#[attr]) on the function instead." - )] + #[error("Invalid inner attribute (#![attr]) in this position. Use an equivalent outer attribute (#[attr]) on the function instead.")] InvalidInnerAttribute, } @@ -890,8 +883,7 @@ pub enum ArgError { AttributeError(#[from] AttributeError), #[error("The type '{0}' is not allowed in this position")] NotAllowedInThisPosition(String), - #[error("Invalid deno_core:: prefix for type '{0}'. Try adding `use deno_core::{1}` at the top of the file and specifying `{2}` in this position." - )] + #[error("Invalid deno_core:: prefix for type '{0}'. Try adding `use deno_core::{1}` at the top of the file and specifying `{2}` in this position.")] InvalidDenoCorePrefix(String, String, String), #[error("Expected a reference. Use '#[cppgc] &{0}' instead.")] ExpectedCppGcReference(String),