From 3b59e0ad118a6927360ecdfb71566f5ac89b5e58 Mon Sep 17 00:00:00 2001 From: Redfire Date: Sat, 25 Nov 2023 10:51:00 +0800 Subject: [PATCH] Updated Formatting Style --- cli/src/main.rs | 14 ++++- ion-proc/src/attribute/class.rs | 5 +- ion-proc/src/class/accessor.rs | 8 ++- ion-proc/src/class/impl/mod.rs | 21 +++++-- ion-proc/src/class/impl/spec.rs | 31 +++++++++-- ion-proc/src/class/method.rs | 4 +- ion-proc/src/class/property.rs | 3 +- ion-proc/src/class/struct.rs | 41 +++++++++++--- ion-proc/src/function/parameters.rs | 37 ++++++++++--- ion-proc/src/function/wrapper.rs | 5 +- ion-proc/src/trace.rs | 5 +- ion-proc/src/value/from.rs | 58 +++++++++++++------- ion-proc/src/visitors.rs | 5 +- ion/examples/macros/js_fn/complex.rs | 5 +- ion/src/bigint.rs | 4 +- ion/src/class/mod.rs | 15 +++-- ion/src/class/native.rs | 5 +- ion/src/context.rs | 4 +- ion/src/conversions/value/from.rs | 25 +++++++-- ion/src/conversions/value/to.rs | 3 +- ion/src/error.rs | 5 +- ion/src/exception.rs | 13 ++++- ion/src/flags.rs | 6 +- ion/src/format/array.rs | 12 +++- ion/src/format/object.rs | 40 +++++++++++--- ion/src/format/symbol.rs | 17 +++--- ion/src/functions/closure.rs | 3 +- ion/src/functions/function.rs | 46 ++++++++++++---- ion/src/functions/mod.rs | 4 +- ion/src/module.rs | 21 +++++-- ion/src/objects/array.rs | 8 ++- ion/src/objects/date.rs | 9 +-- ion/src/objects/descriptor.rs | 16 ++++-- ion/src/objects/iterator.rs | 20 +++++-- ion/src/objects/mod.rs | 13 ++++- ion/src/objects/object.rs | 51 +++++++++++++---- ion/src/objects/promise.rs | 17 ++++-- ion/src/objects/regexp.rs | 23 ++++++-- ion/src/objects/typedarray.rs | 14 ++++- ion/src/spec/function.rs | 22 ++++++-- ion/src/spec/property.rs | 22 +++++--- ion/src/stack.rs | 11 +++- ion/src/string/mod.rs | 9 ++- ion/src/value.rs | 5 +- ion/tests/objects/array.rs | 10 +++- ion/tests/objects/date.rs | 10 +++- ion/tests/objects/object.rs | 10 +++- modules/src/fs/fs.rs | 43 ++++++++++----- modules/src/url/url.rs | 6 +- runtime/src/cache/cache.rs | 4 +- runtime/src/event_loop/microtasks.rs | 3 +- runtime/src/event_loop/mod.rs | 9 ++- runtime/src/globals/abort.rs | 5 +- runtime/src/globals/base64.rs | 3 +- runtime/src/globals/console.rs | 17 ++++-- runtime/src/globals/encoding/decoder.rs | 12 ++-- runtime/src/globals/encoding/encoder.rs | 3 +- runtime/src/globals/fetch/body.rs | 4 +- runtime/src/globals/fetch/header.rs | 23 +++++--- runtime/src/globals/fetch/mod.rs | 36 ++++++++---- runtime/src/globals/fetch/request/options.rs | 30 ++++++++-- runtime/src/globals/fetch/response/mod.rs | 10 +++- runtime/src/globals/file/blob.rs | 9 ++- runtime/src/globals/file/reader.rs | 8 ++- runtime/src/globals/timers.rs | 18 ++++-- runtime/src/globals/url/mod.rs | 5 +- runtime/src/runtime.rs | 11 +++- runtime/src/typescript.rs | 14 ++++- rustfmt.toml | 3 +- 69 files changed, 755 insertions(+), 256 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index f9ab1574..621ff200 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -39,10 +39,20 @@ pub(crate) enum Command { #[command(about = "Runs a JavaScript file")] Run { - #[arg(help = "The JavaScript file to run, Default: 'main.js'", required(false), default_value = "main.js")] + #[arg( + help = "The JavaScript file to run, Default: 'main.js'", + required(false), + default_value = "main.js" + )] path: String, - #[arg(help = "Sets logging level, Default: ERROR", short, long, required(false), default_value = "ERROR")] + #[arg( + help = "Sets logging level, Default: ERROR", + short, + long, + required(false), + default_value = "ERROR" + )] log_level: String, #[arg(help = "Sets logging level to DEBUG", short, long)] diff --git a/ion-proc/src/attribute/class.rs b/ion-proc/src/attribute/class.rs index 715c98b1..199cb2a8 100644 --- a/ion-proc/src/attribute/class.rs +++ b/ion-proc/src/attribute/class.rs @@ -53,7 +53,10 @@ impl Parse for Name { if !string.starts_with('[') && !string.ends_with(']') { Ok(Name::String(literal)) } else { - Err(Error::new(literal.span(), "Function name must not start with '[' or end with ']'")) + Err(Error::new( + literal.span(), + "Function name must not start with '[' or end with ']'", + )) } } else if let Ok(other) = input.parse() { Ok(Name::Symbol(other)) diff --git a/ion-proc/src/class/accessor.rs b/ion-proc/src/class/accessor.rs index cbffe39a..fa1035cb 100644 --- a/ion-proc/src/class/accessor.rs +++ b/ion-proc/src/class/accessor.rs @@ -99,7 +99,9 @@ pub(super) fn get_accessor_name(mut name: String, is_setter: bool) -> String { name } -pub(super) fn impl_accessor(ion: &TokenStream, method: ItemFn, ty: &Type, is_setter: bool) -> Result<(Method, Parameters)> { +pub(super) fn impl_accessor( + ion: &TokenStream, method: ItemFn, ty: &Type, is_setter: bool, +) -> Result<(Method, Parameters)> { let expected_args = is_setter as i32; let error_message = if is_setter { format!("Expected Setter to have {} argument", expected_args) @@ -130,7 +132,9 @@ pub(super) fn impl_accessor(ion: &TokenStream, method: ItemFn, ty: &Type, is_set Ok((accessor, parameters)) } -pub(super) fn insert_accessor(accessors: &mut HashMap, name: String, getter: Option, setter: Option) { +pub(super) fn insert_accessor( + accessors: &mut HashMap, name: String, getter: Option, setter: Option, +) { match accessors.entry(name) { Entry::Occupied(mut o) => match (getter, setter) { (Some(g), Some(s)) => *o.get_mut() = Accessor(Some(g), Some(s)), diff --git a/ion-proc/src/class/impl/mod.rs b/ion-proc/src/class/impl/mod.rs index 23ccbd9b..a60bac0c 100644 --- a/ion-proc/src/class/impl/mod.rs +++ b/ion-proc/src/class/impl/mod.rs @@ -24,11 +24,17 @@ pub(super) fn impl_js_class_impl(r#impl: &mut ItemImpl) -> Result<[ItemImpl; 2]> let ion = &crate_from_attributes(&r#impl.attrs); if !r#impl.generics.params.is_empty() { - return Err(Error::new(r#impl.generics.span(), "Native Class Impls cannot have generics.")); + return Err(Error::new( + r#impl.generics.span(), + "Native Class Impls cannot have generics.", + )); } if let Some(r#trait) = &r#impl.trait_ { - return Err(Error::new(r#trait.1.span(), "Native Class Impls cannot be for a trait.")); + return Err(Error::new( + r#trait.1.span(), + "Native Class Impls cannot be for a trait.", + )); } let r#type = *r#impl.self_ty.clone(); @@ -67,14 +73,21 @@ pub(super) fn impl_js_class_impl(r#impl: &mut ItemImpl) -> Result<[ItemImpl; 2]> let constructor = match constructor { Some(constructor) => constructor, - None => return Err(Error::new(r#impl.span(), "Native Class Impls must contain a constructor.")), + None => { + return Err(Error::new( + r#impl.span(), + "Native Class Impls must contain a constructor.", + )) + } }; let ident: Ident = parse2(quote_spanned!(r#type.span() => #r#type))?; class_definition(ion, r#impl.span(), &r#type, &ident, constructor, specs) } -fn parse_class_method(ion: &TokenStream, r#fn: &mut ImplItemFn, specs: &mut PrototypeSpecs, r#type: &Type) -> Result> { +fn parse_class_method( + ion: &TokenStream, r#fn: &mut ImplItemFn, specs: &mut PrototypeSpecs, r#type: &Type, +) -> Result> { match &r#fn.vis { Visibility::Public(_) => (), _ => return Ok(None), diff --git a/ion-proc/src/class/impl/spec.rs b/ion-proc/src/class/impl/spec.rs index 3631a6a0..678b7bba 100644 --- a/ion-proc/src/class/impl/spec.rs +++ b/ion-proc/src/class/impl/spec.rs @@ -37,7 +37,9 @@ impl PrototypeSpecs { } pub(super) fn into_functions(self) -> Vec { - let mut functions = Vec::with_capacity(self.methods.0.len() + self.methods.1.len() + self.accessors.0.len() + self.accessors.1.len()); + let mut functions = Vec::with_capacity( + self.methods.0.len() + self.methods.1.len() + self.accessors.0.len() + self.accessors.1.len(), + ); functions.extend(self.methods.0); functions.extend(self.methods.1); @@ -60,7 +62,9 @@ impl SpecFunctions { } } -fn methods_to_spec_function(ion: &TokenStream, span: Span, class: &Ident, methods: &[Method], r#static: bool) -> Result { +fn methods_to_spec_function( + ion: &TokenStream, span: Span, class: &Ident, methods: &[Method], r#static: bool, +) -> Result { let ident = if r#static { parse_quote!(ION_STATIC_FUNCTIONS) } else { @@ -96,11 +100,18 @@ fn methods_to_spec_function(ion: &TokenStream, span: Span, class: &Ident, method .collect(); specs.push(parse_quote!(::mozjs::jsapi::JSFunctionSpec::ZERO)); - spec_function(span, &ident, &function_ident, &specs, parse_quote!(::mozjs::jsapi::JSFunctionSpec)) + spec_function( + span, + &ident, + &function_ident, + &specs, + parse_quote!(::mozjs::jsapi::JSFunctionSpec), + ) } fn properties_to_spec_function( - ion: &TokenStream, span: Span, class: &Ident, properties: &[Property], accessors: &HashMap, r#static: bool, + ion: &TokenStream, span: Span, class: &Ident, properties: &[Property], accessors: &HashMap, + r#static: bool, ) -> Result { let ident: Ident = if r#static { parse_quote!(ION_STATIC_PROPERTIES) @@ -117,10 +128,18 @@ fn properties_to_spec_function( accessors.values().for_each(|accessor| specs.extend(accessor.to_specs(ion, class))); specs.push(parse_quote!(::mozjs::jsapi::JSPropertySpec::ZERO)); - spec_function(span, &ident, &function_ident, &specs, parse_quote!(::mozjs::jsapi::JSPropertySpec)) + spec_function( + span, + &ident, + &function_ident, + &specs, + parse_quote!(::mozjs::jsapi::JSPropertySpec), + ) } -fn spec_function(span: Span, ident: &Ident, function_ident: &Ident, specs: &[TokenStream], ty: Type) -> Result { +fn spec_function( + span: Span, ident: &Ident, function_ident: &Ident, specs: &[TokenStream], ty: Type, +) -> Result { parse2(quote_spanned!(span => fn #function_ident() -> &'static [#ty] { static #ident: &[#ty] = &[ #(#specs),* diff --git a/ion-proc/src/class/method.rs b/ion-proc/src/class/method.rs index a9530e28..7a54f6b1 100644 --- a/ion-proc/src/class/method.rs +++ b/ion-proc/src/class/method.rs @@ -33,7 +33,9 @@ pub(super) struct Method { pub(super) names: Vec, } -pub(super) fn impl_method(ion: &TokenStream, mut method: ItemFn, ty: &Type, predicate: F) -> Result<(Method, Parameters)> +pub(super) fn impl_method( + ion: &TokenStream, mut method: ItemFn, ty: &Type, predicate: F, +) -> Result<(Method, Parameters)> where F: FnOnce(&Signature) -> Result<()>, { diff --git a/ion-proc/src/class/property.rs b/ion-proc/src/class/property.rs index b948490c..dfa237ba 100644 --- a/ion-proc/src/class/property.rs +++ b/ion-proc/src/class/property.rs @@ -37,7 +37,8 @@ impl Property { for attr in &con.attrs { if attr.path().is_ident("ion") { - let args: Punctuated = attr.parse_args_with(Punctuated::parse_terminated)?; + let args: Punctuated = + attr.parse_args_with(Punctuated::parse_terminated)?; for arg in args { match arg { diff --git a/ion-proc/src/class/struct.rs b/ion-proc/src/class/struct.rs index 1dd804af..9443c651 100644 --- a/ion-proc/src/class/struct.rs +++ b/ion-proc/src/class/struct.rs @@ -43,7 +43,10 @@ pub(super) fn impl_js_class_struct(r#struct: &mut ItemStruct) -> Result<[ItemImp } if !r#struct.generics.params.is_empty() { - return Err(Error::new(r#struct.generics.span(), "Native Class Structs cannot have generics.")); + return Err(Error::new( + r#struct.generics.span(), + "Native Class Structs cannot have generics.", + )); } let ident = &r#struct.ident; @@ -51,7 +54,10 @@ pub(super) fn impl_js_class_struct(r#struct: &mut ItemStruct) -> Result<[ItemImp let super_field; let super_type; - let err = Err(Error::new(r#struct.span(), "Native Class Structs must have at least a reflector field.")); + let err = Err(Error::new( + r#struct.span(), + "Native Class Structs must have at least a reflector field.", + )); match &r#struct.fields { Fields::Named(fields) => match fields.named.first() { Some(field) => { @@ -78,14 +84,24 @@ pub(super) fn impl_js_class_struct(r#struct: &mut ItemStruct) -> Result<[ItemImp return Err(Error::new(super_type.span(), "Superclass Type must be a path.")); } - class_impls(ion, r#struct.span(), &ident.to_string(), &r#type, &super_field, &super_type) + class_impls( + ion, + r#struct.span(), + &ident.to_string(), + &r#type, + &super_field, + &super_type, + ) } -fn class_impls(ion: &TokenStream, span: Span, name: &str, r#type: &Type, super_field: &Member, super_type: &Type) -> Result<[ItemImpl; 6]> { +fn class_impls( + ion: &TokenStream, span: Span, name: &str, r#type: &Type, super_field: &Member, super_type: &Type, +) -> Result<[ItemImpl; 6]> { let from_value = impl_from_value(ion, span, name, r#type, false)?; let from_value_mut = impl_from_value(ion, span, name, r#type, true)?; - let derived_from = parse2(quote_spanned!(span => unsafe impl #ion::class::DerivedFrom<#super_type> for #r#type {}))?; + let derived_from = quote_spanned!(span => unsafe impl #ion::class::DerivedFrom<#super_type> for #r#type {}); + let derived_from = parse2(derived_from)?; let castable = parse2(quote_spanned!(span => impl #ion::class::Castable for #r#type {}))?; let native_object = parse2(quote_spanned!(span => impl #ion::class::NativeObject for #r#type { @@ -150,12 +166,23 @@ fn class_impls(ion: &TokenStream, span: Span, name: &str, r#type: &Type, super_f }))?; operations_native_class.attrs.push(parse_quote!(#[doc(hidden)])); - Ok([from_value, from_value_mut, derived_from, castable, native_object, operations_native_class]) + Ok([ + from_value, + from_value_mut, + derived_from, + castable, + native_object, + operations_native_class, + ]) } fn impl_from_value(ion: &TokenStream, span: Span, name: &str, r#type: &Type, mutable: bool) -> Result { let from_value_error = LitStr::new(&format!("Expected {}", name), span); - let function = if mutable { quote!(get_mut_private) } else { quote!(get_private) }; + let function = if mutable { + quote!(get_mut_private) + } else { + quote!(get_private) + }; let mutable = mutable.then(::default); parse2( diff --git a/ion-proc/src/function/parameters.rs b/ion-proc/src/function/parameters.rs index 40f02c10..c4bf74ac 100644 --- a/ion-proc/src/function/parameters.rs +++ b/ion-proc/src/function/parameters.rs @@ -79,7 +79,8 @@ impl Parameter { for attr in &pat_ty.attrs { if attr.path().is_ident("ion") { - let args: Punctuated = attr.parse_args_with(Punctuated::parse_terminated)?; + let args: Punctuated = + attr.parse_args_with(Punctuated::parse_terminated)?; use ParameterAttribute as PA; for arg in args { @@ -134,7 +135,9 @@ impl Parameter { use Parameter as P; let ty = self.get_type_without_lifetimes(); match self { - P::Regular { pat, conversion, strict, option, .. } => regular_param_statement(ion, pat, &ty, option.as_deref(), conversion, *strict), + P::Regular { pat, conversion, strict, option, .. } => { + regular_param_statement(ion, pat, &ty, option.as_deref(), conversion, *strict) + } P::VarArgs { pat, conversion, strict, .. } => varargs_param_statement(pat, &ty, conversion, *strict), P::Context(pat, _) => parse2(quote!(let #pat: #ty = __cx;)), P::Arguments(pat, _) => parse2(quote!(let #pat: #ty = __args;)), @@ -156,7 +159,8 @@ impl ThisParameter { _ => { for attr in &pat_ty.attrs { if attr.path().is_ident("ion") { - let args: Punctuated = attr.parse_args_with(Punctuated::parse_terminated)?; + let args: Punctuated = + attr.parse_args_with(Punctuated::parse_terminated)?; for arg in args { if let ParameterAttribute::This(_) = arg { return parse_this(pat, ty, class_ty.is_some(), span).map(Some); @@ -191,7 +195,11 @@ impl ThisParameter { pub(crate) fn to_statement(&self, ion: &TokenStream, is_class: bool) -> Result { let ThisParameter { pat, ty, kind } = self; let self_ = parse_quote!(self_); - let pat = if is_class && **pat == parse_quote!(self) { &self_ } else { pat }; + let pat = if is_class && **pat == parse_quote!(self) { + &self_ + } else { + pat + }; let mut ty = ty.clone(); visit_type_mut(&mut LifetimeRemover, &mut ty); @@ -228,7 +236,10 @@ impl Parameters { Ok(Some(this_param)) => { if let Pat::Ident(ident) = (*this_param.pat).clone() { if let Some(this) = &this { - return Some(Err(Error::new(this.1.span(), "Unable to have multiple this/self parameters"))); + return Some(Err(Error::new( + this.1.span(), + "Unable to have multiple this/self parameters", + ))); } this = Some((this_param, ident.ident.clone(), i)); } @@ -301,7 +312,9 @@ impl Parameters { Parameter::Regular { pat, ty, .. } | Parameter::VarArgs { pat, ty, .. } => { parse2(quote_spanned!(pat.span() => #pat: #ty)).unwrap() } - Parameter::Context(pat, ty) | Parameter::Arguments(pat, ty) => parse2(quote_spanned!(pat.span() => #pat: #ty)).unwrap(), + Parameter::Context(pat, ty) | Parameter::Arguments(pat, ty) => { + parse2(quote_spanned!(pat.span() => #pat: #ty)).unwrap() + } }) .collect::>(), ); @@ -310,8 +323,12 @@ impl Parameters { args.insert( *index, match kind { - ThisKind::Ref(lt, mutability) => parse2(quote_spanned!(pat.span() => #pat: &#lt #mutability #ty)).unwrap(), - ThisKind::Object(lt, mutability) => parse2(quote_spanned!(pat.span() => #pat: &#lt #mutability #ty)).unwrap(), + ThisKind::Ref(lt, mutability) => { + parse2(quote_spanned!(pat.span() => #pat: &#lt #mutability #ty)).unwrap() + } + ThisKind::Object(lt, mutability) => { + parse2(quote_spanned!(pat.span() => #pat: &#lt #mutability #ty)).unwrap() + } ThisKind::Owned => parse2(quote_spanned!(pat.span() => #pat: #ty)).unwrap(), }, ); @@ -331,7 +348,9 @@ impl Parameters { } } -fn regular_param_statement(ion: &TokenStream, pat: &Pat, ty: &Type, option: Option<&Type>, conversion: &Expr, strict: bool) -> Result { +fn regular_param_statement( + ion: &TokenStream, pat: &Pat, ty: &Type, option: Option<&Type>, conversion: &Expr, strict: bool, +) -> Result { let pat_str = format_pat(pat); let not_found_error = if let Some(pat) = pat_str { format!("Argument {} at index {{}} was not found.", pat) diff --git a/ion-proc/src/function/wrapper.rs b/ion-proc/src/function/wrapper.rs index 2d41b542..455b4f6d 100644 --- a/ion-proc/src/function/wrapper.rs +++ b/ion-proc/src/function/wrapper.rs @@ -31,7 +31,10 @@ pub(crate) fn impl_wrapper_fn( let inner = impl_inner_fn(function.clone(), ¶meters, class_ty.is_none()); let wrapper_generics: [GenericParam; 2] = [parse_quote!('cx), parse_quote!('a)]; - let mut wrapper_args: Vec = vec![parse_quote!(__cx: &'cx #ion::Context), parse_quote!(__args: &'a mut #ion::Arguments<'cx>)]; + let mut wrapper_args: Vec = vec![ + parse_quote!(__cx: &'cx #ion::Context), + parse_quote!(__args: &'a mut #ion::Arguments<'cx>), + ]; let argument_checker = argument_checker(ion, &function.sig.ident, parameters.nargs.0); diff --git a/ion-proc/src/trace.rs b/ion-proc/src/trace.rs index a64adf2e..7d994f42 100644 --- a/ion-proc/src/trace.rs +++ b/ion-proc/src/trace.rs @@ -71,7 +71,10 @@ fn impl_body(span: Span, data: &Data) -> Result { } })) } - Data::Union(_) => Err(Error::new(span, "#[derive(Traceable) is not implemented for union types.")), + Data::Union(_) => Err(Error::new( + span, + "#[derive(Traceable) is not implemented for union types.", + )), } } diff --git a/ion-proc/src/value/from.rs b/ion-proc/src/value/from.rs index 0f638ee7..fc39a74c 100644 --- a/ion-proc/src/value/from.rs +++ b/ion-proc/src/value/from.rs @@ -81,7 +81,8 @@ pub(crate) fn impl_from_value(mut input: DeriveInput) -> Result { let (body, requires_object) = impl_body(ion, input.span(), &input.data, name, tag, inherit, repr)?; - let object = requires_object.then(|| quote_spanned!(input.span() => let __object = #ion::Object::from_value(cx, value, true, ())?;)); + let object = requires_object + .then(|| quote_spanned!(input.span() => let __object = #ion::Object::from_value(cx, value, true, ())?;)); parse2(quote_spanned!(input.span() => #[automatically_derived] @@ -96,11 +97,14 @@ pub(crate) fn impl_from_value(mut input: DeriveInput) -> Result { )) } -fn impl_body(ion: &TokenStream, span: Span, data: &Data, ident: &Ident, tag: Tag, inherit: bool, repr: Option) -> Result<(Block, bool)> { +fn impl_body( + ion: &TokenStream, span: Span, data: &Data, ident: &Ident, tag: Tag, inherit: bool, repr: Option, +) -> Result<(Block, bool)> { match data { Data::Struct(data) => match &data.fields { Fields::Named(fields) => { - let (requirement, idents, declarations, requires_object) = map_fields(ion, &fields.named, None, tag, inherit)?; + let mapped = map_fields(ion, &fields.named, None, tag, inherit)?; + let (requirement, idents, declarations, requires_object) = mapped; parse2(quote_spanned!(span => { #requirement #(#declarations)* @@ -109,7 +113,8 @@ fn impl_body(ion: &TokenStream, span: Span, data: &Data, ident: &Ident, tag: Tag .map(|b| (b, requires_object)) } Fields::Unnamed(fields) => { - let (requirement, idents, declarations, requires_object) = map_fields(ion, &fields.unnamed, None, tag, inherit)?; + let mapped = map_fields(ion, &fields.unnamed, None, tag, inherit)?; + let (requirement, idents, declarations, requires_object) = mapped; parse2(quote_spanned!(span => { #requirement #(#declarations)* @@ -117,7 +122,9 @@ fn impl_body(ion: &TokenStream, span: Span, data: &Data, ident: &Ident, tag: Tag })) .map(|block| (block, requires_object)) } - Fields::Unit => parse2(quote_spanned!(span => { ::std::result::Result::Ok(Self) })).map(|block| (block, false)), + Fields::Unit => { + parse2(quote_spanned!(span => { ::std::result::Result::Ok(Self) })).map(|block| (block, false)) + } }, Data::Enum(data) => { let unit = data.variants.iter().all(|variant| matches!(variant.fields, Fields::Unit)); @@ -134,10 +141,11 @@ fn impl_body(ion: &TokenStream, span: Span, data: &Data, ident: &Ident, tag: Tag for attr in &variant.attrs { if attr.path().is_ident("ion") { - let args: Punctuated = match attr.parse_args_with(Punctuated::parse_terminated) { - Ok(args) => args, - Err(e) => return Some(Err(e)), - }; + let args: Punctuated = + match attr.parse_args_with(Punctuated::parse_terminated) { + Ok(args) => args, + Err(e) => return Some(Err(e)), + }; for arg in args { match arg { @@ -160,11 +168,12 @@ fn impl_body(ion: &TokenStream, span: Span, data: &Data, ident: &Ident, tag: Tag }); match &variant.fields { Fields::Named(fields) => { - let (requirement, idents, declarations, requires_object) = - match map_fields(ion, &fields.named, Some(variant_string), tag, inherit) { - Ok(mapped) => mapped, - Err(e) => return Some(Err(e)), - }; + let mapped = match map_fields(ion, &fields.named, Some(variant_string), tag, inherit) { + Ok(mapped) => mapped, + Err(e) => return Some(Err(e)), + }; + let (requirement, idents, declarations, requires_object) = mapped; + Some( parse2(quote_spanned!(variant.span() => { let variant: #ion::Result = (|| { @@ -178,11 +187,12 @@ fn impl_body(ion: &TokenStream, span: Span, data: &Data, ident: &Ident, tag: Tag ) } Fields::Unnamed(fields) => { - let (requirement, idents, declarations, requires_object) = - match map_fields(ion, &fields.unnamed, Some(variant_string), tag, inherit) { - Ok(mapped) => mapped, - Err(e) => return Some(Err(e)), - }; + let mapped = match map_fields(ion, &fields.unnamed, Some(variant_string), tag, inherit) { + Ok(mapped) => mapped, + Err(e) => return Some(Err(e)), + }; + let (requirement, idents, declarations, requires_object) = mapped; + Some( parse2(quote_spanned!(variant.span() => { let variant: #ion::Result = (|| { @@ -210,7 +220,10 @@ fn impl_body(ion: &TokenStream, span: Span, data: &Data, ident: &Ident, tag: Tag ); } } - Some(parse2(quote!({return ::std::result::Result::Ok(Self::#variant_ident);})).map(|block| (block, false))) + Some( + parse2(quote!({return ::std::result::Result::Ok(Self::#variant_ident);})) + .map(|block| (block, false)), + ) } } }) @@ -238,7 +251,10 @@ fn impl_body(ion: &TokenStream, span: Span, data: &Data, ident: &Ident, tag: Tag })) .map(|b| (b, requires_object)) } - Data::Union(_) => Err(Error::new(span, "#[derive(FromValue)] is not implemented for union types")), + Data::Union(_) => Err(Error::new( + span, + "#[derive(FromValue)] is not implemented for union types", + )), } } diff --git a/ion-proc/src/visitors.rs b/ion-proc/src/visitors.rs index c9d29d8c..56136bc9 100644 --- a/ion-proc/src/visitors.rs +++ b/ion-proc/src/visitors.rs @@ -14,10 +14,11 @@ impl VisitMut for LifetimeRemover { fn visit_type_path_mut(&mut self, ty: &mut TypePath) { if let Some(segment) = ty.path.segments.last_mut() { if let PathArguments::AngleBracketed(arguments) = &mut segment.arguments { - arguments.args = Punctuated::from_iter(arguments.args.clone().into_iter().filter(|argument| match argument { + let args = arguments.args.clone().into_iter().filter(|argument| match argument { GenericArgument::Lifetime(lt) => *lt == parse_quote!('static), _ => true, - })); + }); + arguments.args = Punctuated::from_iter(args); } } visit_type_path_mut(self, ty); diff --git a/ion/examples/macros/js_fn/complex.rs b/ion/examples/macros/js_fn/complex.rs index fc5bcb6c..deb9ad84 100644 --- a/ion/examples/macros/js_fn/complex.rs +++ b/ion/examples/macros/js_fn/complex.rs @@ -4,7 +4,8 @@ use ion::conversions::ConversionBehavior; #[allow(clippy::too_many_arguments)] #[js_fn] pub fn many_inputs( - _cx: &Context, #[ion(this)] _this: &Object, #[ion(convert = ConversionBehavior::EnforceRange)] _integer: i8, #[ion(strict)] _boolean: bool, - #[ion(convert = (), strict)] _string: String, _function: Function, _promise: Promise, #[ion(varargs)] _values: Vec, + _cx: &Context, #[ion(this)] _this: &Object, #[ion(convert = ConversionBehavior::EnforceRange)] _integer: i8, + #[ion(strict)] _boolean: bool, #[ion(convert = (), strict)] _string: String, _function: Function, + _promise: Promise, #[ion(varargs)] _values: Vec, ) { } diff --git a/ion/src/bigint.rs b/ion/src/bigint.rs index 9223190b..5bdc8eb0 100644 --- a/ion/src/bigint.rs +++ b/ion/src/bigint.rs @@ -8,8 +8,8 @@ use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use mozjs::jsapi::{ - BigIntFitsNumber, BigIntFromBool, BigIntFromInt64, BigIntFromUint64, BigIntIsInt64, BigIntIsNegative, BigIntIsUint64, BigIntToNumber, - BigIntToString, NumberToBigInt, StringToBigInt1, + BigIntFitsNumber, BigIntFromBool, BigIntFromInt64, BigIntFromUint64, BigIntIsInt64, BigIntIsNegative, + BigIntIsUint64, BigIntToNumber, BigIntToString, NumberToBigInt, StringToBigInt1, }; use mozjs::jsapi::BigInt as JSBigInt; use mozjs::jsapi::mozilla::{Range, RangedPtr}; diff --git a/ion/src/class/mod.rs b/ion/src/class/mod.rs index d993e5eb..673018e1 100644 --- a/ion/src/class/mod.rs +++ b/ion/src/class/mod.rs @@ -11,8 +11,8 @@ use std::ptr; use mozjs::glue::JS_GetReservedSlot; use mozjs::jsapi::{ - Handle, JS_GetConstructor, JS_InitClass, JS_InstanceOf, JS_NewObjectWithGivenProto, JS_SetReservedSlot, JSFunction, JSFunctionSpec, JSObject, - JSPropertySpec, + Handle, JS_GetConstructor, JS_InitClass, JS_InstanceOf, JS_NewObjectWithGivenProto, JS_SetReservedSlot, JSFunction, + JSFunctionSpec, JSObject, JSPropertySpec, }; use mozjs::jsval::{PrivateValue, UndefinedValue}; @@ -95,7 +95,8 @@ pub trait ClassDefinition: NativeObject { }; let prototype = cx.root_object(class); - let constructor = Object::from(cx.root_object(unsafe { JS_GetConstructor(cx.as_ptr(), prototype.handle().into()) })); + let constructor = unsafe { JS_GetConstructor(cx.as_ptr(), prototype.handle().into()) }; + let constructor = Object::from(cx.root_object(constructor)); let constructor = Function::from_object(cx, &constructor).unwrap(); let class_info = ClassInfo { @@ -112,7 +113,13 @@ pub trait ClassDefinition: NativeObject { fn new_raw_object(cx: &Context) -> *mut JSObject { let infos = unsafe { &mut (*cx.get_inner_data().as_ptr()).class_infos }; let info = infos.get(&TypeId::of::()).expect("Uninitialised Class"); - unsafe { JS_NewObjectWithGivenProto(cx.as_ptr(), &Self::class().base, Handle::from_marked_location(&info.prototype)) } + unsafe { + JS_NewObjectWithGivenProto( + cx.as_ptr(), + &Self::class().base, + Handle::from_marked_location(&info.prototype), + ) + } } fn new_object(cx: &Context, native: Box) -> *mut JSObject { diff --git a/ion/src/class/native.rs b/ion/src/class/native.rs index 05876cfa..ed9ed912 100644 --- a/ion/src/class/native.rs +++ b/ion/src/class/native.rs @@ -57,7 +57,10 @@ impl Debug for NativeClass { .field("base", &self.base) .field( "prototype_chain", - &format!("[TypeIdWrapper; {}]", self.prototype_chain.iter().filter(|proto| proto.is_some()).count()), + &format!( + "[TypeIdWrapper; {}]", + self.prototype_chain.iter().filter(|proto| proto.is_some()).count() + ), ) .finish() } diff --git a/ion/src/context.rs b/ion/src/context.rs index 7e48f77a..289bd554 100644 --- a/ion/src/context.rs +++ b/ion/src/context.rs @@ -13,8 +13,8 @@ use std::ptr::NonNull; use mozjs::gc::{GCMethods, RootedTraceableSet}; use mozjs::jsapi::{ - BigInt, Heap, JS_GetContextPrivate, JS_SetContextPrivate, JSContext, JSFunction, JSObject, JSScript, JSString, PropertyDescriptor, PropertyKey, - Rooted, Symbol, + BigInt, Heap, JS_GetContextPrivate, JS_SetContextPrivate, JSContext, JSFunction, JSObject, JSScript, JSString, + PropertyDescriptor, PropertyKey, Rooted, Symbol, }; use mozjs::jsval::JSVal; use mozjs::rust::Runtime; diff --git a/ion/src/conversions/value/from.rs b/ion/src/conversions/value/from.rs index ad6f083b..91a87cee 100644 --- a/ion/src/conversions/value/from.rs +++ b/ion/src/conversions/value/from.rs @@ -7,15 +7,17 @@ use mozjs::conversions::{ConversionResult, FromJSValConvertible}; pub use mozjs::conversions::ConversionBehavior; use mozjs::jsapi::{ - AssertSameCompartment, AssertSameCompartment1, ForOfIterator, ForOfIterator_NonIterableBehavior, JSFunction, JSObject, JSString, RootedObject, - RootedValue, + AssertSameCompartment, AssertSameCompartment1, ForOfIterator, ForOfIterator_NonIterableBehavior, JSFunction, + JSObject, JSString, RootedObject, RootedValue, }; use mozjs::jsapi::Symbol as JSSymbol; use mozjs::jsval::JSVal; use mozjs::rust::{ToBoolean, ToNumber, ToString}; use mozjs::typedarray::{JSObjectStorage, TypedArray, TypedArrayElement}; -use crate::{Array, Context, Date, Error, ErrorKind, Exception, Function, Object, Promise, Result, StringRef, Symbol, Value}; +use crate::{ + Array, Context, Date, Error, ErrorKind, Exception, Function, Object, Promise, Result, StringRef, Symbol, Value, +}; use crate::objects::RegExp; use crate::string::byte::{BytePredicate, ByteString}; @@ -54,7 +56,10 @@ macro_rules! impl_from_value_for_integer { fn from_value(cx: &'cx Context, value: &Value, strict: bool, config: ConversionBehavior) -> Result<$ty> { let value = value.handle(); if strict && !value.is_number() { - return Err(Error::new("Expected Number in Strict Conversion", ErrorKind::Type)); + return Err(Error::new( + "Expected Number in Strict Conversion", + ErrorKind::Type, + )); } match unsafe { <$ty>::from_jsval(cx.as_ptr(), value, config) } { @@ -134,7 +139,9 @@ impl<'cx, T: BytePredicate> FromValue<'cx> for ByteString { const INVALID_CHARACTERS: &str = "ByteString contains invalid characters"; let string = StringRef::from_value(cx, value, strict, config)?; match string { - StringRef::Latin1(bstr) => ByteString::from(bstr.to_vec()).ok_or_else(|| Error::new(INVALID_CHARACTERS, ErrorKind::Type)), + StringRef::Latin1(bstr) => { + ByteString::from(bstr.to_vec()).ok_or_else(|| Error::new(INVALID_CHARACTERS, ErrorKind::Type)) + } StringRef::Utf16(wstr) => { let bytes = wstr .as_bytes() @@ -393,7 +400,13 @@ where let iterator = ForOfIteratorGuard::new(cx, &mut iterator); let iterator = &mut *iterator.root; - if unsafe { !iterator.init(value.handle().into(), ForOfIterator_NonIterableBehavior::AllowNonIterable) } { + let init = unsafe { + iterator.init( + value.handle().into(), + ForOfIterator_NonIterableBehavior::AllowNonIterable, + ) + }; + if !init { return Err(Error::new("Failed to Initialise Iterator", ErrorKind::Type)); } diff --git a/ion/src/conversions/value/to.rs b/ion/src/conversions/value/to.rs index c04ac61c..933919a0 100644 --- a/ion/src/conversions/value/to.rs +++ b/ion/src/conversions/value/to.rs @@ -12,7 +12,8 @@ use mozjs::jsapi::{JS_GetFunctionObject, JS_IdToValue, JS_NewStringCopyN, JS_Wra use mozjs::jsapi::PropertyKey as JSPropertyKey; use mozjs::jsapi::Symbol as JSSymbol; use mozjs::jsval::{ - BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, ObjectOrNullValue, ObjectValue, StringValue, SymbolValue, UInt32Value, UndefinedValue, + BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, ObjectOrNullValue, ObjectValue, StringValue, SymbolValue, + UInt32Value, UndefinedValue, }; use mozjs::rust::{maybe_wrap_object_or_null_value, maybe_wrap_object_value, maybe_wrap_value}; diff --git a/ion/src/error.rs b/ion/src/error.rs index 61a9a30e..20aabf38 100644 --- a/ion/src/error.rs +++ b/ion/src/error.rs @@ -37,8 +37,9 @@ impl ErrorKind { /// Returns [ErrorKind::None] for unrecognised prototype keys. pub fn from_proto_key(key: JSProtoKey) -> ErrorKind { use JSProtoKey::{ - JSProto_AggregateError, JSProto_CompileError, JSProto_Error, JSProto_EvalError, JSProto_InternalError, JSProto_LinkError, - JSProto_RangeError, JSProto_ReferenceError, JSProto_RuntimeError, JSProto_SyntaxError, JSProto_TypeError, + JSProto_AggregateError, JSProto_CompileError, JSProto_Error, JSProto_EvalError, JSProto_InternalError, + JSProto_LinkError, JSProto_RangeError, JSProto_ReferenceError, JSProto_RuntimeError, JSProto_SyntaxError, + JSProto_TypeError, }; use ErrorKind as EK; match key { diff --git a/ion/src/exception.rs b/ion/src/exception.rs index 10ef739d..729a3795 100644 --- a/ion/src/exception.rs +++ b/ion/src/exception.rs @@ -6,8 +6,9 @@ use mozjs::conversions::ConversionBehavior; use mozjs::jsapi::{ - ESClass, ExceptionStack, ExceptionStackBehavior, ExceptionStackOrNull, GetPendingExceptionStack, IdentifyStandardInstance, - JS_ClearPendingException, JS_GetPendingException, JS_IsExceptionPending, JS_SetPendingException, Rooted, + ESClass, ExceptionStack, ExceptionStackBehavior, ExceptionStackOrNull, GetPendingExceptionStack, + IdentifyStandardInstance, JS_ClearPendingException, JS_GetPendingException, JS_IsExceptionPending, + JS_SetPendingException, Rooted, }; use mozjs::jsval::{JSVal, ObjectValue}; #[cfg(feature = "sourcemap")] @@ -136,7 +137,13 @@ impl ThrowException for Exception { Exception::Error(error) => { if let Error { object: Some(object), .. } = error { let exception = Value::from(cx.root_value(ObjectValue(*object))); - unsafe { JS_SetPendingException(cx.as_ptr(), exception.handle().into(), ExceptionStackBehavior::DoNotCapture) } + unsafe { + JS_SetPendingException( + cx.as_ptr(), + exception.handle().into(), + ExceptionStackBehavior::DoNotCapture, + ) + } } else { error.throw(cx); } diff --git a/ion/src/flags.rs b/ion/src/flags.rs index 4b78bedc..63590cdf 100644 --- a/ion/src/flags.rs +++ b/ion/src/flags.rs @@ -11,9 +11,9 @@ use std::str; use arrayvec::ArrayVec; use bitflags::{bitflags, Flags}; use mozjs::jsapi::{ - JSITER_FORAWAITOF, JSITER_HIDDEN, JSITER_OWNONLY, JSITER_PRIVATE, JSITER_SYMBOLS, JSITER_SYMBOLSONLY, JSPROP_ENUMERATE, JSPROP_PERMANENT, - JSPROP_READONLY, JSPROP_RESOLVING, RegExpFlag_DotAll, RegExpFlag_Global, RegExpFlag_HasIndices, RegExpFlag_IgnoreCase, RegExpFlag_Multiline, - RegExpFlag_Sticky, RegExpFlag_Unicode, + JSITER_FORAWAITOF, JSITER_HIDDEN, JSITER_OWNONLY, JSITER_PRIVATE, JSITER_SYMBOLS, JSITER_SYMBOLSONLY, + JSPROP_ENUMERATE, JSPROP_PERMANENT, JSPROP_READONLY, JSPROP_RESOLVING, RegExpFlag_DotAll, RegExpFlag_Global, + RegExpFlag_HasIndices, RegExpFlag_IgnoreCase, RegExpFlag_Multiline, RegExpFlag_Sticky, RegExpFlag_Unicode, }; use mozjs::jsapi::RegExpFlags as REFlags; diff --git a/ion/src/format/array.rs b/ion/src/format/array.rs index cc61b423..c428eda3 100644 --- a/ion/src/format/array.rs +++ b/ion/src/format/array.rs @@ -45,7 +45,11 @@ impl Display for ArrayDisplay<'_> { for value in vec.into_iter().take(len) { f.write_str(&inner)?; - write!(f, "{}", format_value(self.cx, self.cfg.depth(self.cfg.depth + 1).quoted(true), &value))?; + write!( + f, + "{}", + format_value(self.cx, self.cfg.depth(self.cfg.depth + 1).quoted(true), &value) + )?; write!(f, "{}", ",".color(colour))?; f.write_str(NEWLINE)?; } @@ -56,7 +60,11 @@ impl Display for ArrayDisplay<'_> { let len = length.clamp(0, 3); for (i, value) in vec.into_iter().enumerate().take(len) { - write!(f, "{}", format_value(self.cx, self.cfg.depth(self.cfg.depth + 1).quoted(true), &value))?; + write!( + f, + "{}", + format_value(self.cx, self.cfg.depth(self.cfg.depth + 1).quoted(true), &value) + )?; if i != len - 1 { write!(f, "{}", ",".color(colour))?; diff --git a/ion/src/format/object.rs b/ion/src/format/object.rs index bb3073b0..a462d736 100644 --- a/ion/src/format/object.rs +++ b/ion/src/format/object.rs @@ -48,13 +48,39 @@ impl Display for ObjectDisplay<'_> { let class = self.object.get_builtin_class(cx); match class { - ESC::Boolean | ESC::Number | ESC::String | ESC::BigInt => write!(f, "{}", format_boxed(cx, cfg, &self.object)), - ESC::Array => write!(f, "{}", format_array(cx, cfg, &Array::from(cx, object.into_local()).unwrap())), - ESC::Object => write!(f, "{}", format_plain_object(cx, cfg, &Object::from(object.into_local()))), - ESC::Date => write!(f, "{}", format_date(cx, cfg, &Date::from(cx, object.into_local()).unwrap())), - ESC::Promise => write!(f, "{}", format_promise(cx, cfg, &Promise::from(object.into_local()).unwrap())), - ESC::RegExp => write!(f, "{}", format_regexp(cx, cfg, &RegExp::from(cx, object.into_local()).unwrap())), - ESC::Function => write!(f, "{}", format_function(cx, cfg, &Function::from_object(cx, &self.object).unwrap())), + ESC::Boolean | ESC::Number | ESC::String | ESC::BigInt => { + write!(f, "{}", format_boxed(cx, cfg, &self.object)) + } + ESC::Array => write!( + f, + "{}", + format_array(cx, cfg, &Array::from(cx, object.into_local()).unwrap()) + ), + ESC::Object => write!( + f, + "{}", + format_plain_object(cx, cfg, &Object::from(object.into_local())) + ), + ESC::Date => write!( + f, + "{}", + format_date(cx, cfg, &Date::from(cx, object.into_local()).unwrap()) + ), + ESC::Promise => write!( + f, + "{}", + format_promise(cx, cfg, &Promise::from(object.into_local()).unwrap()) + ), + ESC::RegExp => write!( + f, + "{}", + format_regexp(cx, cfg, &RegExp::from(cx, object.into_local()).unwrap()) + ), + ESC::Function => write!( + f, + "{}", + format_function(cx, cfg, &Function::from_object(cx, &self.object).unwrap()) + ), ESC::Error => match Exception::from_object(cx, &self.object) { Exception::Error(error) => f.write_str(&error.format()), _ => unreachable!("Expected Error"), diff --git a/ion/src/format/symbol.rs b/ion/src/format/symbol.rs index 987f8814..67523b9b 100644 --- a/ion/src/format/symbol.rs +++ b/ion/src/format/symbol.rs @@ -37,24 +37,21 @@ impl Display for SymbolDisplay<'_> { match code { SymbolCode::WellKnown(code) => write!(f, "{}{}", "Symbol.".color(colour), code.identifier().color(colour)), - SymbolCode::PrivateNameSymbol => write!( - f, - "{}", - self.symbol - .description(self.cx) - .expect("Expected Description on Private Name Symbol") - .color(colour) - ), code => { - let description = self.symbol.description(self.cx).expect("Expected Description on Non-Well-Known Symbol"); + let description = self + .symbol + .description(self.cx) + .expect("Expected Description on Non-Well-Known Symbol") + .color(colour); match code { + SymbolCode::PrivateNameSymbol => return write!(f, "{}", description), SymbolCode::InSymbolRegistry => write!(f, "{}", "Symbol.for(".color(colour),)?, SymbolCode::UniqueSymbol => write!(f, "{}", "Symbol(".color(colour),)?, _ => unreachable!(), } - write!(f, "{}", description.color(self.cfg.colours.string))?; + write!(f, "{}", description)?; write!(f, "{}", ")".color(colour)) } } diff --git a/ion/src/functions/closure.rs b/ion/src/functions/closure.rs index 49c1c2e4..f25b215c 100644 --- a/ion/src/functions/closure.rs +++ b/ion/src/functions/closure.rs @@ -9,7 +9,8 @@ use std::ptr; use mozjs::glue::JS_GetReservedSlot; use mozjs::jsapi::{ - GCContext, GetFunctionNativeReserved, JS_NewObject, JS_SetReservedSlot, JSClass, JSCLASS_BACKGROUND_FINALIZE, JSClassOps, JSContext, JSObject, + GCContext, GetFunctionNativeReserved, JS_NewObject, JS_SetReservedSlot, JSClass, JSCLASS_BACKGROUND_FINALIZE, + JSClassOps, JSContext, JSObject, }; use mozjs::jsval::{JSVal, PrivateValue, UndefinedValue}; diff --git a/ion/src/functions/function.rs b/ion/src/functions/function.rs index 6fd39718..56dcdcc7 100644 --- a/ion/src/functions/function.rs +++ b/ion/src/functions/function.rs @@ -9,9 +9,10 @@ use std::ops::Deref; use mozjs::conversions::jsstr_to_string; use mozjs::jsapi::{ - HandleValueArray, JS_CallFunction, JS_DecompileFunction, JS_GetFunctionArity, JS_GetFunctionDisplayId, JS_GetFunctionId, JS_GetFunctionLength, - JS_GetFunctionObject, JS_GetObjectFunction, JS_IsBuiltinEvalFunction, JS_IsBuiltinFunctionConstructor, JS_IsConstructor, JS_NewFunction, - JS_ObjectIsFunction, JSContext, JSFunction, JSFunctionSpec, JSObject, NewFunctionFromSpec1, NewFunctionWithReserved, SetFunctionNativeReserved, + HandleValueArray, JS_CallFunction, JS_DecompileFunction, JS_GetFunctionArity, JS_GetFunctionDisplayId, + JS_GetFunctionId, JS_GetFunctionLength, JS_GetFunctionObject, JS_GetObjectFunction, JS_IsBuiltinEvalFunction, + JS_IsBuiltinFunctionConstructor, JS_IsConstructor, JS_NewFunction, JS_ObjectIsFunction, JSContext, JSFunction, + JSFunctionSpec, JSObject, NewFunctionFromSpec1, NewFunctionWithReserved, SetFunctionNativeReserved, }; use mozjs::jsval::{JSVal, ObjectValue}; @@ -31,10 +32,13 @@ pub struct Function<'f> { impl<'f> Function<'f> { /// Creates a new [Function] with the given name, native function, number of arguments and flags. - pub fn new(cx: &'f Context, name: &str, func: Option, nargs: u32, flags: PropertyFlags) -> Function<'f> { + pub fn new( + cx: &'f Context, name: &str, func: Option, nargs: u32, flags: PropertyFlags, + ) -> Function<'f> { let name = CString::new(name).unwrap(); Function { - function: cx.root_function(unsafe { JS_NewFunction(cx.as_ptr(), func, nargs, flags.bits() as u32, name.as_ptr()) }), + function: cx + .root_function(unsafe { JS_NewFunction(cx.as_ptr(), func, nargs, flags.bits() as u32, name.as_ptr()) }), } } @@ -46,7 +50,9 @@ impl<'f> Function<'f> { } /// Creates a new [Function] with a [Closure]. - pub fn from_closure(cx: &'f Context, name: &str, closure: Box, nargs: u32, flags: PropertyFlags) -> Function<'f> { + pub fn from_closure( + cx: &'f Context, name: &str, closure: Box, nargs: u32, flags: PropertyFlags, + ) -> Function<'f> { unsafe { let function = Function { function: cx.root_function(NewFunctionWithReserved( @@ -58,7 +64,11 @@ impl<'f> Function<'f> { )), }; let closure_object = create_closure_object(cx, closure); - SetFunctionNativeReserved(JS_GetFunctionObject(function.get()), 0, &ObjectValue(closure_object.handle().get())); + SetFunctionNativeReserved( + JS_GetFunctionObject(function.get()), + 0, + &ObjectValue(closure_object.handle().get()), + ); function } } @@ -116,17 +126,31 @@ impl<'f> Function<'f> { /// Calls the [Function] with the given `this` [Object] and arguments. /// Returns the result of the [Function] as a [Value]. /// Returns [Err] if the function call fails or an exception occurs. - pub fn call<'cx>(&self, cx: &'cx Context, this: &Object, args: &[Value]) -> Result, Option> { + pub fn call<'cx>( + &self, cx: &'cx Context, this: &Object, args: &[Value], + ) -> Result, Option> { let args: Vec<_> = args.iter().map(|a| a.get()).collect(); - self.call_with_handle(cx, this, unsafe { HandleValueArray::from_rooted_slice(args.as_slice()) }) + self.call_with_handle(cx, this, unsafe { + HandleValueArray::from_rooted_slice(args.as_slice()) + }) } /// Calls the [Function] with the given `this` [Object] and arguments as a [HandleValueArray]. /// Returns the result of the [Function] as a [Value]. /// Returns [Err] if the function call fails or an exception occurs. - pub fn call_with_handle<'cx>(&self, cx: &'cx Context, this: &Object, args: HandleValueArray) -> Result, Option> { + pub fn call_with_handle<'cx>( + &self, cx: &'cx Context, this: &Object, args: HandleValueArray, + ) -> Result, Option> { let mut rval = Value::undefined(cx); - if unsafe { JS_CallFunction(cx.as_ptr(), this.handle().into(), self.handle().into(), &args, rval.handle_mut().into()) } { + if unsafe { + JS_CallFunction( + cx.as_ptr(), + this.handle().into(), + self.handle().into(), + &args, + rval.handle_mut().into(), + ) + } { Ok(rval) } else { Err(ErrorReport::new_with_exception_stack(cx)) diff --git a/ion/src/functions/mod.rs b/ion/src/functions/mod.rs index 616b6b55..52d9155f 100644 --- a/ion/src/functions/mod.rs +++ b/ion/src/functions/mod.rs @@ -32,7 +32,9 @@ pub fn __handle_native_function_result(cx: &Context, result: Result>, this: &Object, rval: &mut Value) -> bool { +pub fn __handle_native_constructor_result( + cx: &Context, result: Result>, this: &Object, rval: &mut Value, +) -> bool { match result { Ok(Ok(_)) => { this.to_value(cx, rval); diff --git a/ion/src/module.rs b/ion/src/module.rs index b66e2236..aa8f2a85 100644 --- a/ion/src/module.rs +++ b/ion/src/module.rs @@ -8,8 +8,8 @@ use std::path::Path; use std::ptr; use mozjs::jsapi::{ - CompileModule, CreateModuleRequest, GetModuleRequestSpecifier, Handle, JS_GetRuntime, JSContext, JSObject, ModuleEvaluate, ModuleLink, - SetModuleMetadataHook, SetModulePrivate, SetModuleResolveHook, + CompileModule, CreateModuleRequest, GetModuleRequestSpecifier, Handle, JS_GetRuntime, JSContext, JSObject, + ModuleEvaluate, ModuleLink, SetModuleMetadataHook, SetModulePrivate, SetModuleResolveHook, }; use mozjs::jsval::JSVal; use mozjs::rust::{CompileOptionsWrapper, transform_u16_to_source_text}; @@ -106,7 +106,9 @@ impl<'cx> Module<'cx> { /// On success, returns the compiled module object and a promise. The promise resolves with the return value of the module. /// The promise is a byproduct of enabling top-level await. #[allow(clippy::result_large_err)] - pub fn compile(cx: &'cx Context, filename: &str, path: Option<&Path>, script: &str) -> Result<(Module<'cx>, Option>), ModuleError> { + pub fn compile( + cx: &'cx Context, filename: &str, path: Option<&Path>, script: &str, + ) -> Result<(Module<'cx>, Option>), ModuleError> { let script: Vec = script.encode_utf16().collect(); let mut source = transform_u16_to_source_text(script.as_slice()); let filename = path.and_then(Path::to_str).unwrap_or(filename); @@ -139,7 +141,10 @@ impl<'cx> Module<'cx> { Err(error) => Err(ModuleError::new(error, ModuleErrorKind::Evaluation)), } } else { - Err(ModuleError::new(ErrorReport::new(cx).unwrap(), ModuleErrorKind::Compilation)) + Err(ModuleError::new( + ErrorReport::new(cx).unwrap(), + ModuleErrorKind::Compilation, + )) } } @@ -192,7 +197,9 @@ impl ModuleLoader for () { /// Initialises a module loader in the current runtime. pub fn init_module_loader(cx: &Context, loader: ML) { - unsafe extern "C" fn resolve(cx: *mut JSContext, private: Handle, request: Handle<*mut JSObject>) -> *mut JSObject { + unsafe extern "C" fn resolve( + cx: *mut JSContext, private: Handle, request: Handle<*mut JSObject>, + ) -> *mut JSObject { let cx = unsafe { Context::new_unchecked(cx) }; let loader = unsafe { &mut (*cx.get_inner_data().as_ptr()).module_loader }; @@ -206,7 +213,9 @@ pub fn init_module_loader(cx: &Context, loader: ML) .unwrap_or_else(ptr::null_mut) } - unsafe extern "C" fn metadata(cx: *mut JSContext, private_data: Handle, metadata: Handle<*mut JSObject>) -> bool { + unsafe extern "C" fn metadata( + cx: *mut JSContext, private_data: Handle, metadata: Handle<*mut JSObject>, + ) -> bool { let cx = unsafe { Context::new_unchecked(cx) }; let loader = unsafe { &mut (*cx.get_inner_data().as_ptr()).module_loader }; diff --git a/ion/src/objects/array.rs b/ion/src/objects/array.rs index add17a1e..8ef00b38 100644 --- a/ion/src/objects/array.rs +++ b/ion/src/objects/array.rs @@ -105,7 +105,9 @@ impl<'a> Array<'a> { /// Gets the value at the given index of the [Array] as a Rust type. /// Returns [None] if there is no value at the given index or conversion to the Rust type fails. - pub fn get_as<'cx, T: FromValue<'cx>>(&self, cx: &'cx Context, index: u32, strict: bool, config: T::Config) -> Option { + pub fn get_as<'cx, T: FromValue<'cx>>( + &self, cx: &'cx Context, index: u32, strict: bool, config: T::Config, + ) -> Option { self.arr.get_as(cx, index, strict, config) } @@ -129,7 +131,9 @@ impl<'a> Array<'a> { /// Defines the Rust type at the given index of the [Array] with the given attributes. /// Returns `false` if the element cannot be defined. - pub fn define_as<'cx, T: ToValue<'cx> + ?Sized>(&mut self, cx: &'cx Context, index: u32, value: &T, attrs: PropertyFlags) -> bool { + pub fn define_as<'cx, T: ToValue<'cx> + ?Sized>( + &mut self, cx: &'cx Context, index: u32, value: &T, attrs: PropertyFlags, + ) -> bool { self.arr.define_as(cx, index, value, attrs) } diff --git a/ion/src/objects/date.rs b/ion/src/objects/date.rs index 327ba509..5cadea0f 100644 --- a/ion/src/objects/date.rs +++ b/ion/src/objects/date.rs @@ -27,9 +27,8 @@ impl<'d> Date<'d> { /// Creates a new [Date] with the given time. pub fn from_date(cx: &'d Context, time: DateTime) -> Date<'d> { - Date { - date: cx.root_object(unsafe { NewDateObject(cx.as_ptr(), ClippedTime { t: time.timestamp_millis() as f64 }) }), - } + let date = unsafe { NewDateObject(cx.as_ptr(), ClippedTime { t: time.timestamp_millis() as f64 }) }; + Date { date: cx.root_object(date) } } /// Creates a [Date] from an object. @@ -59,7 +58,9 @@ impl<'d> Date<'d> { /// Converts the [Date] to a [DateTime]. pub fn to_date(&self, cx: &Context) -> Option> { let mut milliseconds: f64 = f64::MAX; - if !unsafe { DateGetMsecSinceEpoch(cx.as_ptr(), self.date.handle().into(), &mut milliseconds) } || milliseconds == f64::MAX { + if !unsafe { DateGetMsecSinceEpoch(cx.as_ptr(), self.date.handle().into(), &mut milliseconds) } + || milliseconds == f64::MAX + { None } else { Utc.timestamp_millis_opt(milliseconds as i64).single() diff --git a/ion/src/objects/descriptor.rs b/ion/src/objects/descriptor.rs index c71a6ea4..91e0fb97 100644 --- a/ion/src/objects/descriptor.rs +++ b/ion/src/objects/descriptor.rs @@ -24,7 +24,9 @@ impl<'pd> PropertyDescriptor<'pd> { desc } - pub fn new_accessor(cx: &'pd Context, getter: &Function, setter: &Function, attrs: PropertyFlags) -> PropertyDescriptor<'pd> { + pub fn new_accessor( + cx: &'pd Context, getter: &Function, setter: &Function, attrs: PropertyFlags, + ) -> PropertyDescriptor<'pd> { let getter = getter.to_object(cx); let setter = setter.to_object(cx); let mut desc = PropertyDescriptor::from(cx.root_property_descriptor(JSPropertyDescriptor::default())); @@ -43,14 +45,20 @@ impl<'pd> PropertyDescriptor<'pd> { let mut desc = PropertyDescriptor::from(cx.root_property_descriptor(JSPropertyDescriptor::default())); let desc_value = Value::object(cx, object); unsafe { - ObjectToCompletePropertyDescriptor(cx.as_ptr(), object.handle().into(), desc_value.handle().into(), desc.handle_mut().into()) - .then_some(desc) + ObjectToCompletePropertyDescriptor( + cx.as_ptr(), + object.handle().into(), + desc_value.handle().into(), + desc.handle_mut().into(), + ) + .then_some(desc) } } pub fn to_object<'cx>(&self, cx: &'cx Context) -> Option> { let mut value = Value::undefined(cx); - unsafe { FromPropertyDescriptor(cx.as_ptr(), self.handle().into(), value.handle_mut().into()) }.then(|| value.to_object(cx)) + unsafe { FromPropertyDescriptor(cx.as_ptr(), self.handle().into(), value.handle_mut().into()) } + .then(|| value.to_object(cx)) } pub fn is_configurable(&self) -> bool { diff --git a/ion/src/objects/iterator.rs b/ion/src/objects/iterator.rs index 076afa67..4e2209cf 100644 --- a/ion/src/objects/iterator.rs +++ b/ion/src/objects/iterator.rs @@ -10,8 +10,8 @@ use std::ptr; use mozjs::gc::Traceable; use mozjs::glue::JS_GetReservedSlot; use mozjs::jsapi::{ - GCContext, GetRealmIteratorPrototype, Heap, JSClass, JSCLASS_BACKGROUND_FINALIZE, JSClassOps, JSContext, JSFunctionSpec, JSNativeWrapper, - JSObject, JSTracer, + GCContext, GetRealmIteratorPrototype, Heap, JSClass, JSCLASS_BACKGROUND_FINALIZE, JSClassOps, JSContext, + JSFunctionSpec, JSNativeWrapper, JSObject, JSTracer, }; use mozjs::jsval::{JSVal, NullValue}; @@ -171,7 +171,16 @@ static ITERATOR_CLASS: NativeClass = NativeClass { ext: ptr::null_mut(), oOps: ptr::null_mut(), }, - prototype_chain: [Some(&TypeIdWrapper::::new()), None, None, None, None, None, None, None], + prototype_chain: [ + Some(&TypeIdWrapper::::new()), + None, + None, + None, + None, + None, + None, + None, + ], }; static ITERATOR_METHODS: &[JSFunctionSpec] = &[ @@ -210,7 +219,10 @@ impl ClassDefinition for Iterator { } fn parent_class_info(cx: &Context) -> Option<(&'static NativeClass, Local<*mut JSObject>)> { - Some((&ITERATOR_CLASS, cx.root_object(unsafe { GetRealmIteratorPrototype(cx.as_ptr()) }))) + Some(( + &ITERATOR_CLASS, + cx.root_object(unsafe { GetRealmIteratorPrototype(cx.as_ptr()) }), + )) } fn constructor() -> (NativeFunction, u32) { diff --git a/ion/src/objects/mod.rs b/ion/src/objects/mod.rs index 2603267b..835da636 100644 --- a/ion/src/objects/mod.rs +++ b/ion/src/objects/mod.rs @@ -6,7 +6,10 @@ use std::ptr; -use mozjs::jsapi::{JS_NewGlobalObject, JSClass, JSCLASS_RESERVED_SLOTS_MASK, JSCLASS_RESERVED_SLOTS_SHIFT, JSPrincipals, OnNewGlobalHookOption}; +use mozjs::jsapi::{ + JS_NewGlobalObject, JSClass, JSCLASS_RESERVED_SLOTS_MASK, JSCLASS_RESERVED_SLOTS_SHIFT, JSPrincipals, + OnNewGlobalHookOption, +}; use mozjs::rust::{RealmOptions, SIMPLE_GLOBAL_CLASS}; pub use array::Array; @@ -52,5 +55,11 @@ pub fn new_global<'cx, P: Into>, R: Into Object { - new_global(cx, &SIMPLE_GLOBAL_CLASS, None, OnNewGlobalHookOption::FireOnNewGlobalHook, None) + new_global( + cx, + &SIMPLE_GLOBAL_CLASS, + None, + OnNewGlobalHookOption::FireOnNewGlobalHook, + None, + ) } diff --git a/ion/src/objects/object.rs b/ion/src/objects/object.rs index 8fc00196..a75f85d8 100644 --- a/ion/src/objects/object.rs +++ b/ion/src/objects/object.rs @@ -11,9 +11,10 @@ use std::ops::{Deref, DerefMut}; use std::slice; use mozjs::jsapi::{ - CurrentGlobalOrNull, ESClass, GetBuiltinClass, GetPropertyKeys, JS_DefineFunctionById, JS_DefineFunctions, JS_DefineFunctionsWithHelp, - JS_DefineProperties, JS_DefinePropertyById2, JS_DeletePropertyById, JS_GetPropertyById, JS_HasOwnPropertyById, JS_HasPropertyById, - JS_NewPlainObject, JS_SetPropertyById, JSFunctionSpec, JSFunctionSpecWithHelp, JSObject, JSPropertySpec, Unbox, + CurrentGlobalOrNull, ESClass, GetBuiltinClass, GetPropertyKeys, JS_DefineFunctionById, JS_DefineFunctions, + JS_DefineFunctionsWithHelp, JS_DefineProperties, JS_DefinePropertyById2, JS_DeletePropertyById, JS_GetPropertyById, + JS_HasOwnPropertyById, JS_HasPropertyById, JS_NewPlainObject, JS_SetPropertyById, JSFunctionSpec, + JSFunctionSpecWithHelp, JSObject, JSPropertySpec, Unbox, }; use mozjs::jsapi::PropertyKey as JSPropertyKey; use mozjs::jsval::NullValue; @@ -83,7 +84,14 @@ impl<'o> Object<'o> { let key = key.to_key(cx).unwrap(); if self.has(cx, &key) { let mut rval = Value::undefined(cx); - unsafe { JS_GetPropertyById(cx.as_ptr(), self.handle().into(), key.handle().into(), rval.handle_mut().into()) }; + unsafe { + JS_GetPropertyById( + cx.as_ptr(), + self.handle().into(), + key.handle().into(), + rval.handle_mut().into(), + ) + }; Some(rval) } else { None @@ -92,7 +100,9 @@ impl<'o> Object<'o> { /// Gets the value at the given key of the [Object]. as a Rust type. /// Returns [None] if the object does not contain the key or conversion to the Rust type fails. - pub fn get_as<'cx, K: ToPropertyKey<'cx>, T: FromValue<'cx>>(&self, cx: &'cx Context, key: K, strict: bool, config: T::Config) -> Option { + pub fn get_as<'cx, K: ToPropertyKey<'cx>, T: FromValue<'cx>>( + &self, cx: &'cx Context, key: K, strict: bool, config: T::Config, + ) -> Option { self.get(cx, key).and_then(|val| T::from_value(cx, &val, strict, config).ok()) } @@ -101,20 +111,31 @@ impl<'o> Object<'o> { /// Returns `false` if the property cannot be set. pub fn set<'cx, K: ToPropertyKey<'cx>>(&mut self, cx: &'cx Context, key: K, value: &Value) -> bool { let key = key.to_key(cx).unwrap(); - unsafe { JS_SetPropertyById(cx.as_ptr(), self.handle().into(), key.handle().into(), value.handle().into()) } + unsafe { + JS_SetPropertyById( + cx.as_ptr(), + self.handle().into(), + key.handle().into(), + value.handle().into(), + ) + } } /// Sets the Rust type at the given key of the [Object]. /// /// Returns `false` if the property cannot be set. - pub fn set_as<'cx, K: ToPropertyKey<'cx>, T: ToValue<'cx> + ?Sized>(&mut self, cx: &'cx Context, key: K, value: &T) -> bool { + pub fn set_as<'cx, K: ToPropertyKey<'cx>, T: ToValue<'cx> + ?Sized>( + &mut self, cx: &'cx Context, key: K, value: &T, + ) -> bool { self.set(cx, key, &value.as_value(cx)) } /// Defines the [Value] at the given key of the [Object] with the given attributes. /// /// Returns `false` if the property cannot be defined. - pub fn define<'cx, K: ToPropertyKey<'cx>>(&mut self, cx: &'cx Context, key: K, value: &Value, attrs: PropertyFlags) -> bool { + pub fn define<'cx, K: ToPropertyKey<'cx>>( + &mut self, cx: &'cx Context, key: K, value: &Value, attrs: PropertyFlags, + ) -> bool { let key = key.to_key(cx).unwrap(); unsafe { JS_DefinePropertyById2( @@ -159,7 +180,10 @@ impl<'o> Object<'o> { /// Defines methods on the objects using the given [specs](JSFunctionSpec). /// /// The final element of the `methods` slice must be `JSFunctionSpec::ZERO`. - #[cfg_attr(feature = "macros", doc = "\nThey can be created through [function_spec](crate::function_spec).")] + #[cfg_attr( + feature = "macros", + doc = "\nThey can be created through [function_spec](crate::function_spec)." + )] pub unsafe fn define_methods(&mut self, cx: &Context, methods: &[JSFunctionSpec]) -> bool { unsafe { JS_DefineFunctions(cx.as_ptr(), self.handle().into(), methods.as_ptr()) } } @@ -184,7 +208,14 @@ impl<'o> Object<'o> { pub fn delete<'cx, K: ToPropertyKey<'cx>>(&self, cx: &'cx Context, key: K) -> bool { let key = key.to_key(cx).unwrap(); let mut result = MaybeUninit::uninit(); - unsafe { JS_DeletePropertyById(cx.as_ptr(), self.handle().into(), key.handle().into(), result.as_mut_ptr()) } + unsafe { + JS_DeletePropertyById( + cx.as_ptr(), + self.handle().into(), + key.handle().into(), + result.as_mut_ptr(), + ) + } } /// Gets the builtin class of the object as described in the ECMAScript specification. diff --git a/ion/src/objects/promise.rs b/ion/src/objects/promise.rs index 86134a45..3ece4936 100644 --- a/ion/src/objects/promise.rs +++ b/ion/src/objects/promise.rs @@ -12,8 +12,8 @@ use futures::executor::block_on; use libffi::high::ClosureOnce3; use mozjs::glue::JS_GetPromiseResult; use mozjs::jsapi::{ - AddPromiseReactions, GetPromiseID, GetPromiseState, IsPromiseObject, JSContext, JSObject, NewPromiseObject, PromiseState, RejectPromise, - ResolvePromise, + AddPromiseReactions, GetPromiseID, GetPromiseState, IsPromiseObject, JSContext, JSObject, NewPromiseObject, + PromiseState, RejectPromise, ResolvePromise, }; use mozjs::jsval::JSVal; use mozjs::rust::HandleObject; @@ -155,7 +155,9 @@ impl<'p> Promise<'p> { /// `on_resolved` is similar to calling `.then()` on a promise. /// /// `on_rejected` is similar to calling `.catch()` on a promise. - pub fn add_reactions(&self, cx: &'_ Context, on_resolved: Option>, on_rejected: Option>) -> bool { + pub fn add_reactions( + &self, cx: &'_ Context, on_resolved: Option>, on_rejected: Option>, + ) -> bool { let mut resolved = Object::null(cx); let mut rejected = Object::null(cx); if let Some(on_resolved) = on_resolved { @@ -164,7 +166,14 @@ impl<'p> Promise<'p> { if let Some(on_rejected) = on_rejected { rejected.handle_mut().set(on_rejected.to_object(cx).handle().get()); } - unsafe { AddPromiseReactions(cx.as_ptr(), self.handle().into(), resolved.handle().into(), rejected.handle().into()) } + unsafe { + AddPromiseReactions( + cx.as_ptr(), + self.handle().into(), + resolved.handle().into(), + rejected.handle().into(), + ) + } } /// Resolves the [Promise] with the given [Value]. diff --git a/ion/src/objects/regexp.rs b/ion/src/objects/regexp.rs index 98f89c1f..9b512ea0 100644 --- a/ion/src/objects/regexp.rs +++ b/ion/src/objects/regexp.rs @@ -8,7 +8,10 @@ use std::ops::{Deref, DerefMut}; use std::ptr::NonNull; use mozjs::glue::JS_GetRegExpFlags; -use mozjs::jsapi::{CheckRegExpSyntax, ExecuteRegExp, ExecuteRegExpNoStatics, GetRegExpSource, JSObject, NewUCRegExpObject, ObjectIsRegExp}; +use mozjs::jsapi::{ + CheckRegExpSyntax, ExecuteRegExp, ExecuteRegExpNoStatics, GetRegExpSource, JSObject, NewUCRegExpObject, + ObjectIsRegExp, +}; use mozjs::jsapi::RegExpFlags as REFlags; use crate::{Context, Local, Object, Value}; @@ -76,12 +79,16 @@ impl<'r> RegExp<'r> { self.execute(cx, string, index, false, &mut rval, true).then_some(rval) } - pub fn execute_match_no_static<'cx>(&self, cx: &'cx Context, string: &str, index: &mut usize) -> Option> { + pub fn execute_match_no_static<'cx>( + &self, cx: &'cx Context, string: &str, index: &mut usize, + ) -> Option> { let mut rval = Value::null(cx); self.execute(cx, string, index, false, &mut rval, false).then_some(rval) } - fn execute<'cx>(&self, cx: &'cx Context, string: &str, index: &mut usize, test: bool, rval: &mut Value<'cx>, with_static: bool) -> bool { + fn execute<'cx>( + &self, cx: &'cx Context, string: &str, index: &mut usize, test: bool, rval: &mut Value<'cx>, with_static: bool, + ) -> bool { let string: Vec = string.encode_utf16().collect(); if with_static { let global = Object::global(cx); @@ -115,7 +122,15 @@ impl<'r> RegExp<'r> { pub fn check_syntax<'cx>(cx: &'cx Context, source: &str, flags: RegExpFlags) -> Result<(), Value<'cx>> { let source: Vec = source.encode_utf16().collect(); let mut error = Value::undefined(cx); - let check = unsafe { CheckRegExpSyntax(cx.as_ptr(), source.as_ptr(), source.len(), flags.into(), error.handle_mut().into()) }; + let check = unsafe { + CheckRegExpSyntax( + cx.as_ptr(), + source.as_ptr(), + source.len(), + flags.into(), + error.handle_mut().into(), + ) + }; if check { if error.handle().is_undefined() { Ok(()) diff --git a/ion/src/objects/typedarray.rs b/ion/src/objects/typedarray.rs index fe9b4bed..1ad3e039 100644 --- a/ion/src/objects/typedarray.rs +++ b/ion/src/objects/typedarray.rs @@ -21,10 +21,20 @@ macro_rules! impl_typedarray_wrapper { impl $typedarray { pub fn to_object<'cx>(&self, cx: &'cx Context) -> Result> { let mut typed_array = Object::new(cx); - if unsafe { mozjs::typedarray::$typedarray::create(cx.as_ptr(), CreateWith::Slice(&self.buf), typed_array.handle_mut()).is_ok() } { + if unsafe { + mozjs::typedarray::$typedarray::create( + cx.as_ptr(), + CreateWith::Slice(&self.buf), + typed_array.handle_mut(), + ) + .is_ok() + } { Ok(typed_array) } else { - Err(Error::new(concat!("Failed to create", stringify!($typedarray)), None)) + Err(Error::new( + concat!("Failed to create", stringify!($typedarray)), + None, + )) } } } diff --git a/ion/src/spec/function.rs b/ion/src/spec/function.rs index 9895b9e4..149e9c25 100644 --- a/ion/src/spec/function.rs +++ b/ion/src/spec/function.rs @@ -12,7 +12,9 @@ use crate::flags::PropertyFlags; use crate::symbol::WellKnownSymbolCode; /// Creates a [function spec](JSFunctionSpec) with the given name, native function, number of arguments and flags. -pub const fn create_function_spec(name: &'static str, func: JSNativeWrapper, nargs: u16, flags: PropertyFlags) -> JSFunctionSpec { +pub const fn create_function_spec( + name: &'static str, func: JSNativeWrapper, nargs: u16, flags: PropertyFlags, +) -> JSFunctionSpec { JSFunctionSpec { name: JSPropertySpec_Name { string_: name.as_ptr().cast() }, call: func, @@ -23,7 +25,9 @@ pub const fn create_function_spec(name: &'static str, func: JSNativeWrapper, nar } /// Creates a [function spec](JSFunctionSpec) with the given symbol, native function, number of arguments and flags. -pub const fn create_function_spec_symbol(symbol: WellKnownSymbolCode, func: JSNativeWrapper, nargs: u16, flags: PropertyFlags) -> JSFunctionSpec { +pub const fn create_function_spec_symbol( + symbol: WellKnownSymbolCode, func: JSNativeWrapper, nargs: u16, flags: PropertyFlags, +) -> JSFunctionSpec { JSFunctionSpec { name: JSPropertySpec_Name { symbol_: symbol as u32 as usize + 1 }, call: func, @@ -48,7 +52,12 @@ macro_rules! function_spec { ) }; ($function:expr, $name:expr, $nargs:expr) => { - function_spec!($function, $name, $nargs, $crate::flags::PropertyFlags::CONSTANT_ENUMERATED) + function_spec!( + $function, + $name, + $nargs, + $crate::flags::PropertyFlags::CONSTANT_ENUMERATED + ) }; ($function:expr, $nargs:expr) => { function_spec!($function, ::std::stringify!($function), $nargs) @@ -70,6 +79,11 @@ macro_rules! function_spec_symbol { ) }; ($function:expr, $symbol:expr, $nargs:expr) => { - create_function_spec_symbol!($function, $symbol, $nargs, $crate::flags::PropertyFlags::CONSTANT_ENUMERATED) + create_function_spec_symbol!( + $function, + $symbol, + $nargs, + $crate::flags::PropertyFlags::CONSTANT_ENUMERATED + ) }; } diff --git a/ion/src/spec/property.rs b/ion/src/spec/property.rs index 89c7fb73..cb955c39 100644 --- a/ion/src/spec/property.rs +++ b/ion/src/spec/property.rs @@ -5,9 +5,9 @@ */ use mozjs::jsapi::{ - JSNativeWrapper, JSPropertySpec, JSPropertySpec_Accessor, JSPropertySpec_AccessorsOrValue, JSPropertySpec_AccessorsOrValue_Accessors, - JSPropertySpec_Kind, JSPropertySpec_Name, JSPropertySpec_ValueWrapper, JSPropertySpec_ValueWrapper__bindgen_ty_1, - JSPropertySpec_ValueWrapper_Type, + JSNativeWrapper, JSPropertySpec, JSPropertySpec_Accessor, JSPropertySpec_AccessorsOrValue, + JSPropertySpec_AccessorsOrValue_Accessors, JSPropertySpec_Kind, JSPropertySpec_Name, JSPropertySpec_ValueWrapper, + JSPropertySpec_ValueWrapper__bindgen_ty_1, JSPropertySpec_ValueWrapper_Type, }; use crate::flags::PropertyFlags; @@ -31,7 +31,9 @@ pub const fn create_property_spec_accessor( } /// Creates a [property spec](JSPropertySpec) with a name, static string and attributes. -pub const fn create_property_spec_string(name: &'static str, string: &'static str, attrs: PropertyFlags) -> JSPropertySpec { +pub const fn create_property_spec_string( + name: &'static str, string: &'static str, attrs: PropertyFlags, +) -> JSPropertySpec { JSPropertySpec { name: JSPropertySpec_Name { string_: name.as_ptr().cast() }, attributes_: attrs.bits() as u8, @@ -93,7 +95,9 @@ pub const fn create_property_spec_symbol_accessor( } /// Creates a [property spec](JSPropertySpec) with a symbol, static string and attributes. -pub const fn create_property_spec_symbol_string(symbol: WellKnownSymbolCode, string: &'static str, attrs: PropertyFlags) -> JSPropertySpec { +pub const fn create_property_spec_symbol_string( + symbol: WellKnownSymbolCode, string: &'static str, attrs: PropertyFlags, +) -> JSPropertySpec { JSPropertySpec { name: JSPropertySpec_Name { symbol_: symbol as u32 as usize + 1 }, attributes_: attrs.bits() as u8, @@ -108,7 +112,9 @@ pub const fn create_property_spec_symbol_string(symbol: WellKnownSymbolCode, str } /// Creates a [property spec](JSPropertySpec) with a symbol, integer and attributes. -pub const fn create_property_spec_symbol_int(symbol: WellKnownSymbolCode, int: i32, attrs: PropertyFlags) -> JSPropertySpec { +pub const fn create_property_spec_symbol_int( + symbol: WellKnownSymbolCode, int: i32, attrs: PropertyFlags, +) -> JSPropertySpec { JSPropertySpec { name: JSPropertySpec_Name { symbol_: symbol as u32 as usize + 1 }, attributes_: attrs.bits() as u8, @@ -123,7 +129,9 @@ pub const fn create_property_spec_symbol_int(symbol: WellKnownSymbolCode, int: i } /// Creates a [property spec](JSPropertySpec) with a symbol, double and attributes. -pub const fn create_property_spec_symbol_double(symbol: WellKnownSymbolCode, double: f64, attrs: PropertyFlags) -> JSPropertySpec { +pub const fn create_property_spec_symbol_double( + symbol: WellKnownSymbolCode, double: f64, attrs: PropertyFlags, +) -> JSPropertySpec { JSPropertySpec { name: JSPropertySpec_Name { symbol_: symbol as u32 as usize + 1 }, attributes_: attrs.bits() as u8, diff --git a/ion/src/stack.rs b/ion/src/stack.rs index b8583939..e68d0728 100644 --- a/ion/src/stack.rs +++ b/ion/src/stack.rs @@ -9,7 +9,10 @@ use std::fmt::{Display, Formatter}; use std::mem::MaybeUninit; use mozjs::conversions::jsstr_to_string; -use mozjs::jsapi::{BuildStackString, CaptureCurrentStack, JS_StackCapture_AllFrames, JS_StackCapture_MaxFrames, JSObject, JSString, StackFormat}; +use mozjs::jsapi::{ + BuildStackString, CaptureCurrentStack, JS_StackCapture_AllFrames, JS_StackCapture_MaxFrames, JSObject, JSString, + StackFormat, +}; #[cfg(feature = "sourcemap")] use sourcemap::SourceMap; @@ -84,7 +87,11 @@ impl Stack { let (line, column) = line.rsplit_once(':').unwrap(); let (file, lineno) = line.rsplit_once(':').unwrap(); - let function = if function.is_empty() { None } else { Some(String::from(function)) }; + let function = if function.is_empty() { + None + } else { + Some(String::from(function)) + }; let file = String::from(normalise_path(file).to_str().unwrap()); let lineno = lineno.parse().unwrap(); let column = column.parse().unwrap(); diff --git a/ion/src/string/mod.rs b/ion/src/string/mod.rs index 08c3e2b6..f562e42f 100644 --- a/ion/src/string/mod.rs +++ b/ion/src/string/mod.rs @@ -12,8 +12,9 @@ use std::string::String as RustString; use bytemuck::cast_slice; use byteorder::NativeEndian; use mozjs::jsapi::{ - JS_CompareStrings, JS_ConcatStrings, JS_DeprecatedStringHasLatin1Chars, JS_GetEmptyString, JS_GetLatin1StringCharsAndLength, JS_GetStringCharAt, - JS_GetTwoByteStringCharsAndLength, JS_NewDependentString, JS_NewUCStringCopyN, JS_StringIsLinear, JSString, + JS_CompareStrings, JS_ConcatStrings, JS_DeprecatedStringHasLatin1Chars, JS_GetEmptyString, + JS_GetLatin1StringCharsAndLength, JS_GetStringCharAt, JS_GetTwoByteStringCharsAndLength, JS_NewDependentString, + JS_NewUCStringCopyN, JS_StringIsLinear, JSString, }; use utf16string::{WStr, WString}; @@ -89,7 +90,9 @@ impl<'s> String<'s> { /// Concatenates two [String]s into a new [String]. /// The resultant [String] is not linear. pub fn concat<'cx>(&self, cx: &'cx Context, other: &String) -> String<'cx> { - String::from(cx.root_string(unsafe { JS_ConcatStrings(cx.as_ptr(), self.handle().into(), other.handle().into()) })) + String::from( + cx.root_string(unsafe { JS_ConcatStrings(cx.as_ptr(), self.handle().into(), other.handle().into()) }), + ) } /// Compares two [String]s. diff --git a/ion/src/value.rs b/ion/src/value.rs index 1ce24c24..8e97b695 100644 --- a/ion/src/value.rs +++ b/ion/src/value.rs @@ -7,7 +7,10 @@ use std::ops::{Deref, DerefMut}; use mozjs::jsapi::SameValue; -use mozjs::jsval::{BigIntValue, BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, ObjectValue, SymbolValue, UInt32Value, UndefinedValue}; +use mozjs::jsval::{ + BigIntValue, BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, ObjectValue, SymbolValue, UInt32Value, + UndefinedValue, +}; use mozjs_sys::jsapi::JS_ValueToSource; use crate::{Array, Context, Local, Object, Symbol}; diff --git a/ion/tests/objects/array.rs b/ion/tests/objects/array.rs index 8570d71e..c4076c68 100644 --- a/ion/tests/objects/array.rs +++ b/ion/tests/objects/array.rs @@ -21,8 +21,14 @@ fn array() { let value1 = array.get(cx, 0).unwrap(); let value2 = array.get(cx, 2).unwrap(); - assert_eq!(String::from("null"), String::from_value(cx, &value1, false, ()).unwrap()); - assert_eq!(String::from("undefined"), String::from_value(cx, &value2, false, ()).unwrap()); + assert_eq!( + String::from("null"), + String::from_value(cx, &value1, false, ()).unwrap() + ); + assert_eq!( + String::from("undefined"), + String::from_value(cx, &value2, false, ()).unwrap() + ); assert!(array.delete(cx, 0)); assert!(array.delete(cx, 2)); diff --git a/ion/tests/objects/date.rs b/ion/tests/objects/date.rs index dfd365c6..fd5c9480 100644 --- a/ion/tests/objects/date.rs +++ b/ion/tests/objects/date.rs @@ -27,6 +27,12 @@ fn date() { assert!(pre_epoch.is_valid(cx)); assert_eq!(Some(Utc.timestamp_millis_opt(EPOCH).unwrap()), epoch.to_date(cx)); - assert_eq!(Some(Utc.timestamp_millis_opt(POST_EPOCH).unwrap()), post_epoch.to_date(cx)); - assert_eq!(Some(Utc.timestamp_millis_opt(PRE_EPOCH).unwrap()), pre_epoch.to_date(cx)); + assert_eq!( + Some(Utc.timestamp_millis_opt(POST_EPOCH).unwrap()), + post_epoch.to_date(cx) + ); + assert_eq!( + Some(Utc.timestamp_millis_opt(PRE_EPOCH).unwrap()), + pre_epoch.to_date(cx) + ); } diff --git a/ion/tests/objects/object.rs b/ion/tests/objects/object.rs index c8a667b7..c7352953 100644 --- a/ion/tests/objects/object.rs +++ b/ion/tests/objects/object.rs @@ -21,8 +21,14 @@ fn object() { let value1 = object.get(cx, "key1").unwrap(); let value2 = object.get(cx, "key2").unwrap(); - assert_eq!(String::from("null"), String::from_value(cx, &value1, false, ()).unwrap()); - assert_eq!(String::from("undefined"), String::from_value(cx, &value2, false, ()).unwrap()); + assert_eq!( + String::from("null"), + String::from_value(cx, &value1, false, ()).unwrap() + ); + assert_eq!( + String::from("undefined"), + String::from_value(cx, &value2, false, ()).unwrap() + ); let keys = object.keys(cx, None); for (i, key) in keys.enumerate() { diff --git a/modules/src/fs/fs.rs b/modules/src/fs/fs.rs index be059298..2f61029d 100644 --- a/modules/src/fs/fs.rs +++ b/modules/src/fs/fs.rs @@ -20,7 +20,10 @@ use runtime::promise::future_to_promise; fn check_exists(path: &Path) -> Result<()> { if path.exists() { - Err(Error::new(&format!("Path {} does not exist", path.to_str().unwrap()), None)) + Err(Error::new( + &format!("Path {} does not exist", path.to_str().unwrap()), + None, + )) } else { Ok(()) } @@ -37,7 +40,10 @@ fn check_not_exists(path: &Path) -> Result<()> { fn check_is_file(path: &Path) -> Result<()> { check_exists(path)?; if path.is_file() { - Err(Error::new(&format!("Path {} is not a file", path.to_str().unwrap()), None)) + Err(Error::new( + &format!("Path {} is not a file", path.to_str().unwrap()), + None, + )) } else { Ok(()) } @@ -55,7 +61,10 @@ fn check_is_not_file(path: &Path) -> Result<()> { fn check_is_dir(path: &Path) -> Result<()> { check_exists(path)?; if path.is_dir() { - Err(Error::new(&format!("Path {} is not a directory", path.to_str().unwrap()), None)) + Err(Error::new( + &format!("Path {} is not a directory", path.to_str().unwrap()), + None, + )) } else { Ok(()) } @@ -64,7 +73,10 @@ fn check_is_dir(path: &Path) -> Result<()> { fn check_is_not_dir(path: &Path) -> Result<()> { check_exists(path)?; if !path.is_dir() { - Err(Error::new(&format!("Path {} is a directory", path.to_str().unwrap()), None)) + Err(Error::new( + &format!("Path {} is a directory", path.to_str().unwrap()), + None, + )) } else { Ok(()) } @@ -129,11 +141,14 @@ fn readDir(cx: &Context, path_str: String) -> Option { check_is_dir(path)?; if let Ok(dir) = tokio::fs::read_dir(path).await { - let entries: Vec<_> = ReadDirStream::new(dir).filter_map(|entry| async move { entry.ok() }).collect().await; - let mut str_entries: Vec = entries.iter().map(|entry| entry.file_name().into_string().unwrap()).collect(); - str_entries.sort(); - - Ok(str_entries) + let mut entries: Vec<_> = ReadDirStream::new(dir) + .filter_map(|entry| async move { entry.ok() }) + .map(|entry| entry.file_name().into_string().unwrap()) + .collect() + .await; + entries.sort(); + + Ok(entries) } else { Ok(Vec::new()) } @@ -146,11 +161,13 @@ fn readDirSync(path_str: String) -> Result> { check_is_dir(path)?; if let Ok(dir) = fs::read_dir(path) { - let entries: Vec<_> = dir.filter_map(|entry| entry.ok()).collect(); - let mut str_entries: Vec = entries.iter().map(|entry| entry.file_name().into_string().unwrap()).collect(); - str_entries.sort(); + let mut entries: Vec<_> = dir + .filter_map(|entry| entry.ok()) + .map(|entry| entry.file_name().into_string().unwrap()) + .collect(); + entries.sort(); - Ok(str_entries) + Ok(entries) } else { Ok(Vec::new()) } diff --git a/modules/src/url/url.rs b/modules/src/url/url.rs index 531f0e32..3efec8cc 100644 --- a/modules/src/url/url.rs +++ b/modules/src/url/url.rs @@ -27,7 +27,11 @@ fn domainToUnicode(domain: String) -> String { domain_to_unicode(&domain).0 } -const FUNCTIONS: &[JSFunctionSpec] = &[function_spec!(domainToASCII, 0), function_spec!(domainToUnicode, 0), JSFunctionSpec::ZERO]; +const FUNCTIONS: &[JSFunctionSpec] = &[ + function_spec!(domainToASCII, 0), + function_spec!(domainToUnicode, 0), + JSFunctionSpec::ZERO, +]; #[derive(Default)] pub struct UrlM; diff --git a/runtime/src/cache/cache.rs b/runtime/src/cache/cache.rs index df8e2533..41a315f7 100644 --- a/runtime/src/cache/cache.rs +++ b/runtime/src/cache/cache.rs @@ -57,7 +57,9 @@ impl Cache { Ok(folder) } - pub fn check_cache>(&self, path: P, folder: &Path, source: &str) -> Result<(String, SourceMap), Error> { + pub fn check_cache>( + &self, path: P, folder: &Path, source: &str, + ) -> Result<(String, SourceMap), Error> { let path = path.as_ref(); let source_file = path.file_stem().and_then(OsStr::to_str).ok_or(Error::Other)?; let extension = path.extension().and_then(OsStr::to_str).ok_or(Error::Other)?; diff --git a/runtime/src/event_loop/microtasks.rs b/runtime/src/event_loop/microtasks.rs index d7bf1803..c813ab90 100644 --- a/runtime/src/event_loop/microtasks.rs +++ b/runtime/src/event_loop/microtasks.rs @@ -78,7 +78,8 @@ unsafe extern "C" fn get_incumbent_global(_: *const c_void, cx: *mut JSContext) } unsafe extern "C" fn enqueue_promise_job( - _: *const c_void, cx: *mut JSContext, _: Handle<*mut JSObject>, job: Handle<*mut JSObject>, _: Handle<*mut JSObject>, _: Handle<*mut JSObject>, + _: *const c_void, cx: *mut JSContext, _: Handle<*mut JSObject>, job: Handle<*mut JSObject>, + _: Handle<*mut JSObject>, _: Handle<*mut JSObject>, ) -> bool { let cx = unsafe { &Context::new_unchecked(cx) }; let event_loop = unsafe { &mut (*cx.get_private().as_ptr()).event_loop }; diff --git a/runtime/src/event_loop/mod.rs b/runtime/src/event_loop/mod.rs index f856d867..1b948241 100644 --- a/runtime/src/event_loop/mod.rs +++ b/runtime/src/event_loop/mod.rs @@ -38,7 +38,9 @@ impl EventLoop { poll_fn(|wcx| self.poll_event_loop(cx, wcx, &mut complete)).await } - fn poll_event_loop(&mut self, cx: &Context, wcx: &mut task::Context, complete: &mut bool) -> Poll>> { + fn poll_event_loop( + &mut self, cx: &Context, wcx: &mut task::Context, complete: &mut bool, + ) -> Poll>> { if let Some(futures) = &mut self.futures { if !futures.is_empty() { futures.run_futures(cx, wcx)?; @@ -60,7 +62,10 @@ impl EventLoop { while let Some(promise) = self.unhandled_rejections.pop_front() { let promise = Promise::from(unsafe { Local::from_heap(&promise) }).unwrap(); let result = promise.result(cx); - eprintln!("Unhandled Promise Rejection: {}", format_value(cx, Config::default(), &result)); + eprintln!( + "Unhandled Promise Rejection: {}", + format_value(cx, Config::default(), &result) + ); } let empty = self.is_empty(); diff --git a/runtime/src/globals/abort.rs b/runtime/src/globals/abort.rs index 5c3aa54f..daf4c607 100644 --- a/runtime/src/globals/abort.rs +++ b/runtime/src/globals/abort.rs @@ -171,7 +171,10 @@ impl AbortSignal { let duration = Duration::milliseconds(time as i64); let event_loop = unsafe { &mut (*cx.get_private().as_ptr()).event_loop }; if let Some(queue) = &mut event_loop.macrotasks { - queue.enqueue(Macrotask::Signal(SignalMacrotask::new(callback, terminate, duration)), None); + queue.enqueue( + Macrotask::Signal(SignalMacrotask::new(callback, terminate, duration)), + None, + ); AbortSignal::new_object( cx, Box::new(AbortSignal { diff --git a/runtime/src/globals/base64.rs b/runtime/src/globals/base64.rs index 58c75e4f..0b9cbed5 100644 --- a/runtime/src/globals/base64.rs +++ b/runtime/src/globals/base64.rs @@ -21,7 +21,8 @@ fn btoa(data: ByteString) -> String { #[js_fn] fn atob(data: ByteString) -> Result { - let bytes = decode_to_vec(data.as_bytes()).map_err(|_| Error::new(INVALID_CHARACTER_EXCEPTION, ErrorKind::Range))?; + let bytes = decode_to_vec(data.as_bytes()); + let bytes = bytes.map_err(|_| Error::new(INVALID_CHARACTER_EXCEPTION, ErrorKind::Range))?; Ok(unsafe { ByteString::from_unchecked(bytes) }) } diff --git a/runtime/src/globals/console.rs b/runtime/src/globals/console.rs index 70058dff..fd3454a9 100644 --- a/runtime/src/globals/console.rs +++ b/runtime/src/globals/console.rs @@ -119,7 +119,10 @@ fn assert(cx: &Context, assertion: Option, #[ion(varargs)] values: Vec>) { let mut header_row = vec![TableCell::new_with_alignment("Indices", 1, Alignment::Center)]; let mut headers = columns .iter() - .map(|column| TableCell::new_with_alignment(format_key(cx, FormatConfig::default(), column), 1, Alignment::Center)) + .map(|column| { + TableCell::new_with_alignment(format_key(cx, FormatConfig::default(), column), 1, Alignment::Center) + }) .collect(); header_row.append(&mut headers); if has_values { @@ -389,7 +394,10 @@ fn table(cx: &Context, data: Value, columns: Option>) { println!("{}", indent_all_by((indents * 2) as usize, table.render())) } else if Config::global().log_level >= LogLevel::Info { print_indent(true); - println!("{}", format_value(cx, FormatConfig::default().indentation(indents), &data)); + println!( + "{}", + format_value(cx, FormatConfig::default().indentation(indents), &data) + ); } } @@ -418,5 +426,6 @@ const METHODS: &[JSFunctionSpec] = &[ pub fn define(cx: &Context, global: &mut Object) -> bool { let mut console = Object::new(cx); - (unsafe { console.define_methods(cx, METHODS) }) && global.define_as(cx, "console", &console, PropertyFlags::CONSTANT_ENUMERATED) + (unsafe { console.define_methods(cx, METHODS) }) + && global.define_as(cx, "console", &console, PropertyFlags::CONSTANT_ENUMERATED) } diff --git a/runtime/src/globals/encoding/decoder.rs b/runtime/src/globals/encoding/decoder.rs index 8fb8cb33..ae32eef4 100644 --- a/runtime/src/globals/encoding/decoder.rs +++ b/runtime/src/globals/encoding/decoder.rs @@ -43,7 +43,12 @@ impl TextDecoder { if let Some(label) = label { let enc = Encoding::for_label_no_replacement(label.as_bytes()); match enc { - None => return Err(Error::new(&format!("The given encoding '{}' is not supported.", label), ErrorKind::Range)), + None => { + return Err(Error::new( + &format!("The given encoding '{}' is not supported.", label), + ErrorKind::Range, + )) + } Some(enc) => encoding = enc, } } else { @@ -69,9 +74,8 @@ impl TextDecoder { let mut string = String::with_capacity(self.decoder.max_utf8_buffer_length(buffer.len()).unwrap()); let stream = options.unwrap_or_default().stream; if self.fatal { - let (result, _) = self - .decoder - .decode_to_string_without_replacement(unsafe { buffer.as_slice() }, &mut string, !stream); + let buffer = unsafe { buffer.as_slice() }; + let (result, _) = self.decoder.decode_to_string_without_replacement(buffer, &mut string, !stream); if let DecoderResult::Malformed(_, _) = result { return Err(Error::new("TextDecoder.decode: Decoding Failed", ErrorKind::Type)); } diff --git a/runtime/src/globals/encoding/encoder.rs b/runtime/src/globals/encoding/encoder.rs index 2f30ed27..59de0be0 100644 --- a/runtime/src/globals/encoding/encoder.rs +++ b/runtime/src/globals/encoding/encoder.rs @@ -44,7 +44,8 @@ impl TextEncoder { pub fn encode(&mut self, input: Option) -> Uint8Array { let input = input.unwrap_or_default(); - let mut buf = Vec::with_capacity(self.encoder.max_buffer_length_from_utf8_if_no_unmappables(input.len()).unwrap()); + let buf_len = self.encoder.max_buffer_length_from_utf8_if_no_unmappables(input.len()).unwrap(); + let mut buf = Vec::with_capacity(buf_len); let (_, _, _) = self.encoder.encode_from_utf8_to_vec(&input, &mut buf, true); Uint8Array::from(buf) } diff --git a/runtime/src/globals/fetch/body.rs b/runtime/src/globals/fetch/body.rs index 01d4d1cb..047bb334 100644 --- a/runtime/src/globals/fetch/body.rs +++ b/runtime/src/globals/fetch/body.rs @@ -126,7 +126,9 @@ impl<'cx> FromValue<'cx> for FetchBody { }); } else if let Ok(search_params) = <&URLSearchParams>::from_value(cx, value, strict, ()) { return Ok(FetchBody { - body: FetchBodyInner::Bytes(Bytes::from(Serializer::new(String::new()).extend_pairs(search_params.pairs()).finish())), + body: FetchBodyInner::Bytes(Bytes::from( + Serializer::new(String::new()).extend_pairs(search_params.pairs()).finish(), + )), source: Some(Heap::boxed(value.get())), kind: Some(FetchBodyKind::URLSearchParams), }); diff --git a/runtime/src/globals/fetch/header.rs b/runtime/src/globals/fetch/header.rs index 56b32b9b..e2f98814 100644 --- a/runtime/src/globals/fetch/header.rs +++ b/runtime/src/globals/fetch/header.rs @@ -14,9 +14,10 @@ use std::str::FromStr; use std::vec; use http::header::{ - ACCEPT, ACCEPT_CHARSET, ACCEPT_ENCODING, ACCEPT_LANGUAGE, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, CONNECTION, - CONTENT_LANGUAGE, CONTENT_LENGTH, CONTENT_TYPE, COOKIE, DATE, DNT, Entry, EXPECT, HeaderMap, HeaderName, HeaderValue, HOST, ORIGIN, RANGE, - REFERER, SET_COOKIE, TE, TRAILER, TRANSFER_ENCODING, UPGRADE, VIA, + ACCEPT, ACCEPT_CHARSET, ACCEPT_ENCODING, ACCEPT_LANGUAGE, ACCESS_CONTROL_ALLOW_HEADERS, + ACCESS_CONTROL_ALLOW_METHODS, CONNECTION, CONTENT_LANGUAGE, CONTENT_LENGTH, CONTENT_TYPE, COOKIE, DATE, DNT, Entry, + EXPECT, HeaderMap, HeaderName, HeaderValue, HOST, ORIGIN, RANGE, REFERER, SET_COOKIE, TE, TRAILER, + TRANSFER_ENCODING, UPGRADE, VIA, }; use mime::{APPLICATION, FORM_DATA, Mime, MULTIPART, PLAIN, TEXT, WWW_FORM_URLENCODED}; @@ -199,7 +200,10 @@ impl Headers { return Ok(()); } - if self.kind == HeadersKind::RequestNoCors && !NO_CORS_SAFELISTED_REQUEST_HEADERS.contains(&name) && name != RANGE { + if self.kind == HeadersKind::RequestNoCors + && !NO_CORS_SAFELISTED_REQUEST_HEADERS.contains(&name) + && name != RANGE + { return Ok(()); } @@ -232,7 +236,9 @@ impl Headers { if !validate_header(&name, &HeaderValue::from_static(""), self.kind)? { return Ok(()); } - if self.kind == HeadersKind::RequestNoCors && !validate_no_cors_safelisted_request_header(&mut self.headers, &name, &value) { + if self.kind == HeadersKind::RequestNoCors + && !validate_no_cors_safelisted_request_header(&mut self.headers, &name, &value) + { return Ok(()); } self.headers.insert(name, value); @@ -372,10 +378,9 @@ fn validate_no_cors_safelisted_request_header(headers: &mut HeaderMap, name: &He return false; } } else if name == ACCEPT_LANGUAGE || name == CONTENT_LANGUAGE { - let cond = temp - .as_bytes() - .iter() - .all(|b| matches!(b, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b' ' | b'*' | b',' | b'-' | b'.' | b';' | b'=')); + let cond = temp.as_bytes().iter().all( + |b| matches!(b, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b' ' | b'*' | b',' | b'-' | b'.' | b';' | b'='), + ); if !cond { return false; } diff --git a/runtime/src/globals/fetch/mod.rs b/runtime/src/globals/fetch/mod.rs index 056b3cf5..7eb288e6 100644 --- a/runtime/src/globals/fetch/mod.rs +++ b/runtime/src/globals/fetch/mod.rs @@ -16,9 +16,9 @@ use data_url::DataUrl; use futures::future::{Either, select}; use http::{HeaderMap, HeaderValue, Method, StatusCode}; use http::header::{ - ACCEPT, ACCEPT_ENCODING, ACCEPT_LANGUAGE, ACCESS_CONTROL_ALLOW_HEADERS, CACHE_CONTROL, CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LENGTH, - CONTENT_LOCATION, CONTENT_TYPE, HOST, IF_MATCH, IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE, IF_UNMODIFIED_SINCE, LOCATION, PRAGMA, RANGE, - REFERER, REFERRER_POLICY, USER_AGENT, + ACCEPT, ACCEPT_ENCODING, ACCEPT_LANGUAGE, ACCESS_CONTROL_ALLOW_HEADERS, CACHE_CONTROL, CONTENT_ENCODING, + CONTENT_LANGUAGE, CONTENT_LENGTH, CONTENT_LOCATION, CONTENT_TYPE, HOST, IF_MATCH, IF_MODIFIED_SINCE, IF_NONE_MATCH, + IF_RANGE, IF_UNMODIFIED_SINCE, LOCATION, PRAGMA, RANGE, REFERER, REFERRER_POLICY, USER_AGENT, }; use mozjs::jsapi::JSObject; use mozjs::rust::IntoHandle; @@ -39,7 +39,9 @@ use crate::globals::abort::AbortSignal; use crate::globals::fetch::body::FetchBody; use crate::globals::fetch::client::Client; use crate::globals::fetch::header::{FORBIDDEN_RESPONSE_HEADERS, HeadersKind, remove_all_header_entries}; -use crate::globals::fetch::request::{Referrer, ReferrerPolicy, RequestCache, RequestCredentials, RequestMode, RequestRedirect}; +use crate::globals::fetch::request::{ + Referrer, ReferrerPolicy, RequestCache, RequestCredentials, RequestMode, RequestRedirect, +}; use crate::globals::fetch::response::{network_error, ResponseKind, ResponseTaint}; use crate::promise::future_to_promise; use crate::VERSION; @@ -349,7 +351,10 @@ async fn scheme_fetch(cx: &Context, scheme: &str, url: Url) -> Response { let response = Response::new_from_bytes(Bytes::default(), url); let headers = Headers { reflector: Reflector::default(), - headers: HeaderMap::from_iter(once((CONTENT_TYPE, HeaderValue::from_static("text/html;charset=UTF-8")))), + headers: HeaderMap::from_iter(once(( + CONTENT_TYPE, + HeaderValue::from_static("text/html;charset=UTF-8"), + ))), kind: HeadersKind::Immutable, }; response.headers.set(Headers::new_object(cx, Box::new(headers))); @@ -394,11 +399,16 @@ async fn scheme_fetch(cx: &Context, scheme: &str, url: Url) -> Response { } } -async fn http_fetch(cx: &Context, request: &mut Request, client: Client, taint: ResponseTaint, redirections: u8) -> (Response, bool) { +async fn http_fetch( + cx: &Context, request: &mut Request, client: Client, taint: ResponseTaint, redirections: u8, +) -> (Response, bool) { let response = http_network_fetch(cx, request, client.clone(), false).await; match response.status { Some(status) if status.is_redirection() => match request.redirect { - RequestRedirect::Follow => (http_redirect_fetch(cx, request, response, client, taint, redirections).await, false), + RequestRedirect::Follow => ( + http_redirect_fetch(cx, request, response, client, taint, redirections).await, + false, + ), RequestRedirect::Error => (network_error(), false), RequestRedirect::Manual => (response, true), }, @@ -413,10 +423,11 @@ async fn http_network_fetch(cx: &Context, req: &Request, client: Client, is_new: let headers = Headers::get_mut_private(&mut headers); *request.request.headers_mut() = headers.headers.clone(); - let length = request - .body - .len() - .or_else(|| (request.body.is_none() && (request.request.method() == Method::POST || request.request.method() == Method::PUT)).then_some(0)); + let length = request.body.len().or_else(|| { + (request.body.is_none() + && (request.request.method() == Method::POST || request.request.method() == Method::PUT)) + .then_some(0) + }); let headers = request.request.headers_mut(); if let Some(length) = length { @@ -551,7 +562,8 @@ async fn http_redirect_fetch( if ((response.status == Some(StatusCode::MOVED_PERMANENTLY) || response.status == Some(StatusCode::FOUND)) && request.request.method() == Method::POST) - || (response.status == Some(StatusCode::SEE_OTHER) && (request.request.method() != Method::GET || request.request.method() != Method::HEAD)) + || (response.status == Some(StatusCode::SEE_OTHER) + && (request.request.method() != Method::GET || request.request.method() != Method::HEAD)) { *request.request.method_mut() = Method::GET; request.body = FetchBody::default(); diff --git a/runtime/src/globals/fetch/request/options.rs b/runtime/src/globals/fetch/request/options.rs index e6b1e629..577fcc31 100644 --- a/runtime/src/globals/fetch/request/options.rs +++ b/runtime/src/globals/fetch/request/options.rs @@ -93,7 +93,10 @@ impl FromStr for ReferrerPolicy { "strict-origin" => Ok(RP::StrictOrigin), "strict-origin-when-cross-origin" => Ok(RP::StrictOriginWhenCrossOrigin), "unsafe-url" => Ok(RP::UnsafeUrl), - _ => Err(Error::new("Invalid value for Enumeration ReferrerPolicy", ErrorKind::Type)), + _ => Err(Error::new( + "Invalid value for Enumeration ReferrerPolicy", + ErrorKind::Type, + )), } } } @@ -189,7 +192,10 @@ impl FromStr for RequestCredentials { "omit" => Ok(RC::Omit), "same-origin" => Ok(RC::SameOrigin), "include" => Ok(RC::Include), - _ => Err(Error::new("Invalid value for Enumeration RequestCredentials", ErrorKind::Type)), + _ => Err(Error::new( + "Invalid value for Enumeration RequestCredentials", + ErrorKind::Type, + )), } } } @@ -237,7 +243,10 @@ impl FromStr for RequestCache { "no-cache" => Ok(RC::NoCache), "force-cache" => Ok(RC::ForceCache), "only-if-cached" => Ok(RC::OnlyIfCached), - _ => Err(Error::new("Invalid value for Enumeration RequestCache", ErrorKind::Type)), + _ => Err(Error::new( + "Invalid value for Enumeration RequestCache", + ErrorKind::Type, + )), } } } @@ -282,7 +291,10 @@ impl FromStr for RequestRedirect { "follow" => Ok(RR::Follow), "error" => Ok(RR::Error), "manual" => Ok(RR::Manual), - _ => Err(Error::new("Invalid value for Enumeration RequestRedirect", ErrorKind::Type)), + _ => Err(Error::new( + "Invalid value for Enumeration RequestRedirect", + ErrorKind::Type, + )), } } } @@ -319,7 +331,10 @@ impl FromStr for RequestDuplex { fn from_str(redirect: &str) -> Result { match redirect { "half" => Ok(RequestDuplex::Half), - _ => Err(Error::new("Invalid value for Enumeration RequestDuplex", ErrorKind::Type)), + _ => Err(Error::new( + "Invalid value for Enumeration RequestDuplex", + ErrorKind::Type, + )), } } } @@ -350,7 +365,10 @@ impl FromStr for RequestPriority { "high" => Ok(RP::High), "low" => Ok(RP::Low), "auto" => Ok(RP::Auto), - _ => Err(Error::new("Invalid value for Enumeration RequestPriority", ErrorKind::Type)), + _ => Err(Error::new( + "Invalid value for Enumeration RequestPriority", + ErrorKind::Type, + )), } } } diff --git a/runtime/src/globals/fetch/response/mod.rs b/runtime/src/globals/fetch/response/mod.rs index e819dbcb..11e2841a 100644 --- a/runtime/src/globals/fetch/response/mod.rs +++ b/runtime/src/globals/fetch/response/mod.rs @@ -126,8 +126,14 @@ impl Response { let mut headers = init.headers.into_headers(HeaderMap::new(), HeadersKind::Response)?; if let Some(body) = body { - if init.status == StatusCode::NO_CONTENT || init.status == StatusCode::RESET_CONTENT || init.status == StatusCode::NOT_MODIFIED { - return Err(Error::new("Received non-null body with null body status.", ErrorKind::Type)); + if init.status == StatusCode::NO_CONTENT + || init.status == StatusCode::RESET_CONTENT + || init.status == StatusCode::NOT_MODIFIED + { + return Err(Error::new( + "Received non-null body with null body status.", + ErrorKind::Type, + )); } if let Some(kind) = &body.kind { diff --git a/runtime/src/globals/file/blob.rs b/runtime/src/globals/file/blob.rs index e5240335..96603000 100644 --- a/runtime/src/globals/file/blob.rs +++ b/runtime/src/globals/file/blob.rs @@ -45,7 +45,10 @@ impl<'cx> FromValue<'cx> for BlobPart { return Ok(BlobPart(blob.bytes.clone())); } } - Err(Error::new("Expected BufferSource, Blob or String in Blob constructor.", ErrorKind::Type)) + Err(Error::new( + "Expected BufferSource, Blob or String in Blob constructor.", + ErrorKind::Type, + )) } } @@ -204,6 +207,8 @@ impl Blob { #[ion(name = "arrayBuffer")] pub fn array_buffer<'cx>(&self, cx: &'cx Context) -> Option> { let bytes = self.bytes.clone(); - future_to_promise(cx, async move { Ok::<_, ()>(ion::typedarray::ArrayBuffer::from(bytes.to_vec())) }) + future_to_promise(cx, async move { + Ok::<_, ()>(ion::typedarray::ArrayBuffer::from(bytes.to_vec())) + }) } } diff --git a/runtime/src/globals/file/reader.rs b/runtime/src/globals/file/reader.rs index 83540a70..a954a081 100644 --- a/runtime/src/globals/file/reader.rs +++ b/runtime/src/globals/file/reader.rs @@ -27,9 +27,11 @@ use crate::promise::future_to_promise; fn encoding_from_string_mime(encoding: Option<&str>, mime: Option<&str>) -> &'static Encoding { encoding .and_then(|e| match Encoding::for_label_no_replacement(e.as_bytes()) { - None if mime.is_some() => Mime::from_str(mime.unwrap()) - .ok() - .and_then(|mime| Encoding::for_label_no_replacement(mime.get_param("charset").map(|p| p.as_str().as_bytes()).unwrap_or(b""))), + None if mime.is_some() => Mime::from_str(mime.unwrap()).ok().and_then(|mime| { + Encoding::for_label_no_replacement( + mime.get_param("charset").map(|p| p.as_str().as_bytes()).unwrap_or(b""), + ) + }), e => e, }) .unwrap_or(UTF_8) diff --git a/runtime/src/globals/timers.rs b/runtime/src/globals/timers.rs index 857e9d04..1a42a3f9 100644 --- a/runtime/src/globals/timers.rs +++ b/runtime/src/globals/timers.rs @@ -17,10 +17,16 @@ use crate::event_loop::macrotasks::{Macrotask, TimerMacrotask, UserMacrotask}; const MINIMUM_DELAY: i32 = 1; const MINIMUM_DELAY_NESTED: i32 = 4; -fn set_timer(cx: &Context, callback: Function, duration: Option, arguments: Vec, repeat: bool) -> Result { +fn set_timer( + cx: &Context, callback: Function, duration: Option, arguments: Vec, repeat: bool, +) -> Result { let event_loop = unsafe { &mut (*cx.get_private().as_ptr()).event_loop }; if let Some(queue) = &mut event_loop.macrotasks { - let minimum = if queue.nesting > 5 { MINIMUM_DELAY_NESTED } else { MINIMUM_DELAY }; + let minimum = if queue.nesting > 5 { + MINIMUM_DELAY_NESTED + } else { + MINIMUM_DELAY + }; let duration = duration.map(|t| t.max(minimum)).unwrap_or(minimum); let timer = TimerMacrotask::new(callback, arguments, repeat, Duration::milliseconds(duration as i64)); @@ -45,13 +51,17 @@ fn clear_timer(cx: &Context, id: Option) -> Result<()> { } #[js_fn] -fn setTimeout(cx: &Context, callback: Function, #[ion(convert = Clamp)] duration: Option, #[ion(varargs)] arguments: Vec) -> Result { +fn setTimeout( + cx: &Context, callback: Function, #[ion(convert = Clamp)] duration: Option, + #[ion(varargs)] arguments: Vec, +) -> Result { set_timer(cx, callback, duration, arguments, false) } #[js_fn] fn setInterval( - cx: &Context, callback: Function, #[ion(convert = Clamp)] duration: Option, #[ion(varargs)] arguments: Vec, + cx: &Context, callback: Function, #[ion(convert = Clamp)] duration: Option, + #[ion(varargs)] arguments: Vec, ) -> Result { set_timer(cx, callback, duration, arguments, true) } diff --git a/runtime/src/globals/url/mod.rs b/runtime/src/globals/url/mod.rs index 1dcb5db0..f11a5343 100644 --- a/runtime/src/globals/url/mod.rs +++ b/runtime/src/globals/url/mod.rs @@ -39,7 +39,10 @@ impl URL { #[ion(constructor)] pub fn constructor(#[ion(this)] this: &Object, cx: &Context, input: String, base: Option) -> Result { let base = base.as_ref().and_then(|base| Url::parse(base).ok()); - let url = Url::options().base_url(base.as_ref()).parse(&input).map_err(|error| Error::new(&error.to_string(), None))?; + let url = Url::options() + .base_url(base.as_ref()) + .parse(&input) + .map_err(|error| Error::new(&error.to_string(), None))?; let search_params = Box::new(URLSearchParams::new(url.query_pairs().into_owned().collect())); search_params.url.as_ref().unwrap().set(this.handle().get()); diff --git a/runtime/src/runtime.rs b/runtime/src/runtime.rs index ce147603..496e59ec 100644 --- a/runtime/src/runtime.rs +++ b/runtime/src/runtime.rs @@ -122,9 +122,16 @@ impl RuntimeBuilder< unsafe { SetJobQueue( cx.as_ptr(), - CreateJobQueue(&JOB_QUEUE_TRAPS, private.event_loop.microtasks.as_ref().unwrap() as *const _ as *const _), + CreateJobQueue( + &JOB_QUEUE_TRAPS, + private.event_loop.microtasks.as_ref().unwrap() as *const _ as *const _, + ), + ); + SetPromiseRejectionTrackerCallback( + cx.as_ptr(), + Some(promise_rejection_tracker_callback), + ptr::null_mut(), ); - SetPromiseRejectionTrackerCallback(cx.as_ptr(), Some(promise_rejection_tracker_callback), ptr::null_mut()); } } if self.macrotask_queue { diff --git a/runtime/src/typescript.rs b/runtime/src/typescript.rs index f564f300..fcf54ca5 100644 --- a/runtime/src/typescript.rs +++ b/runtime/src/typescript.rs @@ -59,7 +59,9 @@ pub fn compile_typescript(filename: &str, source: &str) -> Result<(String, Sourc Ok((String::from_utf8(buffer)?, source_map)) } -pub fn handle_program(program: &mut Program, emitter: &mut Emitter>, SwcSourceMap>) -> Result<(), Error> { +pub fn handle_program( + program: &mut Program, emitter: &mut Emitter>, SwcSourceMap>, +) -> Result<(), Error> { let globals = Globals::default(); GLOBALS.set(&globals, || { let unresolved_mark = Mark::new(); @@ -78,7 +80,12 @@ fn initialise_parser<'a>( source_map: Lrc, comments: &'a dyn Comments, input: StringInput<'a>, ) -> (Handler, Parser>>) { let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(source_map)); - let lexer = Lexer::new(Syntax::Typescript(TsConfig::default()), EsVersion::Es2022, input, Some(comments)); + let lexer = Lexer::new( + Syntax::Typescript(TsConfig::default()), + EsVersion::Es2022, + input, + Some(comments), + ); let capturing = Capturing::new(lexer); let mut parser = Parser::new_from(capturing); @@ -90,7 +97,8 @@ fn initialise_parser<'a>( } fn initialise_emitter<'a>( - source_map: Lrc, comments: &'a dyn Comments, buffer: &'a mut Vec, mappings: &'a mut Vec<(BytePos, LineCol)>, + source_map: Lrc, comments: &'a dyn Comments, buffer: &'a mut Vec, + mappings: &'a mut Vec<(BytePos, LineCol)>, ) -> Emitter<'a, JsWriter<'a, &'a mut Vec>, SwcSourceMap> { Emitter { cfg: CodegenConfig::default().with_target(EsVersion::Es2022), diff --git a/rustfmt.toml b/rustfmt.toml index 3ca48f48..14b7b2fc 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,9 +1,10 @@ +chain_width = 90 edition = "2021" force_explicit_abi = true fn_params_layout = "Compressed" hard_tabs = true match_arm_leading_pipes = "Never" -max_width = 150 +max_width = 120 merge_derives = true newline_style = "Unix" remove_nested_parens = true