diff --git a/js/rust/build.rs b/js/rust/build.rs index a46f6bb476bc..f13ba5a35d42 100644 --- a/js/rust/build.rs +++ b/js/rust/build.rs @@ -28,8 +28,7 @@ fn build_jsglue_cpp() { /// Find the public include directory within our mozjs-sys crate dependency. fn get_mozjs_include_dir() -> path::PathBuf { - let out_dir = env::var("OUT_DIR") - .expect("cargo should invoke us with the OUT_DIR env var set"); + let out_dir = env::var("OUT_DIR").expect("cargo should invoke us with the OUT_DIR env var set"); let mut target_build_dir = path::PathBuf::from(out_dir); target_build_dir.push("../../"); @@ -37,12 +36,13 @@ fn get_mozjs_include_dir() -> path::PathBuf { let mut include_dir_glob = target_build_dir.display().to_string(); include_dir_glob.push_str("mozjs_sys-*/out/dist/include"); - let entries = glob::glob(&include_dir_glob) - .expect("Should find entries for mozjs-sys include dir"); + let entries = + glob::glob(&include_dir_glob).expect("Should find entries for mozjs-sys include dir"); for entry in entries { if let Ok(path) = entry { - return path.canonicalize() + return path + .canonicalize() .expect("Should canonicalize include path"); } } @@ -78,7 +78,8 @@ fn build_jsapi_bindings() { } let include_dir = get_mozjs_include_dir(); - let include_dir = include_dir.to_str() + let include_dir = include_dir + .to_str() .expect("Path to mozjs include dir should be utf-8"); builder = builder.clang_arg("-I"); builder = builder.clang_arg(include_dir); @@ -115,16 +116,19 @@ fn build_jsapi_bindings() { builder = builder.blacklist_type(ty); } - let bindings = builder.generate() + let bindings = builder + .generate() .expect("Should generate JSAPI bindings OK"); let out = path::PathBuf::from(env::var("OUT_DIR").unwrap()); if cfg!(feature = "debugmozjs") { - bindings.write_to_file(out.join("jsapi_debug.rs")) + bindings + .write_to_file(out.join("jsapi_debug.rs")) .expect("Should write bindings to file OK"); } else { - bindings.write_to_file(out.join("jsapi.rs")) + bindings + .write_to_file(out.join("jsapi.rs")) .expect("Should write bindings to file OK"); } @@ -142,7 +146,8 @@ const UNSAFE_IMPL_SYNC_TYPES: &'static [&'static str] = &[ /// Flags passed through bindgen directly to Clang. const EXTRA_CLANG_FLAGS: &'static [&'static str] = &[ - "-x", "c++", + "-x", + "c++", "-std=gnu++17", "-fno-sized-deallocation", "-fno-aligned-new", diff --git a/js/rust/src/ar.rs b/js/rust/src/ar.rs index eda1f7a75260..fdde11e1309c 100644 --- a/js/rust/src/ar.rs +++ b/js/rust/src/ar.rs @@ -11,50 +11,30 @@ pub struct AutoRealm(JSAutoRealm); impl AutoRealm { #[cfg(feature = "debugmozjs")] - pub unsafe fn with_obj(cx: *mut JSContext, - target: *mut JSObject) - -> AutoRealm - { + pub unsafe fn with_obj(cx: *mut JSContext, target: *mut JSObject) -> AutoRealm { let mut notifier = mozilla::detail::GuardObjectNotifier { mStatementDone: ptr::null_mut(), }; - AutoRealm( - JSAutoRealm::new( - cx, - target, - &mut notifier as *mut _)) + AutoRealm(JSAutoRealm::new(cx, target, &mut notifier as *mut _)) } #[cfg(not(feature = "debugmozjs"))] - pub unsafe fn with_obj(cx: *mut JSContext, - target: *mut JSObject) - -> AutoRealm - { + pub unsafe fn with_obj(cx: *mut JSContext, target: *mut JSObject) -> AutoRealm { AutoRealm(JSAutoRealm::new(cx, target)) } #[cfg(feature = "debugmozjs")] - pub unsafe fn with_script(cx: *mut JSContext, - target: *mut JSScript) - -> AutoRealm - { + pub unsafe fn with_script(cx: *mut JSContext, target: *mut JSScript) -> AutoRealm { let mut notifier = mozilla::detail::GuardObjectNotifier { mStatementDone: ptr::null_mut(), }; - AutoRealm( - JSAutoRealm::new1( - cx, - target, - &mut notifier as *mut _)) + AutoRealm(JSAutoRealm::new1(cx, target, &mut notifier as *mut _)) } #[cfg(not(feature = "debugmozjs"))] - pub unsafe fn with_script(cx: *mut JSContext, - target: *mut JSScript) - -> AutoRealm - { + pub unsafe fn with_script(cx: *mut JSContext, target: *mut JSScript) -> AutoRealm { AutoRealm(JSAutoRealm::new1(cx, target)) } } diff --git a/js/rust/src/conversions.rs b/js/rust/src/conversions.rs index 10c539bc5326..00331f70e059 100644 --- a/js/rust/src/conversions.rs +++ b/js/rust/src/conversions.rs @@ -35,11 +35,11 @@ use glue::RUST_JS_NumberValue; use heap::Heap; use jsapi::root::*; use jsval::{BooleanValue, Int32Value, NullValue, UInt32Value, UndefinedValue}; -use jsval::{ObjectValue, ObjectOrNullValue, StringValue}; -use rust::{ToBoolean, ToInt32, ToInt64, ToNumber, ToUint16, ToUint32, ToUint64}; -use rust::{ToString, maybe_wrap_object_or_null_value, maybe_wrap_value}; +use jsval::{ObjectOrNullValue, ObjectValue, StringValue}; use libc; use num_traits::{Bounded, Zero}; +use rust::{maybe_wrap_object_or_null_value, maybe_wrap_value, ToString}; +use rust::{ToBoolean, ToInt32, ToInt64, ToNumber, ToUint16, ToUint32, ToUint64}; use std::borrow::Cow; use std::rc::Rc; use std::{ptr, slice}; @@ -49,13 +49,13 @@ trait As: Copy { } macro_rules! impl_as { - ($I:ty, $O:ty) => ( + ($I:ty, $O:ty) => { impl As<$O> for $I { fn cast(self) -> $O { self as $O } } - ) + }; } impl_as!(f64, u8); @@ -105,7 +105,7 @@ impl ConversionResult { /// Map a function over the `Success` value. pub fn map(self, mut f: F) -> ConversionResult where - F: FnMut(T) -> U + F: FnMut(T) -> U, { match self { ConversionResult::Success(t) => ConversionResult::Success(f(t)), @@ -131,10 +131,11 @@ pub trait FromJSValConvertible: Sized { /// argument. /// If it returns `Err(())`, a JSAPI exception is pending. /// If it returns `Ok(Failure(reason))`, there is no pending JSAPI exception. - unsafe fn from_jsval(cx: *mut JSContext, - val: JS::HandleValue, - option: Self::Config) - -> Result, ()>; + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + option: Self::Config, + ) -> Result, ()>; } /// Behavior for converting out-of-range integers. @@ -154,11 +155,14 @@ pub struct Default(pub T); impl FromJSValConvertible for Default where - T: FromJSValConvertible + T: FromJSValConvertible, { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, val: JS::HandleValue, _: ()) - -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + _: (), + ) -> Result, ()> { T::from_jsval(cx, val, ConversionBehavior::Default).map(|conv| conv.map(Default)) } } @@ -168,14 +172,16 @@ where pub struct EnforceRange(pub T); impl FromJSValConvertible for EnforceRange - where - T: FromJSValConvertible +where + T: FromJSValConvertible, { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, val: JS::HandleValue, _: ()) - -> Result, ()> { - T::from_jsval(cx, val, ConversionBehavior::EnforceRange) - .map(|conv| conv.map(EnforceRange)) + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + _: (), + ) -> Result, ()> { + T::from_jsval(cx, val, ConversionBehavior::EnforceRange).map(|conv| conv.map(EnforceRange)) } } @@ -184,22 +190,25 @@ impl FromJSValConvertible for EnforceRange pub struct Clamp(pub T); impl FromJSValConvertible for Clamp - where - T: FromJSValConvertible +where + T: FromJSValConvertible, { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, val: JS::HandleValue, _: ()) - -> Result, ()> { - T::from_jsval(cx, val, ConversionBehavior::Clamp) - .map(|conv| conv.map(Clamp)) + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + _: (), + ) -> Result, ()> { + T::from_jsval(cx, val, ConversionBehavior::Clamp).map(|conv| conv.map(Clamp)) } } /// Try to cast the number to a smaller type, but /// if it doesn't fit, it will return an error. unsafe fn enforce_range(cx: *mut JSContext, d: f64) -> Result, ()> - where D: Bounded + As, - f64: As +where + D: Bounded + As, + f64: As, { if d.is_infinite() { throw_type_error(cx, "value out of range in an EnforceRange argument"); @@ -219,8 +228,9 @@ unsafe fn enforce_range(cx: *mut JSContext, d: f64) -> Result(d: f64) -> D - where D: Bounded + As + Zero, - f64: As +where + D: Bounded + As + Zero, + f64: As, { if d.is_nan() { D::zero() @@ -244,10 +254,11 @@ impl ToJSValConvertible for () { impl FromJSValConvertible for JS::HandleValue { type Config = (); #[inline] - unsafe fn from_jsval(cx: *mut JSContext, - value: JS::HandleValue, - _option: ()) - -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + value: JS::HandleValue, + _option: (), + ) -> Result, ()> { if value.is_object() { js::AssertSameCompartment(cx, value.to_object()); } @@ -257,21 +268,25 @@ impl FromJSValConvertible for JS::HandleValue { impl FromJSValConvertible for JS::Value { type Config = (); - unsafe fn from_jsval(_cx: *mut JSContext, - value: JS::HandleValue, - _option: ()) - -> Result, ()> { + unsafe fn from_jsval( + _cx: *mut JSContext, + value: JS::HandleValue, + _option: (), + ) -> Result, ()> { Ok(ConversionResult::Success(value.get())) } } impl FromJSValConvertible for Heap { type Config = (); - unsafe fn from_jsval(_cx: *mut JSContext, - value: JS::HandleValue, - _option: ()) - -> Result, ()> { - Ok(ConversionResult::Success(Heap::::new(value.get()))) + unsafe fn from_jsval( + _cx: *mut JSContext, + value: JS::HandleValue, + _option: (), + ) -> Result, ()> { + Ok(ConversionResult::Success(Heap::::new( + value.get(), + ))) } } @@ -300,18 +315,25 @@ impl ToJSValConvertible for Heap { } #[inline] -unsafe fn convert_int_from_jsval(cx: *mut JSContext, value: JS::HandleValue, - option: ConversionBehavior, - convert_fn: unsafe fn(*mut JSContext, JS::HandleValue) -> Result) - -> Result, ()> - where T: Bounded + Zero + As, - M: Zero + As, - f64: As +unsafe fn convert_int_from_jsval( + cx: *mut JSContext, + value: JS::HandleValue, + option: ConversionBehavior, + convert_fn: unsafe fn(*mut JSContext, JS::HandleValue) -> Result, +) -> Result, ()> +where + T: Bounded + Zero + As, + M: Zero + As, + f64: As, { match option { - ConversionBehavior::Default => Ok(ConversionResult::Success(try!(convert_fn(cx, value)).cast())), + ConversionBehavior::Default => Ok(ConversionResult::Success( + try!(convert_fn(cx, value)).cast(), + )), ConversionBehavior::EnforceRange => enforce_range(cx, try!(ToNumber(cx, value))), - ConversionBehavior::Clamp => Ok(ConversionResult::Success(clamp_to(try!(ToNumber(cx, value))))), + ConversionBehavior::Clamp => Ok(ConversionResult::Success(clamp_to(try!(ToNumber( + cx, value + ))))), } } @@ -326,7 +348,11 @@ impl ToJSValConvertible for bool { // https://heycam.github.io/webidl/#es-boolean impl FromJSValConvertible for bool { type Config = (); - unsafe fn from_jsval(_cx: *mut JSContext, val: JS::HandleValue, _option: ()) -> Result, ()> { + unsafe fn from_jsval( + _cx: *mut JSContext, + val: JS::HandleValue, + _option: (), + ) -> Result, ()> { Ok(ToBoolean(val)).map(ConversionResult::Success) } } @@ -342,10 +368,11 @@ impl ToJSValConvertible for i8 { // https://heycam.github.io/webidl/#es-byte impl FromJSValConvertible for i8 { type Config = ConversionBehavior; - unsafe fn from_jsval(cx: *mut JSContext, - val: JS::HandleValue, - option: ConversionBehavior) - -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + option: ConversionBehavior, + ) -> Result, ()> { convert_int_from_jsval(cx, val, option, ToInt32) } } @@ -361,10 +388,11 @@ impl ToJSValConvertible for u8 { // https://heycam.github.io/webidl/#es-octet impl FromJSValConvertible for u8 { type Config = ConversionBehavior; - unsafe fn from_jsval(cx: *mut JSContext, - val: JS::HandleValue, - option: ConversionBehavior) - -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + option: ConversionBehavior, + ) -> Result, ()> { convert_int_from_jsval(cx, val, option, ToInt32) } } @@ -380,10 +408,11 @@ impl ToJSValConvertible for i16 { // https://heycam.github.io/webidl/#es-short impl FromJSValConvertible for i16 { type Config = ConversionBehavior; - unsafe fn from_jsval(cx: *mut JSContext, - val: JS::HandleValue, - option: ConversionBehavior) - -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + option: ConversionBehavior, + ) -> Result, ()> { convert_int_from_jsval(cx, val, option, ToInt32) } } @@ -399,10 +428,11 @@ impl ToJSValConvertible for u16 { // https://heycam.github.io/webidl/#es-unsigned-short impl FromJSValConvertible for u16 { type Config = ConversionBehavior; - unsafe fn from_jsval(cx: *mut JSContext, - val: JS::HandleValue, - option: ConversionBehavior) - -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + option: ConversionBehavior, + ) -> Result, ()> { convert_int_from_jsval(cx, val, option, ToUint16) } } @@ -418,10 +448,11 @@ impl ToJSValConvertible for i32 { // https://heycam.github.io/webidl/#es-long impl FromJSValConvertible for i32 { type Config = ConversionBehavior; - unsafe fn from_jsval(cx: *mut JSContext, - val: JS::HandleValue, - option: ConversionBehavior) - -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + option: ConversionBehavior, + ) -> Result, ()> { convert_int_from_jsval(cx, val, option, ToInt32) } } @@ -437,10 +468,11 @@ impl ToJSValConvertible for u32 { // https://heycam.github.io/webidl/#es-unsigned-long impl FromJSValConvertible for u32 { type Config = ConversionBehavior; - unsafe fn from_jsval(cx: *mut JSContext, - val: JS::HandleValue, - option: ConversionBehavior) - -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + option: ConversionBehavior, + ) -> Result, ()> { convert_int_from_jsval(cx, val, option, ToUint32) } } @@ -456,10 +488,11 @@ impl ToJSValConvertible for i64 { // https://heycam.github.io/webidl/#es-long-long impl FromJSValConvertible for i64 { type Config = ConversionBehavior; - unsafe fn from_jsval(cx: *mut JSContext, - val: JS::HandleValue, - option: ConversionBehavior) - -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + option: ConversionBehavior, + ) -> Result, ()> { convert_int_from_jsval(cx, val, option, ToInt64) } } @@ -475,10 +508,11 @@ impl ToJSValConvertible for u64 { // https://heycam.github.io/webidl/#es-unsigned-long-long impl FromJSValConvertible for u64 { type Config = ConversionBehavior; - unsafe fn from_jsval(cx: *mut JSContext, - val: JS::HandleValue, - option: ConversionBehavior) - -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + option: ConversionBehavior, + ) -> Result, ()> { convert_int_from_jsval(cx, val, option, ToUint64) } } @@ -494,7 +528,11 @@ impl ToJSValConvertible for f32 { // https://heycam.github.io/webidl/#es-float impl FromJSValConvertible for f32 { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, val: JS::HandleValue, _option: ()) -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + _option: (), + ) -> Result, ()> { let result = ToNumber(cx, val); result.map(|f| f as f32).map(ConversionResult::Success) } @@ -511,7 +549,11 @@ impl ToJSValConvertible for f64 { // https://heycam.github.io/webidl/#es-double impl FromJSValConvertible for f64 { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, val: JS::HandleValue, _option: ()) -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + _option: (), + ) -> Result, ()> { ToNumber(cx, val).map(ConversionResult::Success) } } @@ -537,9 +579,11 @@ impl ToJSValConvertible for str { unsafe fn to_jsval(&self, cx: *mut JSContext, rval: JS::MutableHandleValue) { let mut string_utf16: Vec = Vec::with_capacity(self.len()); string_utf16.extend(self.encode_utf16()); - let jsstr = JS_NewUCStringCopyN(cx, - string_utf16.as_ptr(), - string_utf16.len() as libc::size_t); + let jsstr = JS_NewUCStringCopyN( + cx, + string_utf16.as_ptr(), + string_utf16.len() as libc::size_t, + ); if jsstr.is_null() { panic!("JS_NewUCStringCopyN failed"); } @@ -558,7 +602,11 @@ impl ToJSValConvertible for String { // https://heycam.github.io/webidl/#es-USVString impl FromJSValConvertible for String { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, value: JS::HandleValue, _: ()) -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + value: JS::HandleValue, + _: (), + ) -> Result, ()> { let jsstr = ToString(cx, value); if jsstr.is_null() { debug!("ToString failed"); @@ -595,17 +643,20 @@ impl ToJSValConvertible for Rc { impl FromJSValConvertible for Option { type Config = T::Config; - unsafe fn from_jsval(cx: *mut JSContext, - value: JS::HandleValue, - option: T::Config) - -> Result>, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + value: JS::HandleValue, + option: T::Config, + ) -> Result>, ()> { if value.get().is_null_or_undefined() { Ok(ConversionResult::Success(None)) } else { - Ok(match try!(FromJSValConvertible::from_jsval(cx, value, option)) { - ConversionResult::Success(v) => ConversionResult::Success(Some(v)), - ConversionResult::Failure(v) => ConversionResult::Failure(v), - }) + Ok( + match try!(FromJSValConvertible::from_jsval(cx, value, option)) { + ConversionResult::Success(v) => ConversionResult::Success(Some(v)), + ConversionResult::Failure(v) => ConversionResult::Failure(v), + }, + ) } } } @@ -639,7 +690,7 @@ impl ToJSValConvertible for Vec { /// but borrows and allows access to the whole ForOfIterator, so /// that methods on ForOfIterator can still be used through it. struct ForOfIteratorGuard<'a> { - root: &'a mut JS::ForOfIterator + root: &'a mut JS::ForOfIterator, } impl<'a> ForOfIteratorGuard<'a> { @@ -648,9 +699,7 @@ impl<'a> ForOfIteratorGuard<'a> { root.iterator.register_with_root_lists(cx); root.nextMethod.register_with_root_lists(cx); } - ForOfIteratorGuard { - root: root - } + ForOfIteratorGuard { root: root } } } @@ -663,13 +712,14 @@ impl<'a> Drop for ForOfIteratorGuard<'a> { } } -impl> FromJSValConvertible for Vec { +impl> FromJSValConvertible for Vec { type Config = C; - unsafe fn from_jsval(cx: *mut JSContext, - value: JS::HandleValue, - option: C) - -> Result>, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + value: JS::HandleValue, + option: C, + ) -> Result>, ()> { let mut iterator = JS::ForOfIterator { cx_: cx, iterator: JS::RootedObject::new_unrooted(), @@ -679,8 +729,11 @@ impl> FromJSValConvertible for Vec> FromJSValConvertible for Vec v, - ConversionResult::Failure(e) => return Ok(ConversionResult::Failure(e)), - }); + ret.push( + match try!(T::from_jsval(cx, val.handle(), option.clone())) { + ConversionResult::Success(v) => v, + ConversionResult::Failure(e) => return Ok(ConversionResult::Failure(e)), + }, + ); } Ok(ret).map(ConversionResult::Success) @@ -778,10 +833,11 @@ impl ToJSValConvertible for JS::Handle<*mut JSFunction> { impl FromJSValConvertible for *mut JSFunction { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, - val: JS::HandleValue, - _: ()) - -> Result, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + val: JS::HandleValue, + _: (), + ) -> Result, ()> { let func = JS_ValueToFunction(cx, val); if func.is_null() { Ok(ConversionResult::Failure("value is not a function".into())) diff --git a/js/rust/src/error.rs b/js/rust/src/error.rs index 1216e8b02b32..34a5fa828ab6 100644 --- a/js/rust/src/error.rs +++ b/js/rust/src/error.rs @@ -37,15 +37,18 @@ static mut RANGE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString /// Callback used to throw javascript errors. /// See throw_js_error for info about error_number. -unsafe extern "C" fn get_error_message(_user_ref: *mut os::raw::c_void, - error_number: libc::c_uint) - -> *const JSErrorFormatString { +unsafe extern "C" fn get_error_message( + _user_ref: *mut os::raw::c_void, + error_number: libc::c_uint, +) -> *const JSErrorFormatString { let num: JSExnType = mem::transmute(error_number); match num { JSExnType::JSEXN_TYPEERR => &TYPE_ERROR_FORMAT_STRING as *const JSErrorFormatString, JSExnType::JSEXN_RANGEERR => &RANGE_ERROR_FORMAT_STRING as *const JSErrorFormatString, - _ => panic!("Bad js error number given to get_error_message: {}", - error_number), + _ => panic!( + "Bad js error number given to get_error_message: {}", + error_number + ), } } @@ -55,11 +58,13 @@ unsafe extern "C" fn get_error_message(_user_ref: *mut os::raw::c_void, /// c_uint is u32, so this cast is safe, as is casting to/from i32 from there. unsafe fn throw_js_error(cx: *mut JSContext, error: &str, error_number: u32) { let error = CString::new(error).unwrap(); - JS_ReportErrorNumberUTF8(cx, - Some(get_error_message), - ptr::null_mut(), - error_number, - error.as_ptr()); + JS_ReportErrorNumberUTF8( + cx, + Some(get_error_message), + ptr::null_mut(), + error_number, + error.as_ptr(), + ); } /// Throw a `TypeError` with the given message. diff --git a/js/rust/src/glue.rs b/js/rust/src/glue.rs index d8dfbd9ad3ad..0c7ef7a68090 100644 --- a/js/rust/src/glue.rs +++ b/js/rust/src/glue.rs @@ -2,137 +2,197 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -use jsapi::root::*; use heap::Heap; +use jsapi::root::*; use std::os::raw::c_void; - -pub enum Action { } +pub enum Action {} unsafe impl Sync for ProxyTraps {} #[repr(C)] #[derive(Copy, Clone)] pub struct ProxyTraps { - pub enter: ::std::option::Option bool>, - pub getOwnPropertyDescriptor: - ::std::option::Option) - -> bool>, - pub defineProperty: - ::std::option::Option, - result: *mut JS::ObjectOpResult) - -> bool>, - pub ownPropertyKeys: ::std::option::Option bool>, - pub delete_: ::std::option::Option bool>, - pub enumerate: ::std::option::Option bool>, - pub getPrototypeIfOrdinary: - ::std::option::Option bool>, - pub preventExtensions: - ::std::option::Option bool>, - pub isExtensible: ::std::option::Option bool>, - pub has: ::std::option::Option bool>, - pub get: ::std::option::Option bool>, - pub set: ::std::option::Option bool>, - pub call: ::std::option::Option bool>, - pub construct: ::std::option::Option bool>, - pub hasOwn: ::std::option::Option bool>, - pub getOwnEnumerablePropertyKeys: - ::std::option::Option bool>, - pub nativeCall: ::std::option::Option bool>, - pub hasInstance: ::std::option::Option bool>, - pub objectClassIs: ::std::option::Option bool>, - pub className: ::std::option::Option *const i8>, - pub fun_toString: ::std::option::Option *mut JSString>, - pub boxedValue_unbox: ::std::option::Option bool>, - pub defaultValue: ::std::option::Option bool>, + pub enter: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + id: JS::HandleId, + action: Action, + bp: *mut bool, + ) -> bool, + >, + pub getOwnPropertyDescriptor: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + id: JS::HandleId, + desc: JS::MutableHandle, + ) -> bool, + >, + pub defineProperty: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + id: JS::HandleId, + desc: JS::Handle, + result: *mut JS::ObjectOpResult, + ) -> bool, + >, + pub ownPropertyKeys: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + props: JS::MutableHandleIdVector, + ) -> bool, + >, + pub delete_: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + id: JS::HandleId, + result: *mut JS::ObjectOpResult, + ) -> bool, + >, + pub enumerate: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + objp: JS::MutableHandleObject, + ) -> bool, + >, + pub getPrototypeIfOrdinary: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + isOrdinary: *mut bool, + protop: JS::MutableHandleObject, + ) -> bool, + >, + pub preventExtensions: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + result: *mut JS::ObjectOpResult, + ) -> bool, + >, + pub isExtensible: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + succeeded: *mut bool, + ) -> bool, + >, + pub has: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + id: JS::HandleId, + bp: *mut bool, + ) -> bool, + >, + pub get: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + receiver: JS::HandleValue, + id: JS::HandleId, + vp: JS::MutableHandleValue, + ) -> bool, + >, + pub set: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + id: JS::HandleId, + v: JS::HandleValue, + receiver: JS::HandleValue, + result: *mut JS::ObjectOpResult, + ) -> bool, + >, + pub call: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + args: *const JS::CallArgs, + ) -> bool, + >, + pub construct: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + args: *const JS::CallArgs, + ) -> bool, + >, + pub hasOwn: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + id: JS::HandleId, + bp: *mut bool, + ) -> bool, + >, + pub getOwnEnumerablePropertyKeys: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + props: JS::MutableHandleIdVector, + ) -> bool, + >, + pub nativeCall: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + test: JS::IsAcceptableThis, + _impl: JS::NativeImpl, + args: JS::CallArgs, + ) -> bool, + >, + pub hasInstance: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + v: JS::MutableHandleValue, + bp: *mut bool, + ) -> bool, + >, + pub objectClassIs: ::std::option::Option< + unsafe extern "C" fn( + obj: JS::HandleObject, + classValue: js::ESClass, + cx: *mut JSContext, + ) -> bool, + >, + pub className: ::std::option::Option< + unsafe extern "C" fn(cx: *mut JSContext, proxy: JS::HandleObject) -> *const i8, + >, + pub fun_toString: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + indent: u32, + ) -> *mut JSString, + >, + pub boxedValue_unbox: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + proxy: JS::HandleObject, + vp: JS::MutableHandleValue, + ) -> bool, + >, + pub defaultValue: ::std::option::Option< + unsafe extern "C" fn( + cx: *mut JSContext, + obj: JS::HandleObject, + hint: JSType, + vp: JS::MutableHandleValue, + ) -> bool, + >, pub trace: ::std::option::Option, pub finalize: ::std::option::Option, - pub objectMoved: - ::std::option::Option usize>, + pub objectMoved: ::std::option::Option< + unsafe extern "C" fn(proxy: *mut JSObject, old: *mut JSObject) -> usize, + >, pub isCallable: ::std::option::Option bool>, pub isConstructor: ::std::option::Option bool>, } @@ -164,80 +224,89 @@ impl ::std::default::Default for ForwardingProxyHandler { } extern "C" { - pub fn InvokeGetOwnPropertyDescriptor(handler: *const ::libc::c_void, - cx: *mut JSContext, - proxy: JS::HandleObject, - id: JS::HandleId, - desc: JS::MutableHandle) - -> bool; - pub fn InvokeHasOwn(handler: *const ::libc::c_void, - cx: *mut JSContext, - proxy: JS::HandleObject, - id: JS::HandleId, - bp: *mut bool) - -> bool; + pub fn InvokeGetOwnPropertyDescriptor( + handler: *const ::libc::c_void, + cx: *mut JSContext, + proxy: JS::HandleObject, + id: JS::HandleId, + desc: JS::MutableHandle, + ) -> bool; + pub fn InvokeHasOwn( + handler: *const ::libc::c_void, + cx: *mut JSContext, + proxy: JS::HandleObject, + id: JS::HandleId, + bp: *mut bool, + ) -> bool; pub fn RUST_JS_NumberValue(d: f64) -> JS::Value; pub fn RUST_FUNCTION_VALUE_TO_JITINFO(v: JS::Value) -> *const JSJitInfo; pub fn CreateCallArgsFromVp(argc: u32, v: *mut JS::Value) -> JS::CallArgs; - pub fn CallJitGetterOp(info: *const JSJitInfo, - cx: *mut JSContext, - thisObj: JS::HandleObject, - specializedThis: *mut ::libc::c_void, - argc: u32, - vp: *mut JS::Value) - -> bool; - pub fn CallJitSetterOp(info: *const JSJitInfo, - cx: *mut JSContext, - thisObj: JS::HandleObject, - specializedThis: *mut ::libc::c_void, - argc: u32, - vp: *mut JS::Value) - -> bool; - pub fn CallJitMethodOp(info: *const JSJitInfo, - cx: *mut JSContext, - thisObj: JS::HandleObject, - specializedThis: *mut ::libc::c_void, - argc: u32, - vp: *mut JS::Value) - -> bool; - pub fn CreateProxyHandler(aTraps: *const ProxyTraps, - aExtra: *const ::libc::c_void) - -> *const ::libc::c_void; + pub fn CallJitGetterOp( + info: *const JSJitInfo, + cx: *mut JSContext, + thisObj: JS::HandleObject, + specializedThis: *mut ::libc::c_void, + argc: u32, + vp: *mut JS::Value, + ) -> bool; + pub fn CallJitSetterOp( + info: *const JSJitInfo, + cx: *mut JSContext, + thisObj: JS::HandleObject, + specializedThis: *mut ::libc::c_void, + argc: u32, + vp: *mut JS::Value, + ) -> bool; + pub fn CallJitMethodOp( + info: *const JSJitInfo, + cx: *mut JSContext, + thisObj: JS::HandleObject, + specializedThis: *mut ::libc::c_void, + argc: u32, + vp: *mut JS::Value, + ) -> bool; + pub fn CreateProxyHandler( + aTraps: *const ProxyTraps, + aExtra: *const ::libc::c_void, + ) -> *const ::libc::c_void; pub fn CreateWrapperProxyHandler(aTraps: *const ProxyTraps) -> *const ::libc::c_void; - pub fn CreateRustJSPrincipal(origin: *const ::libc::c_void, - destroy: Option, - write: Option bool>) --> *mut JSPrincipals; + pub fn CreateRustJSPrincipal( + origin: *const ::libc::c_void, + destroy: Option, + write: Option< + unsafe extern "C" fn(cx: *mut JSContext, writer: *mut JSStructuredCloneWriter) -> bool, + >, + ) -> *mut JSPrincipals; pub fn GetPrincipalOrigin(principal: *const JSPrincipals) -> *const ::libc::c_void; pub fn GetCrossCompartmentWrapper() -> *const ::libc::c_void; pub fn GetSecurityWrapper() -> *const ::libc::c_void; - pub fn NewCompileOptions(aCx: *mut JSContext, - aFile: *const ::libc::c_char, - aLine: u32) - -> *mut JS::ReadOnlyCompileOptions; + pub fn NewCompileOptions( + aCx: *mut JSContext, + aFile: *const ::libc::c_char, + aLine: u32, + ) -> *mut JS::ReadOnlyCompileOptions; pub fn DeleteCompileOptions(aOpts: *mut JS::ReadOnlyCompileOptions); - pub fn NewProxyObject(aCx: *mut JSContext, - aHandler: *const ::libc::c_void, - aPriv: JS::HandleValue, - proto: *mut JSObject, - parent: *mut JSObject, - call: *mut JSObject, - construct: *mut JSObject) - -> *mut JSObject; - pub fn WrapperNew(aCx: *mut JSContext, - aObj: JS::HandleObject, - aHandler: *const ::libc::c_void, - aClass: *const JSClass, - aSingleton: bool) - -> *mut JSObject; - pub fn NewWindowProxy(aCx: *mut JSContext, - aObj: JS::HandleObject, - aHandler: *const ::libc::c_void) - -> *mut JSObject; + pub fn NewProxyObject( + aCx: *mut JSContext, + aHandler: *const ::libc::c_void, + aPriv: JS::HandleValue, + proto: *mut JSObject, + parent: *mut JSObject, + call: *mut JSObject, + construct: *mut JSObject, + ) -> *mut JSObject; + pub fn WrapperNew( + aCx: *mut JSContext, + aObj: JS::HandleObject, + aHandler: *const ::libc::c_void, + aClass: *const JSClass, + aSingleton: bool, + ) -> *mut JSObject; + pub fn NewWindowProxy( + aCx: *mut JSContext, + aObj: JS::HandleObject, + aHandler: *const ::libc::c_void, + ) -> *mut JSObject; pub fn GetWindowProxyClass() -> *const JSClass; pub fn GetProxyPrivate(obj: *mut JSObject) -> JS::Value; pub fn SetProxyPrivate(obj: *mut JSObject, private: *const JS::Value); @@ -251,9 +320,10 @@ extern "C" { pub fn RUST_SYMBOL_TO_JSID(sym: *mut JS::Symbol) -> jsid; pub fn RUST_SET_JITINFO(func: *mut JSFunction, info: *const JSJitInfo); pub fn RUST_INTERNED_STRING_TO_JSID(cx: *mut JSContext, str: *mut JSString) -> jsid; - pub fn RUST_js_GetErrorMessage(userRef: *mut ::libc::c_void, - errorNumber: u32) - -> *const JSErrorFormatString; + pub fn RUST_js_GetErrorMessage( + userRef: *mut ::libc::c_void, + errorNumber: u32, + ) -> *const JSErrorFormatString; pub fn IsProxyHandlerFamily(obj: *mut JSObject) -> u8; pub fn GetProxyHandlerExtra(obj: *mut JSObject) -> *const ::libc::c_void; pub fn GetProxyHandler(obj: *mut JSObject) -> *const ::libc::c_void; @@ -263,89 +333,132 @@ extern "C" { pub fn UncheckedUnwrapObject(obj: *mut JSObject, stopAtOuter: u8) -> *mut JSObject; pub fn CreateRootedIdVector(cx: *mut JSContext) -> *mut JS::PersistentRootedIdVector; pub fn AppendToRootedIdVector(v: *mut JS::PersistentRootedIdVector, id: jsid) -> bool; - pub fn SliceRootedIdVector(v: *const JS::PersistentRootedIdVector, length: *mut usize) -> *const jsid; + pub fn SliceRootedIdVector( + v: *const JS::PersistentRootedIdVector, + length: *mut usize, + ) -> *const jsid; pub fn DestroyRootedIdVector(v: *mut JS::PersistentRootedIdVector); - pub fn GetMutableHandleIdVector(v: *mut JS::PersistentRootedIdVector)-> JS::MutableHandleIdVector; + pub fn GetMutableHandleIdVector( + v: *mut JS::PersistentRootedIdVector, + ) -> JS::MutableHandleIdVector; pub fn CreateRootedObjectVector(aCx: *mut JSContext) -> *mut JS::PersistentRootedObjectVector; - pub fn AppendToRootedObjectVector(v: *mut JS::PersistentRootedObjectVector, obj: *mut JSObject) -> bool; + pub fn AppendToRootedObjectVector( + v: *mut JS::PersistentRootedObjectVector, + obj: *mut JSObject, + ) -> bool; pub fn DeleteRootedObjectVector(v: *mut JS::PersistentRootedObjectVector); pub fn CollectServoSizes(rt: *mut JSRuntime, sizes: *mut JS::ServoSizes) -> bool; pub fn CallIdTracer(trc: *mut JSTracer, idp: *mut Heap, name: *const ::libc::c_char); - pub fn CallValueTracer(trc: *mut JSTracer, - valuep: *mut Heap, - name: *const ::libc::c_char); - pub fn CallObjectTracer(trc: *mut JSTracer, - objp: *mut Heap<*mut JSObject>, - name: *const ::libc::c_char); - pub fn CallStringTracer(trc: *mut JSTracer, - strp: *mut Heap<*mut JSString>, - name: *const ::libc::c_char); + pub fn CallValueTracer( + trc: *mut JSTracer, + valuep: *mut Heap, + name: *const ::libc::c_char, + ); + pub fn CallObjectTracer( + trc: *mut JSTracer, + objp: *mut Heap<*mut JSObject>, + name: *const ::libc::c_char, + ); + pub fn CallStringTracer( + trc: *mut JSTracer, + strp: *mut Heap<*mut JSString>, + name: *const ::libc::c_char, + ); #[cfg(feature = "bigint")] - pub fn CallBigIntTracer(trc: *mut JSTracer, - bip: *mut Heap<*mut JS::BigInt>, - name: *const ::libc::c_char); - pub fn CallScriptTracer(trc: *mut JSTracer, - scriptp: *mut Heap<*mut JSScript>, - name: *const ::libc::c_char); - pub fn CallFunctionTracer(trc: *mut JSTracer, - funp: *mut Heap<*mut JSFunction>, - name: *const ::libc::c_char); - pub fn CallUnbarrieredObjectTracer(trc: *mut JSTracer, - objp: *mut *mut JSObject, - name: *const ::libc::c_char); + pub fn CallBigIntTracer( + trc: *mut JSTracer, + bip: *mut Heap<*mut JS::BigInt>, + name: *const ::libc::c_char, + ); + pub fn CallScriptTracer( + trc: *mut JSTracer, + scriptp: *mut Heap<*mut JSScript>, + name: *const ::libc::c_char, + ); + pub fn CallFunctionTracer( + trc: *mut JSTracer, + funp: *mut Heap<*mut JSFunction>, + name: *const ::libc::c_char, + ); + pub fn CallUnbarrieredObjectTracer( + trc: *mut JSTracer, + objp: *mut *mut JSObject, + name: *const ::libc::c_char, + ); pub fn GetProxyHandlerFamily() -> *const c_void; - pub fn GetInt8ArrayLengthAndData(obj: *mut JSObject, - length: *mut u32, - isSharedMemory: *mut bool, - data: *mut *mut i8); - pub fn GetUint8ArrayLengthAndData(obj: *mut JSObject, - length: *mut u32, - isSharedMemory: *mut bool, - data: *mut *mut u8); - pub fn GetUint8ClampedArrayLengthAndData(obj: *mut JSObject, - length: *mut u32, - isSharedMemory: *mut bool, - data: *mut *mut u8); - pub fn GetInt16ArrayLengthAndData(obj: *mut JSObject, - length: *mut u32, - isSharedMemory: *mut bool, - data: *mut *mut i16); - pub fn GetUint16ArrayLengthAndData(obj: *mut JSObject, - length: *mut u32, - isSharedMemory: *mut bool, - data: *mut *mut u16); - pub fn GetInt32ArrayLengthAndData(obj: *mut JSObject, - length: *mut u32, - isSharedMemory: *mut bool, - data: *mut *mut i32); - pub fn GetUint32ArrayLengthAndData(obj: *mut JSObject, - length: *mut u32, - isSharedMemory: *mut bool, - data: *mut *mut u32); - pub fn GetFloat32ArrayLengthAndData(obj: *mut JSObject, - length: *mut u32, - isSharedMemory: *mut bool, - data: *mut *mut f32); - pub fn GetFloat64ArrayLengthAndData(obj: *mut JSObject, - length: *mut u32, - isSharedMemory: *mut bool, - data: *mut *mut f64); + pub fn GetInt8ArrayLengthAndData( + obj: *mut JSObject, + length: *mut u32, + isSharedMemory: *mut bool, + data: *mut *mut i8, + ); + pub fn GetUint8ArrayLengthAndData( + obj: *mut JSObject, + length: *mut u32, + isSharedMemory: *mut bool, + data: *mut *mut u8, + ); + pub fn GetUint8ClampedArrayLengthAndData( + obj: *mut JSObject, + length: *mut u32, + isSharedMemory: *mut bool, + data: *mut *mut u8, + ); + pub fn GetInt16ArrayLengthAndData( + obj: *mut JSObject, + length: *mut u32, + isSharedMemory: *mut bool, + data: *mut *mut i16, + ); + pub fn GetUint16ArrayLengthAndData( + obj: *mut JSObject, + length: *mut u32, + isSharedMemory: *mut bool, + data: *mut *mut u16, + ); + pub fn GetInt32ArrayLengthAndData( + obj: *mut JSObject, + length: *mut u32, + isSharedMemory: *mut bool, + data: *mut *mut i32, + ); + pub fn GetUint32ArrayLengthAndData( + obj: *mut JSObject, + length: *mut u32, + isSharedMemory: *mut bool, + data: *mut *mut u32, + ); + pub fn GetFloat32ArrayLengthAndData( + obj: *mut JSObject, + length: *mut u32, + isSharedMemory: *mut bool, + data: *mut *mut f32, + ); + pub fn GetFloat64ArrayLengthAndData( + obj: *mut JSObject, + length: *mut u32, + isSharedMemory: *mut bool, + data: *mut *mut f64, + ); - pub fn NewJSAutoStructuredCloneBuffer(scope: JS::StructuredCloneScope, - callbacks: *const JSStructuredCloneCallbacks) - -> *mut JSAutoStructuredCloneBuffer; + pub fn NewJSAutoStructuredCloneBuffer( + scope: JS::StructuredCloneScope, + callbacks: *const JSStructuredCloneCallbacks, + ) -> *mut JSAutoStructuredCloneBuffer; pub fn DeleteJSAutoStructuredCloneBuffer(buf: *mut JSAutoStructuredCloneBuffer); pub fn GetLengthOfJSStructuredCloneData(data: *mut JSStructuredCloneData) -> usize; pub fn CopyJSStructuredCloneData(src: *mut JSStructuredCloneData, dest: *mut u8); - pub fn WriteBytesToJSStructuredCloneData(src: *const u8, - len: usize, - dest: *mut JSStructuredCloneData) - -> bool; + pub fn WriteBytesToJSStructuredCloneData( + src: *const u8, + len: usize, + dest: *mut JSStructuredCloneData, + ) -> bool; - pub fn JSEncodeStringToUTF8(cx: *mut JSContext, - string: JS::HandleString) - -> *mut ::libc::c_char; + pub fn JSEncodeStringToUTF8( + cx: *mut JSContext, + string: JS::HandleString, + ) -> *mut ::libc::c_char; pub fn IsDebugBuild() -> bool; } diff --git a/js/rust/src/heap.rs b/js/rust/src/heap.rs index e25a60e187f9..7c39feaf27e8 100644 --- a/js/rust/src/heap.rs +++ b/js/rust/src/heap.rs @@ -51,7 +51,8 @@ pub struct Heap { impl Heap { pub fn new(v: T) -> Heap - where Heap: Default + where + Heap: Default, { let ptr = Heap::default(); ptr.set(v); @@ -68,9 +69,7 @@ impl Heap { } pub fn get(&self) -> T { - unsafe { - *self.ptr.get() - } + unsafe { *self.ptr.get() } } pub unsafe fn get_unsafe(&self) -> *mut T { @@ -78,20 +77,17 @@ impl Heap { } pub fn handle(&self) -> JS::Handle { - unsafe { - JS::Handle::from_marked_location(self.ptr.get() as *const _) - } + unsafe { JS::Handle::from_marked_location(self.ptr.get() as *const _) } } pub fn handle_mut(&self) -> JS::MutableHandle { - unsafe { - JS::MutableHandle::from_marked_location(self.ptr.get()) - } + unsafe { JS::MutableHandle::from_marked_location(self.ptr.get()) } } } impl Clone for Heap - where Heap: Default +where + Heap: Default, { fn clone(&self) -> Self { Heap::new(self.get()) @@ -105,11 +101,12 @@ impl PartialEq for Heap { } impl Default for Heap<*mut T> - where *mut T: GCMethods + Copy +where + *mut T: GCMethods + Copy, { fn default() -> Heap<*mut T> { Heap { - ptr: UnsafeCell::new(ptr::null_mut()) + ptr: UnsafeCell::new(ptr::null_mut()), } } } @@ -117,7 +114,7 @@ impl Default for Heap<*mut T> impl Default for Heap { fn default() -> Heap { Heap { - ptr: UnsafeCell::new(JS::Value::default()) + ptr: UnsafeCell::new(JS::Value::default()), } } } @@ -135,7 +132,7 @@ impl Drop for Heap { macro_rules! c_str { ($str:expr) => { concat!($str, "\0").as_ptr() as *const ::std::os::raw::c_char - } + }; } unsafe impl Trace for Heap<*mut JSFunction> { diff --git a/js/rust/src/jsval.rs b/js/rust/src/jsval.rs index ac9e42647494..f3a388605a03 100644 --- a/js/rust/src/jsval.rs +++ b/js/rust/src/jsval.rs @@ -2,7 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ - use jsapi::root::*; use libc::c_void; use std::mem; @@ -21,16 +20,16 @@ const JSVAL_TAG_CLEAR: u32 = 0xFFFFFF80; #[allow(dead_code)] #[derive(Clone, Copy, Debug)] enum ValueTag { - INT32 = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_INT32 as u32), + INT32 = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_INT32 as u32), UNDEFINED = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_UNDEFINED as u32), - STRING = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_STRING as u32), - SYMBOL = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_SYMBOL as u32), + STRING = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_STRING as u32), + SYMBOL = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_SYMBOL as u32), #[cfg(feature = "bigint")] - BIGINT = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_BIGINT as u32), - BOOLEAN = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_BOOLEAN as u32), - MAGIC = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_MAGIC as u32), - NULL = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_NULL as u32), - OBJECT = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_OBJECT as u32), + BIGINT = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_BIGINT as u32), + BOOLEAN = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_BOOLEAN as u32), + MAGIC = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_MAGIC as u32), + NULL = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_NULL as u32), + OBJECT = JSVAL_TAG_MAX_DOUBLE | (JSValueType::JSVAL_TYPE_OBJECT as u32), } #[cfg(target_pointer_width = "32")] @@ -38,17 +37,17 @@ enum ValueTag { #[allow(dead_code)] #[derive(Clone, Copy, Debug)] enum ValueTag { - PRIVATE = 0, - INT32 = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_INT32 as u32), + PRIVATE = 0, + INT32 = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_INT32 as u32), UNDEFINED = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_UNDEFINED as u32), - STRING = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_STRING as u32), - SYMBOL = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_SYMBOL as u32), + STRING = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_STRING as u32), + SYMBOL = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_SYMBOL as u32), #[cfg(feature = "bigint")] - BIGINT = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_BIGINT as u32), - BOOLEAN = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_BOOLEAN as u32), - MAGIC = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_MAGIC as u32), - NULL = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_NULL as u32), - OBJECT = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_OBJECT as u32), + BIGINT = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_BIGINT as u32), + BOOLEAN = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_BOOLEAN as u32), + MAGIC = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_MAGIC as u32), + NULL = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_NULL as u32), + OBJECT = JSVAL_TAG_CLEAR as u32 | (JSValueType::JSVAL_TYPE_OBJECT as u32), } #[cfg(target_pointer_width = "64")] @@ -57,27 +56,24 @@ enum ValueTag { #[derive(Clone, Copy, Debug)] enum ValueShiftedTag { MAX_DOUBLE = (((JSVAL_TAG_MAX_DOUBLE as u64) << JSVAL_TAG_SHIFT) | 0xFFFFFFFFu64), - INT32 = ((ValueTag::INT32 as u64) << JSVAL_TAG_SHIFT), - UNDEFINED = ((ValueTag::UNDEFINED as u64) << JSVAL_TAG_SHIFT), - STRING = ((ValueTag::STRING as u64) << JSVAL_TAG_SHIFT), - SYMBOL = ((ValueTag::SYMBOL as u64) << JSVAL_TAG_SHIFT), + INT32 = ((ValueTag::INT32 as u64) << JSVAL_TAG_SHIFT), + UNDEFINED = ((ValueTag::UNDEFINED as u64) << JSVAL_TAG_SHIFT), + STRING = ((ValueTag::STRING as u64) << JSVAL_TAG_SHIFT), + SYMBOL = ((ValueTag::SYMBOL as u64) << JSVAL_TAG_SHIFT), #[cfg(feature = "bigint")] - BIGINT = ((ValueTag::BIGINT as u64) << JSVAL_TAG_SHIFT), - BOOLEAN = ((ValueTag::BOOLEAN as u64) << JSVAL_TAG_SHIFT), - MAGIC = ((ValueTag::MAGIC as u64) << JSVAL_TAG_SHIFT), - NULL = ((ValueTag::NULL as u64) << JSVAL_TAG_SHIFT), - OBJECT = ((ValueTag::OBJECT as u64) << JSVAL_TAG_SHIFT), + BIGINT = ((ValueTag::BIGINT as u64) << JSVAL_TAG_SHIFT), + BOOLEAN = ((ValueTag::BOOLEAN as u64) << JSVAL_TAG_SHIFT), + MAGIC = ((ValueTag::MAGIC as u64) << JSVAL_TAG_SHIFT), + NULL = ((ValueTag::NULL as u64) << JSVAL_TAG_SHIFT), + OBJECT = ((ValueTag::OBJECT as u64) << JSVAL_TAG_SHIFT), } - #[cfg(target_pointer_width = "64")] const JSVAL_PAYLOAD_MASK: u64 = 0x00007FFFFFFFFFFF; #[inline(always)] fn AsJSVal(val: u64) -> JS::Value { - JS::Value { - asBits_: val, - } + JS::Value { asBits_: val } } #[cfg(target_pointer_width = "64")] @@ -219,33 +215,25 @@ impl JS::Value { #[inline(always)] #[cfg(target_pointer_width = "64")] pub fn is_undefined(&self) -> bool { - unsafe { - self.asBits() == ValueShiftedTag::UNDEFINED as u64 - } + unsafe { self.asBits() == ValueShiftedTag::UNDEFINED as u64 } } #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn is_undefined(&self) -> bool { - unsafe { - (self.asBits() >> 32) == ValueTag::UNDEFINED as u64 - } + unsafe { (self.asBits() >> 32) == ValueTag::UNDEFINED as u64 } } #[inline(always)] #[cfg(target_pointer_width = "64")] pub fn is_null(&self) -> bool { - unsafe { - self.asBits() == ValueShiftedTag::NULL as u64 - } + unsafe { self.asBits() == ValueShiftedTag::NULL as u64 } } #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn is_null(&self) -> bool { - unsafe { - (self.asBits() >> 32) == ValueTag::NULL as u64 - } + unsafe { (self.asBits() >> 32) == ValueTag::NULL as u64 } } #[inline(always)] @@ -256,101 +244,77 @@ impl JS::Value { #[inline(always)] #[cfg(target_pointer_width = "64")] pub fn is_boolean(&self) -> bool { - unsafe { - (self.asBits() >> JSVAL_TAG_SHIFT) == ValueTag::BOOLEAN as u64 - } + unsafe { (self.asBits() >> JSVAL_TAG_SHIFT) == ValueTag::BOOLEAN as u64 } } #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn is_boolean(&self) -> bool { - unsafe { - (self.asBits() >> 32) == ValueTag::BOOLEAN as u64 - } + unsafe { (self.asBits() >> 32) == ValueTag::BOOLEAN as u64 } } #[inline(always)] #[cfg(target_pointer_width = "64")] pub fn is_int32(&self) -> bool { - unsafe { - (self.asBits() >> JSVAL_TAG_SHIFT) == ValueTag::INT32 as u64 - } + unsafe { (self.asBits() >> JSVAL_TAG_SHIFT) == ValueTag::INT32 as u64 } } #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn is_int32(&self) -> bool { - unsafe { - (self.asBits() >> 32) == ValueTag::INT32 as u64 - } + unsafe { (self.asBits() >> 32) == ValueTag::INT32 as u64 } } #[inline(always)] #[cfg(target_pointer_width = "64")] pub fn is_double(&self) -> bool { - unsafe { - self.asBits() <= ValueShiftedTag::MAX_DOUBLE as u64 - } + unsafe { self.asBits() <= ValueShiftedTag::MAX_DOUBLE as u64 } } #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn is_double(&self) -> bool { - unsafe { - (self.asBits() >> 32) <= JSVAL_TAG_CLEAR as u64 - } + unsafe { (self.asBits() >> 32) <= JSVAL_TAG_CLEAR as u64 } } #[inline(always)] #[cfg(target_pointer_width = "64")] pub fn is_number(&self) -> bool { const JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET: u64 = ValueShiftedTag::UNDEFINED as u64; - unsafe { - self.asBits() < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET - } + unsafe { self.asBits() < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET } } #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn is_number(&self) -> bool { const JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET: u64 = ValueTag::INT32 as u64; - unsafe { - (self.asBits() >> 32) <= JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET - } + unsafe { (self.asBits() >> 32) <= JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET } } #[inline(always)] #[cfg(target_pointer_width = "64")] pub fn is_primitive(&self) -> bool { const JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET: u64 = ValueShiftedTag::OBJECT as u64; - unsafe { - self.asBits() < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET - } + unsafe { self.asBits() < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET } } #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn is_primitive(&self) -> bool { const JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET: u64 = ValueTag::OBJECT as u64; - unsafe { - (self.asBits() >> 32) < JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET - } + unsafe { (self.asBits() >> 32) < JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET } } #[inline(always)] #[cfg(target_pointer_width = "64")] pub fn is_string(&self) -> bool { - unsafe { - (self.asBits() >> JSVAL_TAG_SHIFT) == ValueTag::STRING as u64 - } + unsafe { (self.asBits() >> JSVAL_TAG_SHIFT) == ValueTag::STRING as u64 } } #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn is_string(&self) -> bool { - unsafe { - (self.asBits() >> 32) == ValueTag::STRING as u64 - } + unsafe { (self.asBits() >> 32) == ValueTag::STRING as u64 } } #[inline(always)] @@ -365,69 +329,53 @@ impl JS::Value { #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn is_object(&self) -> bool { - unsafe { - (self.asBits() >> 32) == ValueTag::OBJECT as u64 - } + unsafe { (self.asBits() >> 32) == ValueTag::OBJECT as u64 } } #[inline(always)] #[cfg(target_pointer_width = "64")] pub fn is_symbol(&self) -> bool { - unsafe { - (self.asBits() >> JSVAL_TAG_SHIFT) == ValueTag::SYMBOL as u64 - } + unsafe { (self.asBits() >> JSVAL_TAG_SHIFT) == ValueTag::SYMBOL as u64 } } #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn is_symbol(&self) -> bool { - unsafe { - (self.asBits() >> 32) == ValueTag::SYMBOL as u64 - } + unsafe { (self.asBits() >> 32) == ValueTag::SYMBOL as u64 } } #[inline(always)] #[cfg(feature = "bigint")] #[cfg(target_pointer_width = "64")] pub fn is_bigint(&self) -> bool { - unsafe { - (self.asBits() >> JSVAL_TAG_SHIFT) == ValueTag::BIGINT as u64 - } + unsafe { (self.asBits() >> JSVAL_TAG_SHIFT) == ValueTag::BIGINT as u64 } } #[inline(always)] #[cfg(feature = "bigint")] #[cfg(target_pointer_width = "32")] pub fn is_bigint(&self) -> bool { - unsafe { - (self.asBits() >> 32) == ValueTag::BIGINT as u64 - } + unsafe { (self.asBits() >> 32) == ValueTag::BIGINT as u64 } } #[inline(always)] #[cfg(target_pointer_width = "64")] pub fn to_boolean(&self) -> bool { assert!(self.is_boolean()); - unsafe { - (self.asBits() & JSVAL_PAYLOAD_MASK) != 0 - } + unsafe { (self.asBits() & JSVAL_PAYLOAD_MASK) != 0 } } #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn to_boolean(&self) -> bool { assert!(self.is_boolean()); - unsafe { - (self.asBits() & 0x00000000FFFFFFFF) != 0 - } + unsafe { (self.asBits() & 0x00000000FFFFFFFF) != 0 } } #[inline(always)] pub fn to_int32(&self) -> i32 { assert!(self.is_int32()); - unsafe { - (self.asBits() & 0x00000000FFFFFFFF) as i32 - } + unsafe { (self.asBits() & 0x00000000FFFFFFFF) as i32 } } #[inline(always)] @@ -536,18 +484,14 @@ impl JS::Value { #[cfg(target_pointer_width = "64")] pub fn is_gcthing(&self) -> bool { const JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET: u64 = ValueShiftedTag::STRING as u64; - unsafe { - self.asBits() >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET - } + unsafe { self.asBits() >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET } } #[inline(always)] #[cfg(target_pointer_width = "32")] pub fn is_gcthing(&self) -> bool { const JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET: u64 = ValueTag::STRING as u64; - unsafe { - (self.asBits() >> 32) >= JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET - } + unsafe { (self.asBits() >> 32) >= JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET } } #[inline(always)] diff --git a/js/rust/src/lib.rs b/js/rust/src/lib.rs index 46722628f008..c16d1e1702f1 100644 --- a/js/rust/src/lib.rs +++ b/js/rust/src/lib.rs @@ -4,10 +4,13 @@ #![crate_name = "js"] #![crate_type = "rlib"] - #![cfg_attr(feature = "nonzero", feature(nonzero))] - -#![allow(non_upper_case_globals, non_camel_case_types, non_snake_case, improper_ctypes)] +#![allow( + non_upper_case_globals, + non_camel_case_types, + non_snake_case, + improper_ctypes +)] #[cfg(feature = "nonzero")] extern crate core; diff --git a/js/rust/src/panic.rs b/js/rust/src/panic.rs index 351e24f77350..496ed9b33d4d 100644 --- a/js/rust/src/panic.rs +++ b/js/rust/src/panic.rs @@ -4,7 +4,7 @@ use std::any::Any; use std::cell::RefCell; -use std::panic::{UnwindSafe, catch_unwind, resume_unwind}; +use std::panic::{catch_unwind, resume_unwind, UnwindSafe}; thread_local!(static PANIC_RESULT: RefCell>> = RefCell::new(None)); @@ -17,7 +17,8 @@ pub fn maybe_resume_unwind() { /// Generic wrapper for JS engine callbacks panic-catching pub fn wrap_panic(function: F, generic_return_type: R) -> R - where F: FnOnce() -> R + UnwindSafe +where + F: FnOnce() -> R + UnwindSafe, { let result = catch_unwind(function); match result { diff --git a/js/rust/src/rust.rs b/js/rust/src/rust.rs index ff52bb1745d6..ef98c6e934b6 100644 --- a/js/rust/src/rust.rs +++ b/js/rust/src/rust.rs @@ -5,27 +5,32 @@ //! Rust wrappers around the raw JS apis use ar::AutoRealm; -use libc::c_uint; -use std::cell::{Cell, UnsafeCell}; -use std::char; -use std::ffi; -use std::ptr; -use std::slice; -use std::mem; -use std::u32; -use std::default::Default; -use std::marker; -use std::ops::{Deref, DerefMut}; -use std::sync::{Once, ONCE_INIT, Arc, Mutex}; -use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; -use std::sync::mpsc::{SyncSender, sync_channel}; -use std::thread; +use glue::{ + AppendToRootedObjectVector, CreateCallArgsFromVp, CreateRootedObjectVector, + DeleteRootedObjectVector, IsDebugBuild, +}; +use glue::{ + CreateRootedIdVector, DestroyRootedIdVector, GetMutableHandleIdVector, SliceRootedIdVector, +}; +use glue::{DeleteCompileOptions, NewCompileOptions}; use jsapi::root::*; use jsval::{self, UndefinedValue}; -use glue::{CreateRootedObjectVector, CreateCallArgsFromVp, AppendToRootedObjectVector, DeleteRootedObjectVector, IsDebugBuild}; -use glue::{CreateRootedIdVector, SliceRootedIdVector, DestroyRootedIdVector, GetMutableHandleIdVector}; -use glue::{NewCompileOptions, DeleteCompileOptions}; +use libc::c_uint; use panic; +use std::cell::{Cell, UnsafeCell}; +use std::char; +use std::default::Default; +use std::ffi; +use std::marker; +use std::mem; +use std::ops::{Deref, DerefMut}; +use std::ptr; +use std::slice; +use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; +use std::sync::mpsc::{sync_channel, SyncSender}; +use std::sync::{Arc, Mutex, Once, ONCE_INIT}; +use std::thread; +use std::u32; const DEFAULT_HEAPSIZE: u32 = 32_u32 * 1024_u32 * 1024_u32; @@ -77,9 +82,7 @@ pub struct Runtime { impl Runtime { /// Get the `JSContext` for this thread. pub fn get() -> *mut JSContext { - let cx = CONTEXT.with(|context| { - context.get() - }); + let cx = CONTEXT.with(|context| context.get()); assert!(!cx.is_null()); cx } @@ -112,9 +115,7 @@ impl Runtime { } fn as_atomic(&self) -> &AtomicPtr { - unsafe { - mem::transmute(&self.0) - } + unsafe { mem::transmute(&self.0) } } } @@ -132,12 +133,13 @@ impl Runtime { let is_debug_mozjs = cfg!(feature = "debugmozjs"); let diagnostic = JS::detail::InitWithFailureDiagnostic(is_debug_mozjs); if !diagnostic.is_null() { - panic!("JS::detail::InitWithFailureDiagnostic failed: {}", - ffi::CStr::from_ptr(diagnostic).to_string_lossy()); + panic!( + "JS::detail::InitWithFailureDiagnostic failed: {}", + ffi::CStr::from_ptr(diagnostic).to_string_lossy() + ); } - let context = JS_NewContext( - DEFAULT_HEAPSIZE, ptr::null_mut()); + let context = JS_NewContext(DEFAULT_HEAPSIZE, ptr::null_mut()); assert!(!context.is_null()); JS::InitSelfHostedCode(context); PARENT.set(context); @@ -159,8 +161,7 @@ impl Runtime { assert_eq!(IsDebugBuild(), cfg!(feature = "debugmozjs")); - let js_context = JS_NewContext(DEFAULT_HEAPSIZE, - JS_GetParentRuntime(PARENT.get())); + let js_context = JS_NewContext(DEFAULT_HEAPSIZE, JS_GetParentRuntime(PARENT.get())); assert!(!js_context.is_null()); // Unconstrain the runtime's threshold on nominal heap size, to avoid @@ -168,14 +169,14 @@ impl Runtime { // finite threshold. This leaves the maximum-JS_malloc-bytes threshold // still in effect to cause periodical, and we hope hygienic, // last-ditch GCs from within the GC's allocator. - JS_SetGCParameter( - js_context, JSGCParamKey::JSGC_MAX_BYTES, u32::MAX); + JS_SetGCParameter(js_context, JSGCParamKey::JSGC_MAX_BYTES, u32::MAX); JS_SetNativeStackQuota( js_context, STACK_QUOTA, STACK_QUOTA - SYSTEM_CODE_BUFFER, - STACK_QUOTA - SYSTEM_CODE_BUFFER - TRUSTED_SCRIPT_BUFFER); + STACK_QUOTA - SYSTEM_CODE_BUFFER - TRUSTED_SCRIPT_BUFFER, + ); CONTEXT.with(|context| { assert!(context.get().is_null()); @@ -190,9 +191,7 @@ impl Runtime { JS::SetWarningReporter(js_context, Some(report_warning)); - Ok(Runtime { - cx: js_context, - }) + Ok(Runtime { cx: js_context }) } } @@ -203,17 +202,23 @@ impl Runtime { /// Returns the underlying `JSContext`'s `JSRuntime`. pub fn rt(&self) -> *mut JSRuntime { - unsafe { - JS_GetRuntime(self.cx) - } + unsafe { JS_GetRuntime(self.cx) } } - pub fn evaluate_script(&self, glob: JS::HandleObject, script: &str, filename: &str, - line_num: u32, rval: JS::MutableHandleValue) - -> Result<(),()> { + pub fn evaluate_script( + &self, + glob: JS::HandleObject, + script: &str, + filename: &str, + line_num: u32, + rval: JS::MutableHandleValue, + ) -> Result<(), ()> { let script_utf16: Vec = script.encode_utf16().collect(); let filename_cstr = ffi::CString::new(filename.as_bytes()).unwrap(); - debug!("Evaluating script from {} with content {}", filename, script); + debug!( + "Evaluating script from {} with content {}", + filename, script + ); // SpiderMonkey does not approve of null pointers. let (ptr, len) = if script_utf16.len() == 0 { static empty: &'static [u16] = &[]; @@ -230,7 +235,7 @@ impl Runtime { units_: ptr, length_: len as _, ownsUnits_: false, - _phantom_0: marker::PhantomData + _phantom_0: marker::PhantomData, }; if !JS::Evaluate(self.cx(), options.ptr, &mut srcBuf, rval) { debug!("...err!"); @@ -280,53 +285,72 @@ pub trait RootKind { impl RootKind for *mut JSObject { #[inline(always)] - fn rootKind() -> JS::RootKind { JS::RootKind::Object } + fn rootKind() -> JS::RootKind { + JS::RootKind::Object + } } impl RootKind for *mut JSLinearString { #[inline(always)] - fn rootKind() -> JS::RootKind { JS::RootKind::String } + fn rootKind() -> JS::RootKind { + JS::RootKind::String + } } impl RootKind for *mut JSFunction { #[inline(always)] - fn rootKind() -> JS::RootKind { JS::RootKind::Object } + fn rootKind() -> JS::RootKind { + JS::RootKind::Object + } } impl RootKind for *mut JSString { #[inline(always)] - fn rootKind() -> JS::RootKind { JS::RootKind::String } + fn rootKind() -> JS::RootKind { + JS::RootKind::String + } } impl RootKind for *mut JS::Symbol { #[inline(always)] - fn rootKind() -> JS::RootKind { JS::RootKind::Symbol } + fn rootKind() -> JS::RootKind { + JS::RootKind::Symbol + } } #[cfg(feature = "bigint")] impl RootKind for *mut JS::BigInt { #[inline(always)] - fn rootKind() -> JS::RootKind { JS::RootKind::BigInt } + fn rootKind() -> JS::RootKind { + JS::RootKind::BigInt + } } impl RootKind for *mut JSScript { #[inline(always)] - fn rootKind() -> JS::RootKind { JS::RootKind::Script } + fn rootKind() -> JS::RootKind { + JS::RootKind::Script + } } impl RootKind for jsid { #[inline(always)] - fn rootKind() -> JS::RootKind { JS::RootKind::Id } + fn rootKind() -> JS::RootKind { + JS::RootKind::Id + } } impl RootKind for JS::Value { #[inline(always)] - fn rootKind() -> JS::RootKind { JS::RootKind::Value } + fn rootKind() -> JS::RootKind { + JS::RootKind::Value + } } impl JS::Rooted { pub fn new_unrooted() -> JS::Rooted - where T: GCMethods, + where + T: GCMethods, { JS::Rooted { stack: ptr::null_mut(), @@ -340,9 +364,11 @@ impl JS::Rooted { mem::transmute(cx) } - unsafe fn get_root_stack(cx: *mut JSContext) - -> *mut *mut JS::Rooted<*mut ::std::os::raw::c_void> - where T: RootKind + unsafe fn get_root_stack( + cx: *mut JSContext, + ) -> *mut *mut JS::Rooted<*mut ::std::os::raw::c_void> + where + T: RootKind, { let kind = T::rootKind() as usize; let rooting_cx = Self::get_rooting_context(cx); @@ -350,7 +376,8 @@ impl JS::Rooted { } pub unsafe fn register_with_root_lists(&mut self, cx: *mut JSContext) - where T: RootKind + where + T: RootKind, { self.stack = Self::get_root_stack(cx); let stack = self.stack.as_mut().unwrap(); @@ -369,7 +396,7 @@ impl JS::Rooted { /// Example usage: `rooted!(in(cx) let x = UndefinedValue());`. /// `RootedGuard::new` also works, but the macro is preferred. pub struct RootedGuard<'a, T: 'a + RootKind + GCMethods> { - root: &'a mut JS::Rooted + root: &'a mut JS::Rooted, } impl<'a, T: 'a + RootKind + GCMethods> RootedGuard<'a, T> { @@ -378,24 +405,21 @@ impl<'a, T: 'a + RootKind + GCMethods> RootedGuard<'a, T> { unsafe { root.register_with_root_lists(cx); } - RootedGuard { - root: root - } + RootedGuard { root: root } } pub fn handle(&self) -> JS::Handle { - unsafe { - JS::Handle::from_marked_location(&self.root.ptr) - } + unsafe { JS::Handle::from_marked_location(&self.root.ptr) } } pub fn handle_mut(&mut self) -> JS::MutableHandle { - unsafe { - JS::MutableHandle::from_marked_location(&mut self.root.ptr) - } + unsafe { JS::MutableHandle::from_marked_location(&mut self.root.ptr) } } - pub fn get(&self) -> T where T: Copy { + pub fn get(&self) -> T + where + T: Copy, + { self.root.ptr } @@ -435,12 +459,13 @@ macro_rules! rooted { (in($cx:expr) let mut $name:ident = $init:expr) => { let mut __root = $crate::jsapi::JS::Rooted::new_unrooted(); let mut $name = $crate::rust::RootedGuard::new($cx, &mut __root, $init); - } + }; } impl JS::Handle { pub fn get(&self) -> T - where T: Copy + where + T: Copy, { unsafe { *self.ptr } } @@ -470,19 +495,19 @@ impl JS::MutableHandle { } pub fn handle(&self) -> JS::Handle { - unsafe { - JS::Handle::from_marked_location(self.ptr as *const _) - } + unsafe { JS::Handle::from_marked_location(self.ptr as *const _) } } pub fn get(&self) -> T - where T: Copy + where + T: Copy, { unsafe { *self.ptr } } pub fn set(&self, v: T) - where T: Copy + where + T: Copy, { unsafe { *self.ptr = v } } @@ -504,15 +529,11 @@ impl DerefMut for JS::MutableHandle { impl JS::HandleValue { pub fn null() -> JS::HandleValue { - unsafe { - JS::NullHandleValue - } + unsafe { JS::NullHandleValue } } pub fn undefined() -> JS::HandleValue { - unsafe { - JS::UndefinedHandleValue - } + unsafe { JS::UndefinedHandleValue } } } @@ -527,7 +548,7 @@ impl JS::HandleValueArray { pub unsafe fn from_rooted_slice(values: &[JS::Value]) -> JS::HandleValueArray { JS::HandleValueArray { length_: values.len(), - elements_: values.as_ptr() + elements_: values.as_ptr(), } } } @@ -536,9 +557,7 @@ const ConstNullValue: *mut JSObject = 0 as *mut JSObject; impl JS::HandleObject { pub fn null() -> JS::HandleObject { - unsafe { - JS::HandleObject::from_marked_location(&ConstNullValue) - } + unsafe { JS::HandleObject::from_marked_location(&ConstNullValue) } } } @@ -551,11 +570,15 @@ impl Default for jsid { } impl Default for JS::Value { - fn default() -> JS::Value { jsval::UndefinedValue() } + fn default() -> JS::Value { + jsval::UndefinedValue() + } } impl Default for JS::RealmOptions { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } pub trait GCMethods { @@ -564,55 +587,74 @@ pub trait GCMethods { } impl GCMethods for jsid { - unsafe fn initial() -> jsid { Default::default() } + unsafe fn initial() -> jsid { + Default::default() + } unsafe fn write_barriers(_: *mut jsid, _: jsid, _: jsid) {} } #[cfg(feature = "bigint")] impl GCMethods for *mut JS::BigInt { - unsafe fn initial() -> *mut JS::BigInt { ptr::null_mut() } - unsafe fn write_barriers(v: *mut *mut JS::BigInt, prev: *mut JS::BigInt, - next: *mut JS::BigInt) { + unsafe fn initial() -> *mut JS::BigInt { + ptr::null_mut() + } + unsafe fn write_barriers( + v: *mut *mut JS::BigInt, + prev: *mut JS::BigInt, + next: *mut JS::BigInt, + ) { JS::HeapBigIntWriteBarriers(v, prev, next); } } impl GCMethods for *mut JSObject { - unsafe fn initial() -> *mut JSObject { ptr::null_mut() } - unsafe fn write_barriers(v: *mut *mut JSObject, - prev: *mut JSObject, next: *mut JSObject) { + unsafe fn initial() -> *mut JSObject { + ptr::null_mut() + } + unsafe fn write_barriers(v: *mut *mut JSObject, prev: *mut JSObject, next: *mut JSObject) { JS::HeapObjectWriteBarriers(v, prev, next); } } impl GCMethods for *mut JSString { - unsafe fn initial() -> *mut JSString { ptr::null_mut() } - unsafe fn write_barriers(v: *mut *mut JSString, prev: *mut JSString, - next: *mut JSString) { + unsafe fn initial() -> *mut JSString { + ptr::null_mut() + } + unsafe fn write_barriers(v: *mut *mut JSString, prev: *mut JSString, next: *mut JSString) { JS::HeapStringWriteBarriers(v, prev, next); } } impl GCMethods for *mut JSScript { - unsafe fn initial() -> *mut JSScript { ptr::null_mut() } - unsafe fn write_barriers(v: *mut *mut JSScript, prev: *mut JSScript, - next: *mut JSScript) { + unsafe fn initial() -> *mut JSScript { + ptr::null_mut() + } + unsafe fn write_barriers(v: *mut *mut JSScript, prev: *mut JSScript, next: *mut JSScript) { JS::HeapScriptWriteBarriers(v, prev, next); } } impl GCMethods for *mut JSFunction { - unsafe fn initial() -> *mut JSFunction { ptr::null_mut() } - unsafe fn write_barriers(v: *mut *mut JSFunction, - prev: *mut JSFunction, next: *mut JSFunction) { - JS::HeapObjectWriteBarriers(mem::transmute(v), - mem::transmute(prev), - mem::transmute(next)); + unsafe fn initial() -> *mut JSFunction { + ptr::null_mut() + } + unsafe fn write_barriers( + v: *mut *mut JSFunction, + prev: *mut JSFunction, + next: *mut JSFunction, + ) { + JS::HeapObjectWriteBarriers( + mem::transmute(v), + mem::transmute(prev), + mem::transmute(next), + ); } } impl GCMethods for JS::Value { - unsafe fn initial() -> JS::Value { UndefinedValue() } + unsafe fn initial() -> JS::Value { + UndefinedValue() + } unsafe fn write_barriers(v: *mut JS::Value, prev: JS::Value, next: JS::Value) { JS::HeapValueWriteBarriers(v, &prev, &next); } @@ -623,7 +665,9 @@ impl GCMethods for JS::Value { impl Drop for JSAutoRealm { fn drop(&mut self) { - unsafe { JS::LeaveRealm(self.cx_, self.oldRealm_); } + unsafe { + JS::LeaveRealm(self.cx_, self.oldRealm_); + } } } @@ -642,24 +686,18 @@ impl JSJitMethodCallArgs { #[inline] pub fn index(&self, i: u32) -> JS::HandleValue { assert!(i < self._base.argc_); - unsafe { - JS::HandleValue::from_marked_location(self._base.argv_.offset(i as isize)) - } + unsafe { JS::HandleValue::from_marked_location(self._base.argv_.offset(i as isize)) } } #[inline] pub fn index_mut(&self, i: u32) -> JS::MutableHandleValue { assert!(i < self._base.argc_); - unsafe { - JS::MutableHandleValue::from_marked_location(self._base.argv_.offset(i as isize)) - } + unsafe { JS::MutableHandleValue::from_marked_location(self._base.argv_.offset(i as isize)) } } #[inline] pub fn rval(&self) -> JS::MutableHandleValue { - unsafe { - JS::MutableHandleValue::from_marked_location(self._base.argv_.offset(-2)) - } + unsafe { JS::MutableHandleValue::from_marked_location(self._base.argv_.offset(-2)) } } } @@ -674,17 +712,13 @@ impl JS::CallArgs { #[inline] pub fn index(&self, i: u32) -> JS::HandleValue { assert!(i < self._base.argc_); - unsafe { - JS::HandleValue::from_marked_location(self._base.argv_.offset(i as isize)) - } + unsafe { JS::HandleValue::from_marked_location(self._base.argv_.offset(i as isize)) } } #[inline] pub fn index_mut(&self, i: u32) -> JS::MutableHandleValue { assert!(i < self._base.argc_); - unsafe { - JS::MutableHandleValue::from_marked_location(self._base.argv_.offset(i as isize)) - } + unsafe { JS::MutableHandleValue::from_marked_location(self._base.argv_.offset(i as isize)) } } #[inline] @@ -700,23 +734,17 @@ impl JS::CallArgs { #[inline] pub fn rval(&self) -> JS::MutableHandleValue { - unsafe { - JS::MutableHandleValue::from_marked_location(self._base.argv_.offset(-2)) - } + unsafe { JS::MutableHandleValue::from_marked_location(self._base.argv_.offset(-2)) } } #[inline] pub fn thisv(&self) -> JS::HandleValue { - unsafe { - JS::HandleValue::from_marked_location(self._base.argv_.offset(-1)) - } + unsafe { JS::HandleValue::from_marked_location(self._base.argv_.offset(-1)) } } #[inline] pub fn calleev(&self) -> JS::HandleValue { - unsafe { - JS::HandleValue::from_marked_location(self._base.argv_.offset(-2)) - } + unsafe { JS::HandleValue::from_marked_location(self._base.argv_.offset(-2)) } } #[inline] @@ -729,7 +757,8 @@ impl JS::CallArgs { assert!(self._base.constructing_()); unsafe { JS::MutableHandleValue::from_marked_location( - self._base.argv_.offset(self._base.argc_ as isize)) + self._base.argv_.offset(self._base.argc_ as isize), + ) } } } @@ -753,22 +782,18 @@ impl JSJitSetterCallArgs { // Wrappers around things in jsglue.cpp pub struct RootedObjectVectorWrapper { - pub ptr: *mut JS::PersistentRootedObjectVector + pub ptr: *mut JS::PersistentRootedObjectVector, } impl RootedObjectVectorWrapper { pub fn new(cx: *mut JSContext) -> RootedObjectVectorWrapper { RootedObjectVectorWrapper { - ptr: unsafe { - CreateRootedObjectVector(cx) - } + ptr: unsafe { CreateRootedObjectVector(cx) }, } } pub fn append(&self, obj: *mut JSObject) -> bool { - unsafe { - AppendToRootedObjectVector(self.ptr, obj) - } + unsafe { AppendToRootedObjectVector(self.ptr, obj) } } } @@ -779,13 +804,17 @@ impl Drop for RootedObjectVectorWrapper { } pub struct CompileOptionsWrapper { - pub ptr: *mut JS::ReadOnlyCompileOptions + pub ptr: *mut JS::ReadOnlyCompileOptions, } impl CompileOptionsWrapper { - pub fn new(cx: *mut JSContext, file: *const ::libc::c_char, line: c_uint) -> CompileOptionsWrapper { + pub fn new( + cx: *mut JSContext, + file: *const ::libc::c_char, + line: c_uint, + ) -> CompileOptionsWrapper { CompileOptionsWrapper { - ptr: unsafe { NewCompileOptions(cx, file, line) } + ptr: unsafe { NewCompileOptions(cx, file, line) }, } } } @@ -846,9 +875,8 @@ pub unsafe fn ToNumber(cx: *mut JSContext, v: JS::HandleValue) -> Result( cx: *mut JSContext, v: JS::HandleValue, - conv_fn: unsafe extern "C" fn(*mut JSContext, JS::HandleValue, *mut T) -> bool) - -> Result { - + conv_fn: unsafe extern "C" fn(*mut JSContext, JS::HandleValue, *mut T) -> bool, +) -> Result { let val = *v.ptr; if val.is_int32() { let intval: i64 = val.to_int32() as i64; @@ -900,9 +928,12 @@ pub unsafe fn ToString(cx: *mut JSContext, v: JS::HandleValue) -> *mut JSString js::ToStringSlow(cx, v) } -pub unsafe extern fn report_warning(_cx: *mut JSContext, report: *mut JSErrorReport) { +pub unsafe extern "C" fn report_warning(_cx: *mut JSContext, report: *mut JSErrorReport) { fn latin1_to_string(bytes: &[u8]) -> String { - bytes.iter().map(|c| char::from_u32(*c as u32).unwrap()).collect() + bytes + .iter() + .map(|c| char::from_u32(*c as u32).unwrap()) + .collect() } let fnptr = (*report)._base.filename; @@ -917,7 +948,9 @@ pub unsafe extern fn report_warning(_cx: *mut JSContext, report: *mut JSErrorRep let column = (*report)._base.column; let msg_ptr = (*report)._base.message_.data_ as *const u16; - let msg_len = (0usize..).find(|&i| *msg_ptr.offset(i as isize) == 0).unwrap(); + let msg_len = (0usize..) + .find(|&i| *msg_ptr.offset(i as isize) == 0) + .unwrap(); let msg_slice = slice::from_raw_parts(msg_ptr, msg_len); let msg = String::from_utf16_lossy(msg_slice); @@ -932,30 +965,24 @@ impl JSNativeWrapper { } pub struct RootedIdVectorWrapper { - pub ptr: *mut JS::PersistentRootedIdVector + pub ptr: *mut JS::PersistentRootedIdVector, } impl RootedIdVectorWrapper { pub fn new(cx: *mut JSContext) -> RootedIdVectorWrapper { RootedIdVectorWrapper { - ptr: unsafe { - CreateRootedIdVector(cx) - } + ptr: unsafe { CreateRootedIdVector(cx) }, } } pub fn handle_mut(&self) -> JS::MutableHandleIdVector { - unsafe { - GetMutableHandleIdVector(self.ptr) - } + unsafe { GetMutableHandleIdVector(self.ptr) } } } impl Drop for RootedIdVectorWrapper { fn drop(&mut self) { - unsafe { - DestroyRootedIdVector(self.ptr) - } + unsafe { DestroyRootedIdVector(self.ptr) } } } @@ -986,15 +1013,26 @@ impl Deref for RootedIdVectorWrapper { /// /// - `cx` must be valid. /// - This function calls into unaudited C++ code. -pub unsafe fn define_methods(cx: *mut JSContext, obj: JS::HandleObject, - methods: &'static [JSFunctionSpec]) - -> Result<(), ()> { +pub unsafe fn define_methods( + cx: *mut JSContext, + obj: JS::HandleObject, + methods: &'static [JSFunctionSpec], +) -> Result<(), ()> { assert!({ match methods.last() { - Some(&JSFunctionSpec { name: JSFunctionSpec_Name { string_: name, }, call, nargs, flags, selfHostedName }) => { - name.is_null() && call.is_zeroed() && nargs == 0 && flags == 0 && - selfHostedName.is_null() - }, + Some(&JSFunctionSpec { + name: JSFunctionSpec_Name { string_: name }, + call, + nargs, + flags, + selfHostedName, + }) => { + name.is_null() + && call.is_zeroed() + && nargs == 0 + && flags == 0 + && selfHostedName.is_null() + } None => false, } }); @@ -1017,14 +1055,18 @@ pub unsafe fn define_methods(cx: *mut JSContext, obj: JS::HandleObject, /// /// - `cx` must be valid. /// - This function calls into unaudited C++ code. -pub unsafe fn define_properties(cx: *mut JSContext, obj: JS::HandleObject, - properties: &'static [JSPropertySpec]) - -> Result<(), ()> { +pub unsafe fn define_properties( + cx: *mut JSContext, + obj: JS::HandleObject, + properties: &'static [JSPropertySpec], +) -> Result<(), ()> { assert!(!properties.is_empty()); assert!({ let spec = properties.last().unwrap(); - let slice = slice::from_raw_parts(spec as *const _ as *const u8, - mem::size_of::()); + let slice = slice::from_raw_parts( + spec as *const _ as *const u8, + mem::size_of::(), + ); slice.iter().all(|byte| *byte == 0) }); @@ -1048,11 +1090,13 @@ static SIMPLE_GLOBAL_CLASS_OPS: JSClassOps = JSClassOps { /// This is a simple `JSClass` for global objects, primarily intended for tests. pub static SIMPLE_GLOBAL_CLASS: JSClass = JSClass { name: b"Global\0" as *const u8 as *const _, - flags: (JSCLASS_IS_GLOBAL | ((JSCLASS_GLOBAL_SLOT_COUNT & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT)) as u32, + flags: (JSCLASS_IS_GLOBAL + | ((JSCLASS_GLOBAL_SLOT_COUNT & JSCLASS_RESERVED_SLOTS_MASK) + << JSCLASS_RESERVED_SLOTS_SHIFT)) as u32, cOps: &SIMPLE_GLOBAL_CLASS_OPS as *const JSClassOps, spec: 0 as *mut _, ext: 0 as *mut _, - oOps: 0 as *mut _ + oOps: 0 as *mut _, }; #[inline] @@ -1116,9 +1160,7 @@ pub unsafe fn maybe_wrap_object_value(cx: *mut JSContext, rval: JS::MutableHandl } #[inline] -pub unsafe fn maybe_wrap_object_or_null_value( - cx: *mut JSContext, - rval: JS::MutableHandleValue) { +pub unsafe fn maybe_wrap_object_or_null_value(cx: *mut JSContext, rval: JS::MutableHandleValue) { assert!(rval.is_object_or_null()); if !rval.is_null() { maybe_wrap_object_value(cx, rval); @@ -1136,14 +1178,14 @@ pub unsafe fn maybe_wrap_value(cx: *mut JSContext, rval: JS::MutableHandleValue) /// Equivalents of the JS_FN* macros. impl JSFunctionSpec { - pub fn js_fs(name: *const ::std::os::raw::c_char, - func: JSNative, - nargs: u16, - flags: u16) -> JSFunctionSpec { + pub fn js_fs( + name: *const ::std::os::raw::c_char, + func: JSNative, + nargs: u16, + flags: u16, + ) -> JSFunctionSpec { JSFunctionSpec { - name: JSFunctionSpec_Name { - string_: name, - }, + name: JSFunctionSpec_Name { string_: name }, call: JSNativeWrapper { op: func, info: ptr::null(), @@ -1154,14 +1196,14 @@ impl JSFunctionSpec { } } - pub fn js_fn(name: *const ::std::os::raw::c_char, - func: JSNative, - nargs: u16, - flags: u16) -> JSFunctionSpec { + pub fn js_fn( + name: *const ::std::os::raw::c_char, + func: JSNative, + nargs: u16, + flags: u16, + ) -> JSFunctionSpec { JSFunctionSpec { - name: JSFunctionSpec_Name { - string_: name, - }, + name: JSFunctionSpec_Name { string_: name }, call: JSNativeWrapper { op: func, info: ptr::null(), @@ -1188,13 +1230,14 @@ impl JSFunctionSpec { /// Equivalents of the JS_PS* macros. impl JSPropertySpec { - pub fn getter(name: *const ::std::os::raw::c_char, flags: u8, func: JSNative) - -> JSPropertySpec { + pub fn getter( + name: *const ::std::os::raw::c_char, + flags: u8, + func: JSNative, + ) -> JSPropertySpec { debug_assert_eq!(flags & !(JSPROP_ENUMERATE | JSPROP_PERMANENT), 0); JSPropertySpec { - name: JSPropertySpec_Name { - string_: name, - }, + name: JSPropertySpec_Name { string_: name }, flags: flags, u: JSPropertySpec_AccessorsOrValue { accessors: JSPropertySpec_AccessorsOrValue_Accessors { @@ -1209,22 +1252,21 @@ impl JSPropertySpec { op: None, info: ptr::null(), }, - } - } - } + }, + }, + }, } } - pub fn getter_setter(name: *const ::std::os::raw::c_char, - flags: u8, - g_f: JSNative, - s_f: JSNative) - -> JSPropertySpec { + pub fn getter_setter( + name: *const ::std::os::raw::c_char, + flags: u8, + g_f: JSNative, + s_f: JSNative, + ) -> JSPropertySpec { debug_assert_eq!(flags & !(JSPROP_ENUMERATE | JSPROP_PERMANENT), 0); JSPropertySpec { - name: JSPropertySpec_Name { - string_: name, - }, + name: JSPropertySpec_Name { string_: name }, flags: flags, u: JSPropertySpec_AccessorsOrValue { accessors: JSPropertySpec_AccessorsOrValue_Accessors { @@ -1239,9 +1281,9 @@ impl JSPropertySpec { op: s_f, info: ptr::null(), }, - } - } - } + }, + }, + }, } } @@ -1250,7 +1292,7 @@ impl JSPropertySpec { string_: 0 as *const _, }, flags: 0, - u: JSPropertySpec_AccessorsOrValue{ + u: JSPropertySpec_AccessorsOrValue { accessors: JSPropertySpec_AccessorsOrValue_Accessors { getter: JSPropertySpec_Accessor { native: JSNativeWrapper { @@ -1263,8 +1305,8 @@ impl JSPropertySpec { op: None, info: 0 as *const _, }, - } - } - } + }, + }, + }, }; } diff --git a/js/rust/src/sc.rs b/js/rust/src/sc.rs index a6089583bbe0..590c87b42111 100644 --- a/js/rust/src/sc.rs +++ b/js/rust/src/sc.rs @@ -20,30 +20,23 @@ impl StructuredCloneBuffer { /// # Panics /// /// Panics if the underlying JSAPI calls fail. - pub fn new(scope: jsapi::JS::StructuredCloneScope, - callbacks: &jsapi::JSStructuredCloneCallbacks) - -> StructuredCloneBuffer { - let raw = unsafe { - glue::NewJSAutoStructuredCloneBuffer(scope, callbacks) - }; + pub fn new( + scope: jsapi::JS::StructuredCloneScope, + callbacks: &jsapi::JSStructuredCloneCallbacks, + ) -> StructuredCloneBuffer { + let raw = unsafe { glue::NewJSAutoStructuredCloneBuffer(scope, callbacks) }; assert!(!raw.is_null()); - StructuredCloneBuffer { - raw: raw, - } + StructuredCloneBuffer { raw: raw } } /// Get the raw `*mut JSStructuredCloneData` owned by this buffer. pub fn data(&self) -> *mut jsapi::JSStructuredCloneData { - unsafe { - &mut (*self.raw).data_ - } + unsafe { &mut (*self.raw).data_ } } /// Copy this buffer's data into a vec. pub fn copy_to_vec(&self) -> Vec { - let len = unsafe { - glue::GetLengthOfJSStructuredCloneData(self.data()) - }; + let len = unsafe { glue::GetLengthOfJSStructuredCloneData(self.data()) }; let mut vec = Vec::with_capacity(len); unsafe { glue::CopyJSStructuredCloneData(self.data(), vec.as_mut_ptr()); @@ -52,12 +45,22 @@ impl StructuredCloneBuffer { } /// Read a JS value out of this buffer. - pub fn read(&mut self, - vp: jsapi::JS::MutableHandleValue, - callbacks: &jsapi::JSStructuredCloneCallbacks) - -> Result<(), ()> { + pub fn read( + &mut self, + vp: jsapi::JS::MutableHandleValue, + callbacks: &jsapi::JSStructuredCloneCallbacks, + ) -> Result<(), ()> { if unsafe { - (*self.raw).read(Runtime::get(), vp, &jsapi::JS::CloneDataPolicy{ allowIntraClusterClonableSharedObjects_: false, allowSharedMemoryObjects_: false }, callbacks, ptr::null_mut()) + (*self.raw).read( + Runtime::get(), + vp, + &jsapi::JS::CloneDataPolicy { + allowIntraClusterClonableSharedObjects_: false, + allowSharedMemoryObjects_: false, + }, + callbacks, + ptr::null_mut(), + ) } { Ok(()) } else { @@ -66,13 +69,12 @@ impl StructuredCloneBuffer { } /// Write a JS value into this buffer. - pub fn write(&mut self, - v: jsapi::JS::HandleValue, - callbacks: &jsapi::JSStructuredCloneCallbacks) - -> Result<(), ()> { - if unsafe { - (*self.raw).write(Runtime::get(), v, callbacks, ptr::null_mut()) - } { + pub fn write( + &mut self, + v: jsapi::JS::HandleValue, + callbacks: &jsapi::JSStructuredCloneCallbacks, + ) -> Result<(), ()> { + if unsafe { (*self.raw).write(Runtime::get(), v, callbacks, ptr::null_mut()) } { Ok(()) } else { Err(()) @@ -83,9 +85,7 @@ impl StructuredCloneBuffer { pub fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), ()> { let len = bytes.len(); let src = bytes.as_ptr(); - if unsafe { - glue::WriteBytesToJSStructuredCloneData(src, len, self.data()) - } { + if unsafe { glue::WriteBytesToJSStructuredCloneData(src, len, self.data()) } { Ok(()) } else { Err(()) diff --git a/js/rust/src/typedarray.rs b/js/rust/src/typedarray.rs index 840a2308449d..aa3d535edeaf 100644 --- a/js/rust/src/typedarray.rs +++ b/js/rust/src/typedarray.rs @@ -15,9 +15,9 @@ use glue::GetUint16ArrayLengthAndData; use glue::GetUint32ArrayLengthAndData; use glue::GetUint8ArrayLengthAndData; use glue::GetUint8ClampedArrayLengthAndData; -use jsapi::*; use jsapi::js::*; use jsapi::JS::*; +use jsapi::*; use rust::RootedGuard; use std::ptr; use std::slice; @@ -37,10 +37,11 @@ impl<'a, T: TypedArrayElement> TypedArray<'a, T> { /// Create a typed array representation that wraps an existing JS reflector. /// This operation will fail if attempted on a JS object that does not match /// the expected typed array details. - pub fn from(cx: *mut JSContext, - root: &'a mut Rooted<*mut JSObject>, - object: *mut JSObject) - -> Result { + pub fn from( + cx: *mut JSContext, + root: &'a mut Rooted<*mut JSObject>, + object: *mut JSObject, + ) -> Result { if object.is_null() { return Err(()); } @@ -94,10 +95,11 @@ impl<'a, T: TypedArrayElement> TypedArray<'a, T> { impl<'a, T: TypedArrayElementCreator + TypedArrayElement> TypedArray<'a, T> { /// Create a new JS typed array, optionally providing initial data that will /// be copied into the newly-allocated buffer. Returns the new JS reflector. - pub unsafe fn create(cx: *mut JSContext, - with: CreateWith, - result: MutableHandleObject) - -> Result<(), ()> { + pub unsafe fn create( + cx: *mut JSContext, + with: CreateWith, + result: MutableHandleObject, + ) -> Result<(), ()> { let length = match with { CreateWith::Length(len) => len, CreateWith::Slice(slice) => slice.len() as u32, @@ -150,7 +152,7 @@ macro_rules! typed_array_element { ($t: ident, $element: ty, $unwrap: ident, - $length_and_data: ident) => ( + $length_and_data: ident) => { /// A kind of typed array. pub struct $t; @@ -169,14 +171,14 @@ macro_rules! typed_array_element { (data, len) } } - ); + }; ($t: ident, $element: ty, $unwrap: ident, $length_and_data: ident, $create_new: ident, - $get_data: ident) => ( + $get_data: ident) => { typed_array_element!($t, $element, $unwrap, $length_and_data); impl TypedArrayElementCreator for $t { @@ -191,73 +193,95 @@ macro_rules! typed_array_element { data } } - ); + }; } -typed_array_element!(Uint8, - u8, - UnwrapUint8Array, - GetUint8ArrayLengthAndData, - JS_NewUint8Array, - JS_GetUint8ArrayData); -typed_array_element!(Uint16, - u16, - UnwrapUint16Array, - GetUint16ArrayLengthAndData, - JS_NewUint16Array, - JS_GetUint16ArrayData); -typed_array_element!(Uint32, - u32, - UnwrapUint32Array, - GetUint32ArrayLengthAndData, - JS_NewUint32Array, - JS_GetUint32ArrayData); -typed_array_element!(Int8, - i8, - UnwrapInt8Array, - GetInt8ArrayLengthAndData, - JS_NewInt8Array, - JS_GetInt8ArrayData); -typed_array_element!(Int16, - i16, - UnwrapInt16Array, - GetInt16ArrayLengthAndData, - JS_NewInt16Array, - JS_GetInt16ArrayData); -typed_array_element!(Int32, - i32, - UnwrapInt32Array, - GetInt32ArrayLengthAndData, - JS_NewInt32Array, - JS_GetInt32ArrayData); -typed_array_element!(Float32, - f32, - UnwrapFloat32Array, - GetFloat32ArrayLengthAndData, - JS_NewFloat32Array, - JS_GetFloat32ArrayData); -typed_array_element!(Float64, - f64, - UnwrapFloat64Array, - GetFloat64ArrayLengthAndData, - JS_NewFloat64Array, - JS_GetFloat64ArrayData); -typed_array_element!(ClampedU8, - u8, - UnwrapUint8ClampedArray, - GetUint8ClampedArrayLengthAndData, - JS_NewUint8ClampedArray, - JS_GetUint8ClampedArrayData); -typed_array_element!(ArrayBufferU8, - u8, - UnwrapArrayBuffer, - GetArrayBufferLengthAndData, - NewArrayBuffer, - GetArrayBufferData); -typed_array_element!(ArrayBufferViewU8, - u8, - UnwrapArrayBufferView, - GetArrayBufferViewLengthAndData); +typed_array_element!( + Uint8, + u8, + UnwrapUint8Array, + GetUint8ArrayLengthAndData, + JS_NewUint8Array, + JS_GetUint8ArrayData +); +typed_array_element!( + Uint16, + u16, + UnwrapUint16Array, + GetUint16ArrayLengthAndData, + JS_NewUint16Array, + JS_GetUint16ArrayData +); +typed_array_element!( + Uint32, + u32, + UnwrapUint32Array, + GetUint32ArrayLengthAndData, + JS_NewUint32Array, + JS_GetUint32ArrayData +); +typed_array_element!( + Int8, + i8, + UnwrapInt8Array, + GetInt8ArrayLengthAndData, + JS_NewInt8Array, + JS_GetInt8ArrayData +); +typed_array_element!( + Int16, + i16, + UnwrapInt16Array, + GetInt16ArrayLengthAndData, + JS_NewInt16Array, + JS_GetInt16ArrayData +); +typed_array_element!( + Int32, + i32, + UnwrapInt32Array, + GetInt32ArrayLengthAndData, + JS_NewInt32Array, + JS_GetInt32ArrayData +); +typed_array_element!( + Float32, + f32, + UnwrapFloat32Array, + GetFloat32ArrayLengthAndData, + JS_NewFloat32Array, + JS_GetFloat32ArrayData +); +typed_array_element!( + Float64, + f64, + UnwrapFloat64Array, + GetFloat64ArrayLengthAndData, + JS_NewFloat64Array, + JS_GetFloat64ArrayData +); +typed_array_element!( + ClampedU8, + u8, + UnwrapUint8ClampedArray, + GetUint8ClampedArrayLengthAndData, + JS_NewUint8ClampedArray, + JS_GetUint8ClampedArrayData +); +typed_array_element!( + ArrayBufferU8, + u8, + UnwrapArrayBuffer, + GetArrayBufferLengthAndData, + NewArrayBuffer, + GetArrayBufferData +); +typed_array_element!( + ArrayBufferViewU8, + u8, + UnwrapArrayBufferView, + GetArrayBufferViewLengthAndData +); /// The Uint8ClampedArray type. pub type Uint8ClampedArray<'a> = TypedArray<'a, ClampedU8>; @@ -297,5 +321,5 @@ macro_rules! typedarray { (in($cx:expr) let mut $name:ident : $ty:ident = $init:expr) => { let mut __root = $crate::jsapi::JS::Rooted::new_unrooted(); let mut $name = $crate::typedarray::$ty::from($cx, &mut __root, $init); - } + }; } diff --git a/js/rust/tests/bigint.rs b/js/rust/tests/bigint.rs index 921931027fe4..3c8ef1ed2944 100644 --- a/js/rust/tests/bigint.rs +++ b/js/rust/tests/bigint.rs @@ -1,8 +1,8 @@ #[macro_use] extern crate js; -use js::jsapi::root::JS::CompartmentOptions; use js::jsapi::root::JS_NewGlobalObject; +use js::jsapi::root::JS::CompartmentOptions; use js::jsapi::root::JS::OnNewGlobalHookOption; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; @@ -22,8 +22,9 @@ fn is_bigint() { ); rooted!(in(cx) let mut rval = UndefinedValue()); - assert!(rt.evaluate_script(global.handle(), "BigInt(0)", - "test", 1, rval.handle_mut()).is_ok()); + assert!(rt + .evaluate_script(global.handle(), "BigInt(0)", "test", 1, rval.handle_mut()) + .is_ok()); assert!(rval.is_bigint()); } } @@ -41,8 +42,15 @@ fn is_not_bigint() { ); rooted!(in(cx) let mut rval = UndefinedValue()); - assert!(rt.evaluate_script(global.handle(), "'not a BigInt'", - "test", 1, rval.handle_mut()).is_ok()); + assert!(rt + .evaluate_script( + global.handle(), + "'not a BigInt'", + "test", + 1, + rval.handle_mut() + ) + .is_ok()); assert!(!rval.is_bigint()); } } diff --git a/js/rust/tests/callback.rs b/js/rust/tests/callback.rs index c059256ea96e..de75f97d26ea 100644 --- a/js/rust/tests/callback.rs +++ b/js/rust/tests/callback.rs @@ -8,13 +8,13 @@ extern crate libc; use js::ar::AutoRealm; use js::glue::JSEncodeStringToUTF8; -use js::jsapi::root::JS::CallArgs; -use js::jsapi::root::JS::RealmOptions; use js::jsapi::root::JSContext; use js::jsapi::root::JS_DefineFunction; use js::jsapi::root::JS_NewGlobalObject; use js::jsapi::root::JS_ReportErrorASCII; +use js::jsapi::root::JS::CallArgs; use js::jsapi::root::JS::OnNewGlobalHookOption; +use js::jsapi::root::JS::RealmOptions; use js::jsapi::root::JS::Value; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; @@ -31,12 +31,24 @@ fn callback() { let c_option = RealmOptions::default(); unsafe { - let global = JS_NewGlobalObject(context, &SIMPLE_GLOBAL_CLASS, ptr::null_mut(), h_option, &c_option); + let global = JS_NewGlobalObject( + context, + &SIMPLE_GLOBAL_CLASS, + ptr::null_mut(), + h_option, + &c_option, + ); rooted!(in(context) let global_root = global); let global = global_root.handle(); let _ar = AutoRealm::with_obj(context, global.get()); - let function = JS_DefineFunction(context, global, b"puts\0".as_ptr() as *const libc::c_char, - Some(puts), 1, 0); + let function = JS_DefineFunction( + context, + global, + b"puts\0".as_ptr() as *const libc::c_char, + Some(puts), + 1, + 0, + ); assert!(!function.is_null()); let javascript = "puts('Test Iñtërnâtiônàlizætiøn ┬─┬ノ( º _ ºノ) ');"; rooted!(in(context) let mut rval = UndefinedValue()); @@ -48,7 +60,10 @@ unsafe extern "C" fn puts(context: *mut JSContext, argc: u32, vp: *mut Value) -> let args = CallArgs::from_vp(vp, argc); if args._base.argc_ != 1 { - JS_ReportErrorASCII(context, b"puts() requires exactly 1 argument\0".as_ptr() as *const libc::c_char); + JS_ReportErrorASCII( + context, + b"puts() requires exactly 1 argument\0".as_ptr() as *const libc::c_char, + ); return false; } diff --git a/js/rust/tests/enumerate.rs b/js/rust/tests/enumerate.rs index 2bb993f73e90..a1c8a6735ddb 100644 --- a/js/rust/tests/enumerate.rs +++ b/js/rust/tests/enumerate.rs @@ -7,12 +7,12 @@ extern crate js; use js::glue::RUST_JSID_IS_STRING; use js::glue::RUST_JSID_TO_STRING; -use js::jsapi::root::JS::RealmOptions; use js::jsapi::root::js::GetPropertyKeys; -use js::jsapi::root::JSITER_OWNONLY; use js::jsapi::root::JS_NewGlobalObject; use js::jsapi::root::JS_StringEqualsAscii; use js::jsapi::root::JS::OnNewGlobalHookOption; +use js::jsapi::root::JS::RealmOptions; +use js::jsapi::root::JSITER_OWNONLY; use js::jsval::UndefinedValue; use js::rust::RootedIdVectorWrapper; use js::rust::Runtime; @@ -32,13 +32,25 @@ fn enumerate() { ); rooted!(in(cx) let mut rval = UndefinedValue()); - assert!(rt.evaluate_script(global.handle(), "({ 'a': 7 })", - "test", 1, rval.handle_mut()).is_ok()); + assert!(rt + .evaluate_script( + global.handle(), + "({ 'a': 7 })", + "test", + 1, + rval.handle_mut() + ) + .is_ok()); assert!(rval.is_object()); rooted!(in(cx) let object = rval.to_object()); let ids = RootedIdVectorWrapper::new(cx); - assert!(GetPropertyKeys(cx, object.handle(), JSITER_OWNONLY, ids.handle_mut())); + assert!(GetPropertyKeys( + cx, + object.handle(), + JSITER_OWNONLY, + ids.handle_mut() + )); assert_eq!(ids.len(), 1); rooted!(in(cx) let id = ids[0]); @@ -47,10 +59,12 @@ fn enumerate() { rooted!(in(cx) let id = RUST_JSID_TO_STRING(id.handle())); let mut matches = false; - assert!(JS_StringEqualsAscii(cx, - id.get(), - b"a\0" as *const _ as *const _, - &mut matches)); + assert!(JS_StringEqualsAscii( + cx, + id.get(), + b"a\0" as *const _ as *const _, + &mut matches + )); assert!(matches); } } diff --git a/js/rust/tests/evaluate.rs b/js/rust/tests/evaluate.rs index ae8de51beb0b..8ce4396adee5 100644 --- a/js/rust/tests/evaluate.rs +++ b/js/rust/tests/evaluate.rs @@ -5,9 +5,9 @@ #[macro_use] extern crate js; -use js::jsapi::root::JS::RealmOptions; use js::jsapi::root::JS_NewGlobalObject; use js::jsapi::root::JS::OnNewGlobalHookOption; +use js::jsapi::root::JS::RealmOptions; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; @@ -19,14 +19,14 @@ fn evaluate() { let cx = rt.cx(); unsafe { - rooted!(in(cx) let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS, ptr::null_mut(), OnNewGlobalHookOption::FireOnNewGlobalHook, &RealmOptions::default()) ); rooted!(in(cx) let mut rval = UndefinedValue()); - assert!(rt.evaluate_script(global.handle(), "1 + 1", - "test", 1, rval.handle_mut()).is_ok()); + assert!(rt + .evaluate_script(global.handle(), "1 + 1", "test", 1, rval.handle_mut()) + .is_ok()); } } diff --git a/js/rust/tests/panic.rs b/js/rust/tests/panic.rs index 0de0350f4a2d..ecb570501710 100644 --- a/js/rust/tests/panic.rs +++ b/js/rust/tests/panic.rs @@ -21,23 +21,30 @@ fn panic() { let c_option = JS::RealmOptions::default(); unsafe { - let global = JS_NewGlobalObject(context, &SIMPLE_GLOBAL_CLASS, - ptr::null_mut(), h_option, &c_option); + let global = JS_NewGlobalObject( + context, + &SIMPLE_GLOBAL_CLASS, + ptr::null_mut(), + h_option, + &c_option, + ); rooted!(in(context) let global_root = global); let global = global_root.handle(); let _ar = js::ar::AutoRealm::with_obj(context, global.get()); - let function = JS_DefineFunction(context, global, - b"test\0".as_ptr() as *const _, - Some(test), 0, 0); + let function = JS_DefineFunction( + context, + global, + b"test\0".as_ptr() as *const _, + Some(test), + 0, + 0, + ); assert!(!function.is_null()); rooted!(in(context) let mut rval = UndefinedValue()); - let _ = runtime.evaluate_script(global, "test();", "test.js", 0, - rval.handle_mut()); + let _ = runtime.evaluate_script(global, "test();", "test.js", 0, rval.handle_mut()); } } unsafe extern "C" fn test(_cx: *mut JSContext, _argc: u32, _vp: *mut JS::Value) -> bool { - wrap_panic(|| { - panic!() - }, false) + wrap_panic(|| panic!(), false) } diff --git a/js/rust/tests/rooting.rs b/js/rust/tests/rooting.rs index 81b46a18b5a9..b0ab0ed6f6de 100644 --- a/js/rust/tests/rooting.rs +++ b/js/rust/tests/rooting.rs @@ -11,7 +11,7 @@ extern crate lazy_static; extern crate libc; use js::jsapi::*; -use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS, define_methods}; +use js::rust::{define_methods, Runtime, SIMPLE_GLOBAL_CLASS}; use std::ptr; #[test] @@ -48,7 +48,10 @@ lazy_static! { name: JSFunctionSpec_Name { string_: b"addEventListener\0" as *const u8 as *const libc::c_char, }, - call: JSNativeWrapper { op: Some(generic_method), info: ptr::null() }, + call: JSNativeWrapper { + op: Some(generic_method), + info: ptr::null() + }, nargs: 2, flags: JSPROP_ENUMERATE as u16, selfHostedName: 0 as *const libc::c_char @@ -57,7 +60,10 @@ lazy_static! { name: JSFunctionSpec_Name { string_: b"removeEventListener\0" as *const u8 as *const libc::c_char, }, - call: JSNativeWrapper { op: Some(generic_method), info: ptr::null() }, + call: JSNativeWrapper { + op: Some(generic_method), + info: ptr::null() + }, nargs: 2, flags: JSPROP_ENUMERATE as u16, selfHostedName: 0 as *const libc::c_char @@ -66,7 +72,10 @@ lazy_static! { name: JSFunctionSpec_Name { string_: b"dispatchEvent\0" as *const u8 as *const libc::c_char, }, - call: JSNativeWrapper { op: Some(generic_method), info: ptr::null() }, + call: JSNativeWrapper { + op: Some(generic_method), + info: ptr::null() + }, nargs: 1, flags: JSPROP_ENUMERATE as u16, selfHostedName: 0 as *const libc::c_char @@ -75,7 +84,10 @@ lazy_static! { name: JSFunctionSpec_Name { string_: ptr::null(), }, - call: JSNativeWrapper { op: None, info: ptr::null() }, + call: JSNativeWrapper { + op: None, + info: ptr::null() + }, nargs: 0, flags: 0, selfHostedName: ptr::null() @@ -89,5 +101,5 @@ static CLASS: JSClass = JSClass { cOps: 0 as *const _, spec: 0 as *mut _, ext: 0 as *mut _, - oOps: 0 as *mut _ + oOps: 0 as *mut _, }; diff --git a/js/rust/tests/runtime.rs b/js/rust/tests/runtime.rs index c6a4cc85c538..ac69f5034bb0 100644 --- a/js/rust/tests/runtime.rs +++ b/js/rust/tests/runtime.rs @@ -31,7 +31,7 @@ fn runtime() { assert!(Runtime::new(false).is_err()); } -unsafe extern fn finalize(_fop: *mut JSFreeOp, _object: *mut JSObject) { +unsafe extern "C" fn finalize(_fop: *mut JSFreeOp, _object: *mut JSObject) { assert!(!Runtime::get().is_null()); } @@ -55,5 +55,5 @@ static CLASS: JSClass = JSClass { cOps: &CLASS_OPS as *const JSClassOps, spec: 0 as *mut _, ext: 0 as *mut _, - oOps: 0 as *mut _ + oOps: 0 as *mut _, }; diff --git a/js/rust/tests/stack_limit.rs b/js/rust/tests/stack_limit.rs index e0a0bf1d0f9f..02613d379344 100644 --- a/js/rust/tests/stack_limit.rs +++ b/js/rust/tests/stack_limit.rs @@ -5,9 +5,9 @@ #[macro_use] extern crate js; -use js::jsapi::root::JS::RealmOptions; use js::jsapi::root::JS_NewGlobalObject; use js::jsapi::root::JS::OnNewGlobalHookOption; +use js::jsapi::root::JS::RealmOptions; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; @@ -21,12 +21,24 @@ fn stack_limit() { unsafe { let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook; let c_option = RealmOptions::default(); - let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS, - ptr::null_mut(), h_option, &c_option); + let global = JS_NewGlobalObject( + cx, + &SIMPLE_GLOBAL_CLASS, + ptr::null_mut(), + h_option, + &c_option, + ); rooted!(in(cx) let global_root = global); let global = global_root.handle(); rooted!(in(cx) let mut rval = UndefinedValue()); - assert!(rt.evaluate_script(global, "function f() { f.apply() } f()", - "test", 1, rval.handle_mut()).is_err()); + assert!(rt + .evaluate_script( + global, + "function f() { f.apply() } f()", + "test", + 1, + rval.handle_mut() + ) + .is_err()); } } diff --git a/js/rust/tests/typedarray.rs b/js/rust/tests/typedarray.rs index fc253988093f..6cd759f5f3b6 100644 --- a/js/rust/tests/typedarray.rs +++ b/js/rust/tests/typedarray.rs @@ -27,8 +27,15 @@ fn typedarray() { let _ar = js::ar::AutoRealm::with_obj(cx, global.get()); rooted!(in(cx) let mut rval = UndefinedValue()); - assert!(rt.evaluate_script(global.handle(), "new Uint8Array([0, 2, 4])", - "test", 1, rval.handle_mut()).is_ok()); + assert!(rt + .evaluate_script( + global.handle(), + "new Uint8Array([0, 2, 4])", + "test", + 1, + rval.handle_mut() + ) + .is_ok()); assert!(rval.is_object()); typedarray!(in(cx) let array: Uint8Array = rval.to_object()); @@ -38,7 +45,10 @@ fn typedarray() { assert!(array.is_err()); typedarray!(in(cx) let view: ArrayBufferView = rval.to_object()); - assert_eq!(view.unwrap().get_array_type(), js::jsapi::js::Scalar::Type::Uint8); + assert_eq!( + view.unwrap().get_array_type(), + js::jsapi::js::Scalar::Type::Uint8 + ); rooted!(in(cx) let mut rval = ptr::null_mut()); assert!(Uint32Array::create(cx, CreateWith::Slice(&[1, 3, 5]), rval.handle_mut()).is_ok()); @@ -65,7 +75,10 @@ fn typedarray() { assert_eq!(array.unwrap().as_slice(), &[0, 1, 2, 3, 0]); typedarray!(in(cx) let view: ArrayBufferView = rval.get()); - assert_eq!(view.unwrap().get_array_type(), js::jsapi::js::Scalar::Type::Uint32); + assert_eq!( + view.unwrap().get_array_type(), + js::jsapi::js::Scalar::Type::Uint32 + ); } } diff --git a/js/rust/tests/value.rs b/js/rust/tests/value.rs index a844a52118c9..0622268cd81d 100644 --- a/js/rust/tests/value.rs +++ b/js/rust/tests/value.rs @@ -5,9 +5,9 @@ #[macro_use] extern crate js; -use js::jsapi::root::JS::RealmOptions; use js::jsapi::root::JS_NewGlobalObject; use js::jsapi::root::JS::OnNewGlobalHookOption; +use js::jsapi::root::JS::RealmOptions; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; @@ -25,8 +25,15 @@ fn is_symbol() { &RealmOptions::default()) ); rooted!(in(cx) let mut rval = UndefinedValue()); - assert!(rt.evaluate_script(global.handle(), "Symbol('test')", - "test", 1, rval.handle_mut()).is_ok()); + assert!(rt + .evaluate_script( + global.handle(), + "Symbol('test')", + "test", + 1, + rval.handle_mut() + ) + .is_ok()); assert!(rval.is_symbol()); } } @@ -43,8 +50,15 @@ fn is_not_symbol() { &RealmOptions::default()) ); rooted!(in(cx) let mut rval = UndefinedValue()); - assert!(rt.evaluate_script(global.handle(), "'not a symbol'", - "test", 1, rval.handle_mut()).is_ok()); + assert!(rt + .evaluate_script( + global.handle(), + "'not a symbol'", + "test", + 1, + rval.handle_mut() + ) + .is_ok()); assert!(!rval.is_symbol()); } } diff --git a/js/rust/tests/vec_conversion.rs b/js/rust/tests/vec_conversion.rs index 38826c213400..a4446799aaf3 100644 --- a/js/rust/tests/vec_conversion.rs +++ b/js/rust/tests/vec_conversion.rs @@ -10,21 +10,18 @@ use js::conversions::ConversionBehavior; use js::conversions::ConversionResult; use js::conversions::FromJSValConvertible; use js::conversions::ToJSValConvertible; -use js::jsapi::root::JS::RealmOptions; -use js::jsapi::root::JS::InitRealmStandardClasses; use js::jsapi::root::JS_NewGlobalObject; +use js::jsapi::root::JS::InitRealmStandardClasses; use js::jsapi::root::JS::OnNewGlobalHookOption; +use js::jsapi::root::JS::RealmOptions; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; use std::ptr; -fn assert_is_array(cx: *mut js::jsapi::root::JSContext, - val: js::jsapi::root::JS::HandleValue) { +fn assert_is_array(cx: *mut js::jsapi::root::JSContext, val: js::jsapi::root::JS::HandleValue) { let mut is_array = false; - assert!(unsafe { - js::jsapi::root::JS::IsArrayObject(cx, val, &mut is_array as *mut _) - }); + assert!(unsafe { js::jsapi::root::JS::IsArrayObject(cx, val, &mut is_array as *mut _) }); assert!(is_array); } @@ -37,8 +34,13 @@ fn vec_conversion() { let c_option = RealmOptions::default(); unsafe { - let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS, - ptr::null_mut(), h_option, &c_option); + let global = JS_NewGlobalObject( + cx, + &SIMPLE_GLOBAL_CLASS, + ptr::null_mut(), + h_option, + &c_option, + ); rooted!(in(cx) let global_root = global); let global = global_root.handle(); @@ -56,22 +58,21 @@ fn vec_conversion() { let orig_vec: Vec = vec![1, 2, 3]; orig_vec.to_jsval(cx, rval.handle_mut()); assert_is_array(cx, rval.handle()); - let converted = Vec::::from_jsval(cx, rval.handle(), - ConversionBehavior::Default).unwrap(); - - assert_eq!(&orig_vec, converted.get_success_value().unwrap()); - - rt.evaluate_script(global, "new Set([1, 2, 3])", - "test", 1, rval.handle_mut()).unwrap(); let converted = - Vec::::from_jsval(cx, rval.handle(), - ConversionBehavior::Default).unwrap(); + Vec::::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(&orig_vec, converted.get_success_value().unwrap()); - rt.evaluate_script(global, "({})", "test", 1, rval.handle_mut()).unwrap(); - let converted = Vec::::from_jsval(cx, rval.handle(), - ConversionBehavior::Default); + rt.evaluate_script(global, "new Set([1, 2, 3])", "test", 1, rval.handle_mut()) + .unwrap(); + let converted = + Vec::::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); + + assert_eq!(&orig_vec, converted.get_success_value().unwrap()); + + rt.evaluate_script(global, "({})", "test", 1, rval.handle_mut()) + .unwrap(); + let converted = Vec::::from_jsval(cx, rval.handle(), ConversionBehavior::Default); assert!(match converted { Ok(ConversionResult::Failure(_)) => true, _ => false, diff --git a/js/src/build.rs b/js/src/build.rs index cf3706714428..9152f3f1a78a 100644 --- a/js/src/build.rs +++ b/js/src/build.rs @@ -2,8 +2,8 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. -extern crate num_cpus; extern crate glob; +extern crate num_cpus; use std::env; use std::path; @@ -34,28 +34,29 @@ fn main() { let python = env::var("PYTHON3").unwrap_or("python3".into()); let mut cmd = Command::new(&python); - cmd.args(&["./devtools/automation/autospider.py", - // Only build SpiderMonkey, don't run all the tests. - "--build-only", - // Disable Mozilla's jemalloc; Rust has its own jemalloc that we - // can swap in instead and everything using a single malloc is - // good. - "--no-jemalloc", - // Don't try to clobber the output directory. Without - // this option, the build will fail because the directory - // already exists but wasn't created by autospider. - "--dep", - "--objdir", &out_dir, - &variant]) - .env("NO_RUST_PANIC_HOOK", "1") - .env("SOURCE", &js_src) - .env("PWD", &js_src) - .stdout(Stdio::inherit()) - .stderr(Stdio::inherit()); + cmd.args(&[ + "./devtools/automation/autospider.py", + // Only build SpiderMonkey, don't run all the tests. + "--build-only", + // Disable Mozilla's jemalloc; Rust has its own jemalloc that we + // can swap in instead and everything using a single malloc is + // good. + "--no-jemalloc", + // Don't try to clobber the output directory. Without + // this option, the build will fail because the directory + // already exists but wasn't created by autospider. + "--dep", + "--objdir", + &out_dir, + &variant, + ]) + .env("NO_RUST_PANIC_HOOK", "1") + .env("SOURCE", &js_src) + .env("PWD", &js_src) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()); println!("Running command: {:?}", cmd); - let result = cmd - .status() - .expect("Should spawn autospider OK"); + let result = cmd.status().expect("Should spawn autospider OK"); assert!(result.success(), "autospider should exit OK"); println!("cargo:rustc-link-search=native={}/js/src/build", out_dir); @@ -82,8 +83,7 @@ fn main() { /// Find if Spidermonkey built the Spidermonkey Rust library, and add it to the /// link if it was the case. fn maybe_add_spidermonkey_rust_lib() { - let out_dir = env::var("OUT_DIR") - .expect("cargo should invoke us with the OUT_DIR env var set"); + let out_dir = env::var("OUT_DIR").expect("cargo should invoke us with the OUT_DIR env var set"); let mut target_build_dir = path::PathBuf::from(out_dir); target_build_dir.push("../../"); @@ -91,17 +91,19 @@ fn maybe_add_spidermonkey_rust_lib() { let mut build_dir = target_build_dir.display().to_string(); build_dir.push_str("mozjs_sys-*/out/*/debug"); - let entries = match glob::glob(&build_dir){ - Err(_) => { return; } - Ok(entries) => entries + let entries = match glob::glob(&build_dir) { + Err(_) => { + return; + } + Ok(entries) => entries, }; for entry in entries { if let Ok(path) = entry { - let path = path.canonicalize() + let path = path + .canonicalize() .expect("Should canonicalize debug build path"); - let path = path.to_str() - .expect("Should be utf8"); + let path = path.to_str().expect("Should be utf8"); println!("cargo:rustc-link-search=native={}", path); println!("cargo:rustc-link-lib=static=jsrust"); return; diff --git a/js/src/frontend/binast/src/main.rs b/js/src/frontend/binast/src/main.rs index 94f8c18549ff..40f0c84a2666 100644 --- a/js/src/frontend/binast/src/main.rs +++ b/js/src/frontend/binast/src/main.rs @@ -7,25 +7,26 @@ extern crate clap; extern crate env_logger; extern crate inflector; extern crate itertools; -#[macro_use] extern crate log; +#[macro_use] +extern crate log; extern crate yaml_rust; -use binjs_meta::export::{ ToWebidl, TypeDeanonymizer, TypeName }; +use binjs_meta::export::{ToWebidl, TypeDeanonymizer, TypeName}; use binjs_meta::import::Importer; use binjs_meta::spec::*; -use binjs_meta::util:: { Reindentable, ToCases, ToStr }; +use binjs_meta::util::{Reindentable, ToCases, ToStr}; mod refgraph; -use refgraph::{ ReferenceGraph }; +use refgraph::ReferenceGraph; use std::borrow::Cow; -use std::collections::{ HashMap, HashSet }; +use std::collections::{HashMap, HashSet}; use std::fs::*; -use std::io::{ Read, Write }; +use std::io::{Read, Write}; use std::rc::Rc; -use clap::{ App, Arg }; +use clap::{App, Arg}; use itertools::Itertools; @@ -77,7 +78,6 @@ struct SumRules { disabled: bool, } - /// Rules for generating the code for parsing a full node /// of a node. /// @@ -191,8 +191,7 @@ struct GlobalRules { } impl GlobalRules { fn new(syntax: &Spec, yaml: &yaml_rust::yaml::Yaml) -> Self { - let rules = yaml.as_hash() - .expect("Rules are not a dictionary"); + let rules = yaml.as_hash().expect("Rules are not a dictionary"); let mut parser_class_name = None; let mut parser_class_template = None; @@ -213,7 +212,8 @@ impl GlobalRules { let mut per_node = HashMap::new(); for (node_key, node_entries) in rules.iter() { - let node_key = node_key.as_str() + let node_key = node_key + .as_str() .expect("Could not convert node_key to string"); match node_key { @@ -250,148 +250,283 @@ impl GlobalRules { .unwrap_or_else(|_| panic!("Rule hpp.tokens.header must be a string")); update_rule(&mut hpp_tokens_footer, &node_entries["tokens"]["footer"]) .unwrap_or_else(|_| panic!("Rule hpp.tokens.footer must be a string")); - update_rule(&mut hpp_tokens_kind_doc, &node_entries["tokens"]["kind"]["doc"]) - .unwrap_or_else(|_| panic!("Rule hpp.tokens.kind.doc must be a string")); - update_rule(&mut hpp_tokens_field_doc, &node_entries["tokens"]["field"]["doc"]) - .unwrap_or_else(|_| panic!("Rule hpp.tokens.field.doc must be a string")); - update_rule(&mut hpp_tokens_variants_doc, &node_entries["tokens"]["variants"]["doc"]) - .unwrap_or_else(|_| panic!("Rule hpp.tokens.variants.doc must be a string")); + update_rule( + &mut hpp_tokens_kind_doc, + &node_entries["tokens"]["kind"]["doc"], + ) + .unwrap_or_else(|_| panic!("Rule hpp.tokens.kind.doc must be a string")); + update_rule( + &mut hpp_tokens_field_doc, + &node_entries["tokens"]["field"]["doc"], + ) + .unwrap_or_else(|_| panic!("Rule hpp.tokens.field.doc must be a string")); + update_rule( + &mut hpp_tokens_variants_doc, + &node_entries["tokens"]["variants"]["doc"], + ) + .unwrap_or_else(|_| panic!("Rule hpp.tokens.variants.doc must be a string")); continue; } _ => {} } - - let node_name = syntax.get_node_name(&node_key) + let node_name = syntax + .get_node_name(&node_key) .unwrap_or_else(|| panic!("Unknown node name {}", node_key)); - let hash = node_entries.as_hash() + let hash = node_entries + .as_hash() .unwrap_or_else(|| panic!("Node {} isn't a dictionary")); let mut node_rule = NodeRules::default(); for (node_item_key, node_item_entry) in hash { - let as_string = node_item_key.as_str() + let as_string = node_item_key + .as_str() .unwrap_or_else(|| panic!("Keys for rule {} must be strings", node_key)); match as_string { "inherits" => { - let name = node_item_entry.as_str() - .unwrap_or_else(|| panic!("Rule {}.{} must be a string", node_key, as_string)); - let inherits = syntax.get_node_name(name) + let name = node_item_entry.as_str().unwrap_or_else(|| { + panic!("Rule {}.{} must be a string", node_key, as_string) + }); + let inherits = syntax + .get_node_name(name) .unwrap_or_else(|| panic!("Unknown node name {}", name)); node_rule.inherits = Some(inherits).cloned(); } "extra-params" => { update_rule_rc(&mut node_rule.extra_params, node_item_entry) - .unwrap_or_else(|()| panic!("Rule {}.{} must be a string", node_key, as_string)); + .unwrap_or_else(|()| { + panic!("Rule {}.{} must be a string", node_key, as_string) + }); } "extra-args" => { - update_rule_rc(&mut node_rule.extra_args, node_item_entry) - .unwrap_or_else(|()| panic!("Rule {}.{} must be a string", node_key, as_string)); + update_rule_rc(&mut node_rule.extra_args, node_item_entry).unwrap_or_else( + |()| panic!("Rule {}.{} must be a string", node_key, as_string), + ); } "some" => { update_rule_rc(&mut node_rule.some_before, &node_item_entry["before"]) - .unwrap_or_else(|()| panic!("Rule {}.{}.before must be a string", node_key, as_string)); + .unwrap_or_else(|()| { + panic!("Rule {}.{}.before must be a string", node_key, as_string) + }); update_rule_rc(&mut node_rule.some_after, &node_item_entry["after"]) - .unwrap_or_else(|()| panic!("Rule {}.{}.after must be a string", node_key, as_string)); + .unwrap_or_else(|()| { + panic!("Rule {}.{}.after must be a string", node_key, as_string) + }); } "none" => { update_rule_rc(&mut node_rule.none_replace, &node_item_entry["replace"]) - .unwrap_or_else(|()| panic!("Rule {}.{}.replace must be a string", node_key, as_string)); + .unwrap_or_else(|()| { + panic!("Rule {}.{}.replace must be a string", node_key, as_string) + }); } "init" => { - update_rule(&mut node_rule.init, node_item_entry) - .unwrap_or_else(|()| panic!("Rule {}.{} must be a string", node_key, as_string)); + update_rule(&mut node_rule.init, node_item_entry).unwrap_or_else(|()| { + panic!("Rule {}.{} must be a string", node_key, as_string) + }); } "build" => { - update_rule(&mut node_rule.build_result, node_item_entry) - .unwrap_or_else(|()| panic!("Rule {}.{} must be a string", node_key, as_string)); + update_rule(&mut node_rule.build_result, node_item_entry).unwrap_or_else( + |()| panic!("Rule {}.{} must be a string", node_key, as_string), + ); } "append" => { - update_rule(&mut node_rule.append, node_item_entry) - .unwrap_or_else(|()| panic!("Rule {}.{} must be a string", node_key, as_string)); + update_rule(&mut node_rule.append, node_item_entry).unwrap_or_else(|()| { + panic!("Rule {}.{} must be a string", node_key, as_string) + }); } "type-ok" => { - update_rule_rc(&mut node_rule.type_ok, node_item_entry) - .unwrap_or_else(|()| panic!("Rule {}.{} must be a string", node_key, as_string)); + update_rule_rc(&mut node_rule.type_ok, node_item_entry).unwrap_or_else( + |()| panic!("Rule {}.{} must be a string", node_key, as_string), + ); } "default-value" => { update_rule_rc(&mut node_rule.default_value, node_item_entry) - .unwrap_or_else(|()| panic!("Rule {}.{} must be a string", node_key, as_string)); + .unwrap_or_else(|()| { + panic!("Rule {}.{} must be a string", node_key, as_string) + }); } "fields" => { - let fields = node_item_entry.as_hash() - .unwrap_or_else(|| panic!("Rule {}.fields must be a hash, got {:?}", node_key, node_entries["fields"])); + let fields = node_item_entry.as_hash().unwrap_or_else(|| { + panic!( + "Rule {}.fields must be a hash, got {:?}", + node_key, node_entries["fields"] + ) + }); for (field_key, field_entry) in fields { - let field_key = field_key.as_str() - .unwrap_or_else(|| panic!("In rule {}, field entries must be field names", - node_key)) + let field_key = field_key + .as_str() + .unwrap_or_else(|| { + panic!( + "In rule {}, field entries must be field names", + node_key + ) + }) .to_string(); - let field_name = syntax.get_field_name(&field_key) - .unwrap_or_else(|| panic!("In rule {}, can't find field {}", - node_key, - field_key)); + let field_name = + syntax.get_field_name(&field_key).unwrap_or_else(|| { + panic!("In rule {}, can't find field {}", node_key, field_key) + }); let mut field_rule = FieldRules::default(); - for (field_config_key, field_config_entry) in field_entry.as_hash() - .unwrap_or_else(|| panic!("Rule {}.fields.{} must be a hash", node_key, field_key)) + for (field_config_key, field_config_entry) in + field_entry.as_hash().unwrap_or_else(|| { + panic!("Rule {}.fields.{} must be a hash", node_key, field_key) + }) { - let field_config_key = field_config_key.as_str() + let field_config_key = field_config_key + .as_str() .expect("Expected a string as a key"); - match field_config_key - { + match field_config_key { "block" => { - update_rule(&mut field_rule.declare, &field_config_entry["declare"]) - .unwrap_or_else(|()| panic!("Rule {}.fields.{}.{}.{} must be a string", node_key, field_key, field_config_key, "declare")); + update_rule( + &mut field_rule.declare, + &field_config_entry["declare"], + ) + .unwrap_or_else( + |()| { + panic!( + "Rule {}.fields.{}.{}.{} must be a string", + node_key, + field_key, + field_config_key, + "declare" + ) + }, + ); - update_rule(&mut field_rule.replace, &field_config_entry["replace"]) - .unwrap_or_else(|()| panic!("Rule {}.fields.{}.{}.{} must be a string", node_key, field_key, field_config_key, "replace")); + update_rule( + &mut field_rule.replace, + &field_config_entry["replace"], + ) + .unwrap_or_else( + |()| { + panic!( + "Rule {}.fields.{}.{}.{} must be a string", + node_key, + field_key, + field_config_key, + "replace" + ) + }, + ); - update_rule(&mut field_rule.block_before_field, &field_config_entry["before"]) - .unwrap_or_else(|()| panic!("Rule {}.fields.{}.{}.{} must be a string", node_key, field_key, field_config_key, "before")); + update_rule( + &mut field_rule.block_before_field, + &field_config_entry["before"], + ) + .unwrap_or_else( + |()| { + panic!( + "Rule {}.fields.{}.{}.{} must be a string", + node_key, field_key, field_config_key, "before" + ) + }, + ); - update_rule(&mut field_rule.block_after_field, &field_config_entry["after"]) - .unwrap_or_else(|()| panic!("Rule {}.fields.{}.{}.{} must be a string", node_key, field_key, field_config_key, "after")); + update_rule( + &mut field_rule.block_after_field, + &field_config_entry["after"], + ) + .unwrap_or_else( + |()| { + panic!( + "Rule {}.fields.{}.{}.{} must be a string", + node_key, field_key, field_config_key, "after" + ) + }, + ); } "before" => { - update_rule(&mut field_rule.before_field, &field_config_entry) - .unwrap_or_else(|()| panic!("Rule {}.fields.{}.{} must be a string", node_key, field_key, field_config_key)); + update_rule( + &mut field_rule.before_field, + &field_config_entry, + ) + .unwrap_or_else( + |()| { + panic!( + "Rule {}.fields.{}.{} must be a string", + node_key, field_key, field_config_key + ) + }, + ); } "after" => { - update_rule(&mut field_rule.after_field, &field_config_entry) - .unwrap_or_else(|()| panic!("Rule {}.fields.{}.{} must be a string", node_key, field_key, field_config_key)); + update_rule( + &mut field_rule.after_field, + &field_config_entry, + ) + .unwrap_or_else( + |()| { + panic!( + "Rule {}.fields.{}.{} must be a string", + node_key, field_key, field_config_key + ) + }, + ); } "extra-args" => { - update_rule_rc(&mut field_rule.extra_args, &field_config_entry) - .unwrap_or_else(|()| panic!("Rule {}.fields.{}.{} must be a string", node_key, field_key, field_config_key)); - } - _ => { - panic!("Unexpected {}.fields.{}.{}", node_key, field_key, field_config_key) + update_rule_rc( + &mut field_rule.extra_args, + &field_config_entry, + ) + .unwrap_or_else( + |()| { + panic!( + "Rule {}.fields.{}.{} must be a string", + node_key, field_key, field_config_key + ) + }, + ); } + _ => panic!( + "Unexpected {}.fields.{}.{}", + node_key, field_key, field_config_key + ), } } node_rule.by_field.insert(field_name.clone(), field_rule); } } "sum-arms" => { - let arms = node_item_entry.as_hash() - .unwrap_or_else(|| panic!("Rule {}.sum-arms must be a hash, got {:?}", node_key, node_entries["sum-arms"])); + let arms = node_item_entry.as_hash().unwrap_or_else(|| { + panic!( + "Rule {}.sum-arms must be a hash, got {:?}", + node_key, node_entries["sum-arms"] + ) + }); for (sum_arm_key, sum_arm_entry) in arms { - let sum_arm_key = sum_arm_key.as_str() - .unwrap_or_else(|| panic!("In rule {}, sum arms must be interface names")); - let sum_arm_name = syntax.get_node_name(&sum_arm_key) - .unwrap_or_else(|| panic!("In rule {}. cannot find interface {}", node_key, sum_arm_key)); + let sum_arm_key = sum_arm_key.as_str().unwrap_or_else(|| { + panic!("In rule {}, sum arms must be interface names") + }); + let sum_arm_name = + syntax.get_node_name(&sum_arm_key).unwrap_or_else(|| { + panic!( + "In rule {}. cannot find interface {}", + node_key, sum_arm_key + ) + }); let mut sum_rule = SumRules::default(); - for (arm_config_key, arm_config_entry) in sum_arm_entry.as_hash() - .unwrap_or_else(|| panic!("Rule {}.sum-arms.{} must be a hash", node_key, sum_arm_key)) + for (arm_config_key, arm_config_entry) in + sum_arm_entry.as_hash().unwrap_or_else(|| { + panic!( + "Rule {}.sum-arms.{} must be a hash", + node_key, sum_arm_key + ) + }) { - let arm_config_key = arm_config_key.as_str() - .expect("Expected a string as a key"); - match arm_config_key - { + let arm_config_key = + arm_config_key.as_str().expect("Expected a string as a key"); + match arm_config_key { "after" => { update_rule(&mut sum_rule.after_arm, arm_config_entry) - .unwrap_or_else(|()| panic!("Rule {}.sum-arms.{}.{} must be a string", node_key, sum_arm_key, arm_config_key)); + .unwrap_or_else(|()| { + panic!( + "Rule {}.sum-arms.{}.{} must be a string", + node_key, sum_arm_key, arm_config_key + ) + }); } "disabled" => { if let Some(disabled) = arm_config_entry.as_bool() { @@ -399,18 +534,24 @@ impl GlobalRules { sum_rule.disabled = true; } } else { - panic!("Rule {}.sum-arms.{}.{} must be a bool", node_key, sum_arm_key, arm_config_key); + panic!( + "Rule {}.sum-arms.{}.{} must be a bool", + node_key, sum_arm_key, arm_config_key + ); } } _ => { - panic!("Unexpected {}.sum-arms.{}.{}", node_key, sum_arm_key, arm_config_key); + panic!( + "Unexpected {}.sum-arms.{}.{}", + node_key, sum_arm_key, arm_config_key + ); } } } node_rule.by_sum.insert(sum_arm_name.clone(), sum_rule); } } - _ => panic!("Unexpected node_item_key {}.{}", node_key, as_string) + _ => panic!("Unexpected node_item_key {}.{}", node_key, as_string), } } @@ -418,15 +559,13 @@ impl GlobalRules { } Self { - parser_class_name: parser_class_name - .expect("parser.class-name should be specified"), + parser_class_name: parser_class_name.expect("parser.class-name should be specified"), parser_class_template: Rc::new(if parser_class_template.is_some() { format!("{} ", parser_class_template.unwrap()) } else { "".to_string() }), - parser_type_ok: parser_type_ok - .expect("parser.type-ok should be specified"), + parser_type_ok: parser_type_ok.expect("parser.type-ok should be specified"), parser_default_value: parser_default_value .expect("parser.default-value should be specified"), parser_list_append, @@ -445,9 +584,7 @@ impl GlobalRules { } } fn get(&self, name: &NodeName) -> NodeRules { - let mut rules = self.per_node.get(name) - .cloned() - .unwrap_or_default(); + let mut rules = self.per_node.get(name).cloned().unwrap_or_default(); if let Some(ref parent) = rules.inherits { let NodeRules { inherits: _, @@ -495,12 +632,10 @@ impl GlobalRules { rules.build_result = build_result; } for (key, value) in by_field { - rules.by_field.entry(key) - .or_insert(value); + rules.by_field.entry(key).or_insert(value); } for (key, value) in by_sum { - rules.by_sum.entry(key) - .or_insert(value); + rules.by_sum.entry(key).or_insert(value); } } rules @@ -547,24 +682,19 @@ enum MethodCallKind { } /// Fixed parameter of interface method. -const INTERFACE_PARAMS: &str = - "const size_t start"; +const INTERFACE_PARAMS: &str = "const size_t start"; /// Fixed arguments of interface method. -const INTERFACE_ARGS: &str = - "start"; +const INTERFACE_ARGS: &str = "start"; /// Fixed parameter of sum interface method. -const SUM_INTERFACE_PARAMS: &str = - "const size_t start, const BinASTKind kind"; +const SUM_INTERFACE_PARAMS: &str = "const size_t start, const BinASTKind kind"; /// Fixed arguments of sum interface method. -const SUM_INTERFACE_ARGS: &str = - "start, kind"; +const SUM_INTERFACE_ARGS: &str = "start, kind"; /// The name of the toplevel interface for the script. -const TOPLEVEL_INTERFACE: &str = - "Program"; +const TOPLEVEL_INTERFACE: &str = "Program"; /// In which context an interface appears. #[derive(Clone, Debug, PartialEq)] @@ -691,8 +821,14 @@ impl CPPExporter { for (parser_node_name, typedef) in syntax.typedefs_by_name() { if typedef.is_optional() { let content_name = TypeName::type_spec(typedef.spec()); - let content_node_name = syntax.get_node_name(&content_name) - .unwrap_or_else(|| panic!("While generating an option parser, could not find node name \"{}\"", content_name)) + let content_node_name = syntax + .get_node_name(&content_name) + .unwrap_or_else(|| { + panic!( + "While generating an option parser, could not find node name \"{}\"", + content_name + ) + }) .clone(); debug!(target: "generate_spidermonkey", "CPPExporter::new adding optional typedef {:?} => {:?} => {:?}", parser_node_name, @@ -700,13 +836,23 @@ impl CPPExporter { content_node_name); option_parsers_to_generate.push(OptionParserData { name: parser_node_name.clone(), - elements: content_node_name + elements: content_node_name, }); - } else if let TypeSpec::Array { ref contents, ref supports_empty } = *typedef.spec() { + } else if let TypeSpec::Array { + ref contents, + ref supports_empty, + } = *typedef.spec() + { use std::collections::hash_map::Entry::*; let content_name = TypeName::type_(&**contents); - let content_node_name = syntax.get_node_name(&content_name) - .unwrap_or_else(|| panic!("While generating an array parser, could not find node name {}", content_name)) + let content_node_name = syntax + .get_node_name(&content_name) + .unwrap_or_else(|| { + panic!( + "While generating an array parser, could not find node name {}", + content_name + ) + }) .clone(); debug!(target: "generate_spidermonkey", "CPPExporter::new adding list typedef {:?} => {:?} => {:?}", parser_node_name, @@ -715,7 +861,7 @@ impl CPPExporter { let data = ListParserData { name: parser_node_name.clone(), supports_empty: *supports_empty, - elements: content_node_name + elements: content_node_name, }; match canonical_list_parsers.entry(data.elements.clone()) { @@ -747,28 +893,35 @@ impl CPPExporter { // string enums that contain each symbol and come up with a unique name // (note that there is no guarantee of unicity – if collisions show up, // we may need to tweak the name generation algorithm). - let mut enum_by_string : HashMap> = HashMap::new(); - let mut enum_types : HashMap> = HashMap::new(); + let mut enum_by_string: HashMap> = HashMap::new(); + let mut enum_types: HashMap> = HashMap::new(); for (name, enum_) in syntax.string_enums_by_name().iter() { - let type_ = format!("typename {parser_class_name}::{kind}", - parser_class_name = rules.parser_class_name, - kind = name.to_class_cases()); + let type_ = format!( + "typename {parser_class_name}::{kind}", + parser_class_name = rules.parser_class_name, + kind = name.to_class_cases() + ); enum_types.insert(name.clone(), Rc::new(type_)); for string in enum_.strings().iter() { - let vec = enum_by_string.entry(string.clone()) + let vec = enum_by_string + .entry(string.clone()) .or_insert_with(|| vec![]); vec.push(name.clone()); } } - let variants_by_symbol = enum_by_string.drain() + let variants_by_symbol = enum_by_string + .drain() .map(|(string, names)| { - let expanded = format!("{names}{symbol}", - names = names.iter() + let expanded = format!( + "{names}{symbol}", + names = names + .iter() .map(NodeName::to_str) .sorted() .into_iter() .format("Or"), - symbol = string.to_cpp_enum_case()); + symbol = string.to_cpp_enum_case() + ); (string, expanded) }) .collect(); @@ -798,16 +951,24 @@ impl CPPExporter { if let Some(NamedType::Typedef(ref typedef)) = self.syntax.get_type_by_name(name) { assert!(typedef.is_optional()); if let TypeSpec::NamedType(ref named) = *typedef.spec() { - self.syntax.get_type_by_name(named) - .unwrap_or_else(|| panic!("Internal error: Could not find type {}, which should have been generated.", named.to_str())) + self.syntax.get_type_by_name(named).unwrap_or_else(|| { + panic!( + "Internal error: Could not find type {}, which should have been generated.", + named.to_str() + ) + }) } else { - panic!("Internal error: In {}, type {:?} should have been a named type", - name.to_str(), - typedef); + panic!( + "Internal error: In {}, type {:?} should have been a named type", + name.to_str(), + typedef + ); } } else { - panic!("Internal error: In {}, there should be a type with that name", - name.to_str()); + panic!( + "Internal error: In {}, there should be a type with that name", + name.to_str() + ); } } @@ -829,7 +990,9 @@ impl CPPExporter { let mut sum_edges: HashSet> = HashSet::new(); for node in nodes { - let rule_for_this_arm = rules_for_this_sum.by_sum.get(&node) + let rule_for_this_arm = rules_for_this_sum + .by_sum + .get(&node) .cloned() .unwrap_or_default(); @@ -866,11 +1029,14 @@ impl CPPExporter { if is_implemented { for field in interface.contents().fields() { match field.type_().get_primitive(&self.syntax) { - Some(IsNullable { is_nullable: _, content: Primitive::Interface(_) }) - | None => { - let typename = TypeName::type_(field.type_()); - interface_edges.insert(Rc::new(typename.to_string())); - }, + Some(IsNullable { + is_nullable: _, + content: Primitive::Interface(_), + }) + | None => { + let typename = TypeName::type_(field.type_()); + interface_edges.insert(Rc::new(typename.to_string())); + } // Don't have to handle other type of fields (string, // number, bool, etc). @@ -909,14 +1075,12 @@ impl CPPExporter { match named_implementation { NamedType::Interface(_) => { edges.insert(Rc::new(format!("Interface{}", parser.elements.to_string()))); - }, - NamedType::Typedef(ref type_) => { - match type_.spec() { - &TypeSpec::TypeSum(_) => { - edges.insert(Rc::new(format!("Sum{}", parser.elements.to_string()))); - }, - _ => {} + } + NamedType::Typedef(ref type_) => match type_.spec() { + &TypeSpec::TypeSum(_) => { + edges.insert(Rc::new(format!("Sum{}", parser.elements.to_string()))); } + _ => {} }, _ => {} } @@ -939,21 +1103,27 @@ impl CPPExporter { /// Collect context information for each interface to determine /// which *Context type each method should receive. fn collect_context(&mut self) { - fn add_context(map: &mut ContextMap, name: Rc, - context: LookupContext) { + fn add_context(map: &mut ContextMap, name: Rc, context: LookupContext) { let entry = map.entry(name).or_insert(LookupContext::empty()); (*entry).add(context); } // 1. Root - add_context(&mut self.context_map, - Rc::new("Program".to_string()), LookupContext::root()); - add_context(&mut self.context_map, - Rc::new("FunctionExpressionContents".to_string()), - LookupContext::root()); - add_context(&mut self.context_map, - Rc::new("FunctionOrMethodContents".to_string()), - LookupContext::root()); + add_context( + &mut self.context_map, + Rc::new("Program".to_string()), + LookupContext::root(), + ); + add_context( + &mut self.context_map, + Rc::new("FunctionExpressionContents".to_string()), + LookupContext::root(), + ); + add_context( + &mut self.context_map, + Rc::new("FunctionOrMethodContents".to_string()), + LookupContext::root(), + ); // 2. Interface fields // XXX => XXX.field @@ -966,14 +1136,18 @@ impl CPPExporter { for field in interface.contents().fields() { match field.type_().get_primitive(&self.syntax) { - Some(IsNullable { is_nullable: _, - content: Primitive::Interface(_) }) - | None => { - let typename = TypeName::type_(field.type_()); - add_context(&mut self.context_map, - Rc::new(typename), - LookupContext::field()); - } + Some(IsNullable { + is_nullable: _, + content: Primitive::Interface(_), + }) + | None => { + let typename = TypeName::type_(field.type_()); + add_context( + &mut self.context_map, + Rc::new(typename), + LookupContext::field(), + ); + } _ => {} } } @@ -986,17 +1160,16 @@ impl CPPExporter { continue; } - add_context(&mut self.context_map, - Rc::new(parser.elements.to_class_cases()), - LookupContext::list()); + add_context( + &mut self.context_map, + Rc::new(parser.elements.to_class_cases()), + LookupContext::list(), + ); } - fn propagate_context(map: &mut ContextMap, from: Rc, - to: Rc) { + fn propagate_context(map: &mut ContextMap, from: Rc, to: Rc) { let opt_context = match map.get(&from) { - Some(opt_context) => { - opt_context.clone() - } + Some(opt_context) => opt_context.clone(), _ => { return; } @@ -1015,19 +1188,21 @@ impl CPPExporter { let named_implementation = self.get_named_implementation(&parser.name); match named_implementation { NamedType::Interface(_) => { - propagate_context(&mut self.context_map, - Rc::new(parser.name.to_class_cases()), - Rc::new(format!("Interface{}", parser.elements.to_class_cases()))); - }, - NamedType::Typedef(ref type_) => { - match type_.spec() { - &TypeSpec::TypeSum(_) => { - propagate_context(&mut self.context_map, - Rc::new(parser.name.to_class_cases()), - Rc::new(format!("Sum{}", parser.elements.to_class_cases()))); - }, - _ => {} + propagate_context( + &mut self.context_map, + Rc::new(parser.name.to_class_cases()), + Rc::new(format!("Interface{}", parser.elements.to_class_cases())), + ); + } + NamedType::Typedef(ref type_) => match type_.spec() { + &TypeSpec::TypeSum(_) => { + propagate_context( + &mut self.context_map, + Rc::new(parser.name.to_class_cases()), + Rc::new(format!("Sum{}", parser.elements.to_class_cases())), + ); } + _ => {} }, _ => {} } @@ -1045,13 +1220,15 @@ impl CPPExporter { propagate_context( &mut self.context_map, Rc::new(name.to_class_cases()), - Rc::new(format!("Sum{}", name.to_class_cases()))); + Rc::new(format!("Sum{}", name.to_class_cases())), + ); for node in nodes { propagate_context( &mut self.context_map, Rc::new(format!("Sum{}", name.to_class_cases())), - Rc::new(format!("Interface{}", node.to_class_cases()))); + Rc::new(format!("Interface{}", node.to_class_cases())), + ); } } @@ -1068,15 +1245,17 @@ impl CPPExporter { propagate_context( &mut self.context_map, Rc::new(name.to_class_cases()), - Rc::new(format!("Interface{}", name.to_class_cases()))); + Rc::new(format!("Interface{}", name.to_class_cases())), + ); propagate_context( &mut self.context_map, Rc::new(format!("Interface{}", name.to_class_cases())), - Rc::new(name.to_class_cases())); + Rc::new(name.to_class_cases()), + ); } } -// ----- Generating the header + // ----- Generating the header /// Get the type representing a success for parsing this node. fn get_type_ok(&self, name: &NodeName) -> Rc { @@ -1107,14 +1286,16 @@ impl CPPExporter { } fn get_context_param(&self, name: &NodeName, prefix: &str) -> String { - let context = match self.context_map.get(&Rc::new(format!("{}{}", prefix, name.to_rc_string()))) { - Some(context) => { - context.clone() - } - _ => { - panic!("{}{} doesn't have context", prefix, name.to_rc_string()); - } - }; + let context = + match self + .context_map + .get(&Rc::new(format!("{}{}", prefix, name.to_rc_string()))) + { + Some(context) => context.clone(), + _ => { + panic!("{}{} doesn't have context", prefix, name.to_rc_string()); + } + }; if context.is_root() { return "const RootContext& context".to_string(); } @@ -1134,25 +1315,25 @@ impl CPPExporter { panic!("unexpected context"); } - fn get_method_signature(&self, name: &NodeName, prefix: &str, args: &str, - extra_params: &Option>) -> String { + fn get_method_signature( + &self, + name: &NodeName, + prefix: &str, + args: &str, + extra_params: &Option>, + ) -> String { let type_ok = self.get_type_ok(name); let kind = name.to_class_cases(); let extra = match extra_params { - Some(s) => { - format!("{}\n{}", - if args.len() > 0 { - "," - } else { - "" - }, - s.reindent(" ")) - } - _ => { - "".to_string() - } + Some(s) => format!( + "{}\n{}", + if args.len() > 0 { "," } else { "" }, + s.reindent(" ") + ), + _ => "".to_string(), }; - format!(" JS::Result<{type_ok}> parse{prefix}{kind}({args}{extra}{before_context}{context}); + format!( + " JS::Result<{type_ok}> parse{prefix}{kind}({args}{extra}{before_context}{context}); ", prefix = prefix, type_ok = type_ok, @@ -1168,25 +1349,25 @@ impl CPPExporter { ) } - fn get_method_definition_start(&self, name: &NodeName, prefix: &str, args: &str, - extra_params: &Option>) -> String { + fn get_method_definition_start( + &self, + name: &NodeName, + prefix: &str, + args: &str, + extra_params: &Option>, + ) -> String { let type_ok = self.get_type_ok(name); let kind = name.to_class_cases(); let extra = match extra_params { - Some(s) => { - format!("{}\n{}", - if args.len() > 0 { - "," - } else { - "" - }, - s.reindent(" ")) - } - _ => { - "".to_string() - } + Some(s) => format!( + "{}\n{}", + if args.len() > 0 { "," } else { "" }, + s.reindent(" ") + ), + _ => "".to_string(), }; - format!("{parser_class_template}JS::Result<{type_ok}> + format!( + "{parser_class_template}JS::Result<{type_ok}> {parser_class_name}::parse{prefix}{kind}({args}{extra}{before_context}{context})", parser_class_template = self.rules.parser_class_template, prefix = prefix, @@ -1204,18 +1385,17 @@ impl CPPExporter { ) } - fn get_context_param_for_sum(&self, sum: &NodeName, - arm: &NodeName, context: &str) -> String { + fn get_context_param_for_sum(&self, sum: &NodeName, arm: &NodeName, context: &str) -> String { let sum_name = format!("Sum{}", sum); let arm_name = format!("Interface{}", arm); let sum_context = match self.context_map.get(&sum_name) { Some(context) => context.clone(), - _ => panic!("no context") + _ => panic!("no context"), }; let arm_context = match self.context_map.get(&arm_name) { Some(context) => context.clone(), - _ => panic!("no context") + _ => panic!("no context"), }; if sum_context == arm_context { @@ -1232,19 +1412,23 @@ impl CPPExporter { return format!("FieldOrListContext({})", context); } - fn get_context_param_for_optional(&self, optional: &NodeName, - body_prefix: &str, body: &NodeName, - context: &str) -> String { + fn get_context_param_for_optional( + &self, + optional: &NodeName, + body_prefix: &str, + body: &NodeName, + context: &str, + ) -> String { let optional_name = optional.to_string().clone(); let body_name = format!("{}{}", body_prefix, body); let optional_context = match self.context_map.get(&optional_name) { Some(context) => context.clone(), - _ => panic!("no context") + _ => panic!("no context"), }; let body_context = match self.context_map.get(&body_name) { Some(context) => context.clone(), - _ => panic!("no context") + _ => panic!("no context"), }; if optional_context == body_context { @@ -1261,13 +1445,12 @@ impl CPPExporter { return format!("FieldOrListContext({})", context); } - fn get_context_param_for_list(&self, element: &NodeName, - context: &str) -> String { + fn get_context_param_for_list(&self, element: &NodeName, context: &str) -> String { let element_name = element.to_string().clone(); let element_context = match self.context_map.get(&element_name) { Some(context) => context.clone(), - _ => panic!("no context") + _ => panic!("no context"), }; if element_context.is_list() { @@ -1279,13 +1462,12 @@ impl CPPExporter { return format!("FieldOrListContext({})", context); } - fn get_context_param_for_field(&self, field: &NodeName, - context: &str) -> String { + fn get_context_param_for_field(&self, field: &NodeName, context: &str) -> String { let field_name = field.to_string().clone(); let field_context = match self.context_map.get(&field_name) { Some(context) => context.clone(), - _ => panic!("no context") + _ => panic!("no context"), }; if field_context.is_field() { @@ -1301,66 +1483,69 @@ impl CPPExporter { return format!("FieldOrListContext({})", context); } - fn get_method_call(&self, var_name: &str, name: &NodeName, - prefix: &str, args: &str, - extra_params: &Option>, - context_name: String, - call_kind: MethodCallKind) -> String { + fn get_method_call( + &self, + var_name: &str, + name: &NodeName, + prefix: &str, + args: &str, + extra_params: &Option>, + context_name: String, + call_kind: MethodCallKind, + ) -> String { let type_ok_is_ok = match call_kind { - MethodCallKind::Decl | MethodCallKind::Var => { - self.get_type_ok(name).to_str() == "Ok" - } - MethodCallKind::AlwaysDecl | MethodCallKind::AlwaysVar => { - false - } + MethodCallKind::Decl | MethodCallKind::Var => self.get_type_ok(name).to_str() == "Ok", + MethodCallKind::AlwaysDecl | MethodCallKind::AlwaysVar => false, }; let extra = match extra_params { - Some(s) => { - format!("{}\n{}", - if args.len() > 0 { - "," - } else { - "" - }, - s.reindent(" ")) - } - _ => { - "".to_string() - } + Some(s) => format!( + "{}\n{}", + if args.len() > 0 { "," } else { "" }, + s.reindent(" ") + ), + _ => "".to_string(), }; - let call = format!("parse{prefix}{name}({args}{extra}{before_context}{context})", - prefix = prefix, - name = name.to_class_cases(), - args = args, - extra = extra, - before_context = if extra_params.is_some() || args.len() > 0 { - ", " - } else { - "" - }, - context = context_name + let call = format!( + "parse{prefix}{name}({args}{extra}{before_context}{context})", + prefix = prefix, + name = name.to_class_cases(), + args = args, + extra = extra, + before_context = if extra_params.is_some() || args.len() > 0 { + ", " + } else { + "" + }, + context = context_name ); if type_ok_is_ok { // Special case: `Ok` means that we shouldn't bind the return value. - format!("MOZ_TRY({call});", - call = call) + format!("MOZ_TRY({call});", call = call) } else { match call_kind { - MethodCallKind::Decl | MethodCallKind::AlwaysDecl => { - format!("BINJS_MOZ_TRY_DECL({var_name}, {call});", - var_name = var_name, call = call) - } - MethodCallKind::Var | MethodCallKind::AlwaysVar => { - format!("MOZ_TRY_VAR({var_name}, {call});", - var_name = var_name, call = call) - } + MethodCallKind::Decl | MethodCallKind::AlwaysDecl => format!( + "BINJS_MOZ_TRY_DECL({var_name}, {call});", + var_name = var_name, + call = call + ), + MethodCallKind::Var | MethodCallKind::AlwaysVar => format!( + "MOZ_TRY_VAR({var_name}, {call});", + var_name = var_name, + call = call + ), } } } /// Auxiliary function: get a name for a field type. - fn get_field_type_name(canonical_list_parsers: &HashMap, _typedef: Option<&str>, spec: &Spec, type_: &Type, make_optional: bool) -> Cow<'static, str> { + fn get_field_type_name( + canonical_list_parsers: &HashMap, + _typedef: Option<&str>, + spec: &Spec, + type_: &Type, + make_optional: bool, + ) -> Cow<'static, str> { let optional = make_optional || type_.is_optional(); match *type_.spec() { TypeSpec::Boolean if optional => Cow::from("PRIMITIVE(MaybeBoolean)"), @@ -1383,29 +1568,47 @@ impl CPPExporter { let typename = TypeName::type_(contents); let node_name = spec.get_node_name(&typename).unwrap(); let ref name = canonical_list_parsers.get(node_name).unwrap().name; - let contents = Self::get_field_type_name(canonical_list_parsers, None, spec, contents, false); + let contents = + Self::get_field_type_name(canonical_list_parsers, None, spec, contents, false); debug!(target: "generate_spidermonkey", "get_field_type_name for LIST {name}", name = name); - Cow::from(format!("LIST({name}, {contents})", + Cow::from(format!( + "LIST({name}, {contents})", name = name, - contents = contents)) - }, + contents = contents + )) + } TypeSpec::NamedType(ref name) => { debug!(target: "generate_spidermonkey", "get_field_type_name for named type {name} ({optional})", name = name, optional = if optional { "optional" } else { "required" }); - match spec.get_type_by_name(name).expect("By now, all types MUST exist") { + match spec + .get_type_by_name(name) + .expect("By now, all types MUST exist") + { NamedType::Typedef(alias_type) => { if alias_type.is_optional() { - return Self::get_field_type_name(canonical_list_parsers, Some(name.to_str()), spec, alias_type.as_ref(), true) + return Self::get_field_type_name( + canonical_list_parsers, + Some(name.to_str()), + spec, + alias_type.as_ref(), + true, + ); } // Keep the simple name of sums and lists if there is one. match *alias_type.spec() { TypeSpec::TypeSum(_) => { if optional { - Cow::from(format!("OPTIONAL_SUM({name})", name = name.to_cpp_enum_case())) + Cow::from(format!( + "OPTIONAL_SUM({name})", + name = name.to_cpp_enum_case() + )) } else { - Cow::from(format!("SUM({name})", name = name.to_cpp_enum_case())) + Cow::from(format!( + "SUM({name})", + name = name.to_cpp_enum_case() + )) } } TypeSpec::Array { ref contents, .. } => { @@ -1413,36 +1616,56 @@ impl CPPExporter { let typename = TypeName::type_(contents); let node_name = spec.get_node_name(&typename).unwrap(); let ref name = canonical_list_parsers.get(node_name).unwrap().name; - let contents = Self::get_field_type_name(canonical_list_parsers, None, spec, contents, false); + let contents = Self::get_field_type_name( + canonical_list_parsers, + None, + spec, + contents, + false, + ); debug!(target: "generate_spidermonkey", "get_field_type_name for typedefed LIST {name}", name = name); if optional { - Cow::from(format!("OPTIONAL_LIST({name}, {contents})", + Cow::from(format!( + "OPTIONAL_LIST({name}, {contents})", name = name.to_cpp_enum_case(), - contents = contents)) + contents = contents + )) } else { - Cow::from(format!("LIST({name}, {contents})", + Cow::from(format!( + "LIST({name}, {contents})", name = name.to_cpp_enum_case(), - contents = contents)) + contents = contents + )) } } - _ => { - Self::get_field_type_name(canonical_list_parsers, Some(name.to_str()), spec, alias_type.as_ref(), optional) - } + _ => Self::get_field_type_name( + canonical_list_parsers, + Some(name.to_str()), + spec, + alias_type.as_ref(), + optional, + ), } } - NamedType::StringEnum(_) if type_.is_optional() => Cow::from( - format!("OPTIONAL_STRING_ENUM({name})", - name = TypeName::type_(type_))), - NamedType::StringEnum(_) => Cow::from( - format!("STRING_ENUM({name})", - name = TypeName::type_(type_))), - NamedType::Interface(ref interface) if type_.is_optional() => Cow::from( - format!("OPTIONAL_INTERFACE({name})", - name = interface.name().to_class_cases())), - NamedType::Interface(ref interface) => Cow::from( - format!("INTERFACE({name})", - name = interface.name().to_class_cases())), + NamedType::StringEnum(_) if type_.is_optional() => Cow::from(format!( + "OPTIONAL_STRING_ENUM({name})", + name = TypeName::type_(type_) + )), + NamedType::StringEnum(_) => Cow::from(format!( + "STRING_ENUM({name})", + name = TypeName::type_(type_) + )), + NamedType::Interface(ref interface) if type_.is_optional() => { + Cow::from(format!( + "OPTIONAL_INTERFACE({name})", + name = interface.name().to_class_cases() + )) + } + NamedType::Interface(ref interface) => Cow::from(format!( + "INTERFACE({name})", + name = interface.name().to_class_cases() + )), } } TypeSpec::TypeSum(ref contents) if type_.is_optional() => { @@ -1453,7 +1676,9 @@ impl CPPExporter { let name = TypeName::type_(&non_optional_type); Cow::from(format!("OPTIONAL_SUM({name})", name = name)) } - TypeSpec::TypeSum(_) => Cow::from(format!("SUM({name})", name = TypeName::type_(type_))), + TypeSpec::TypeSum(_) => { + Cow::from(format!("SUM({name})", name = TypeName::type_(type_))) + } } } @@ -1466,66 +1691,85 @@ impl CPPExporter { buffer.push_str(&self.rules.hpp_tokens_kind_doc.reindent("")); } - let node_names = self.syntax.interfaces_by_name() + let node_names = self + .syntax + .interfaces_by_name() .keys() .map(|n| n.to_string()) .sorted() .collect_vec(); let kind_limit = node_names.len(); - buffer.push_str(&format!(" + buffer.push_str(&format!( + " #define FOR_EACH_BIN_KIND(F) \\ F(_Uninitialized, \"Uninitialized\", UNINITIALIZED) \\ {nodes} ", - nodes = node_names.iter() - .map(|name| format!(" F({enum_name}, \"{spec_name}\", {macro_name})", + nodes = node_names + .iter() + .map(|name| format!( + " F({enum_name}, \"{spec_name}\", {macro_name})", enum_name = name.to_cpp_enum_case(), spec_name = name, - macro_name = name.to_cpp_macro_case())) - .format(" \\\n"))); - buffer.push_str(" + macro_name = name.to_cpp_macro_case() + )) + .format(" \\\n") + )); + buffer.push_str( + " enum class BinASTKind: uint16_t { #define EMIT_ENUM(name, _1, _2) name, FOR_EACH_BIN_KIND(EMIT_ENUM) #undef EMIT_ENUM }; -"); +", + ); - buffer.push_str(&format!(" + buffer.push_str(&format!( + " // The number of distinct values of BinASTKind. const size_t BINASTKIND_LIMIT = {}; -", kind_limit)); +", + kind_limit + )); if self.rules.hpp_tokens_field_doc.is_some() { buffer.push_str(&self.rules.hpp_tokens_field_doc.reindent("")); } - let field_names = self.syntax.field_names() - .keys() - .sorted() - .collect_vec(); + let field_names = self.syntax.field_names().keys().sorted().collect_vec(); let field_limit = field_names.len(); - buffer.push_str(&format!(" + buffer.push_str(&format!( + " #define FOR_EACH_BIN_FIELD(F) \\ {nodes} ", - nodes = field_names.iter() - .map(|name| format!(" F({enum_name}, \"{spec_name}\")", + nodes = field_names + .iter() + .map(|name| format!( + " F({enum_name}, \"{spec_name}\")", spec_name = name, - enum_name = name.to_cpp_enum_case())) - .format(" \\\n"))); - buffer.push_str(" + enum_name = name.to_cpp_enum_case() + )) + .format(" \\\n") + )); + buffer.push_str( + " enum class BinASTField: uint16_t { #define EMIT_ENUM(name, _) name, FOR_EACH_BIN_FIELD(EMIT_ENUM) #undef EMIT_ENUM }; -"); - buffer.push_str(&format!(" +", + ); + buffer.push_str(&format!( + " // The number of distinct values of BinASTField. const size_t BINASTFIELD_LIMIT = {}; -", field_limit)); +", + field_limit + )); buffer.push_str(&format!(" @@ -1550,15 +1794,19 @@ const size_t BINASTFIELD_LIMIT = {}; ) }) .format(" \\\n"))); - buffer.push_str(" + buffer.push_str( + " enum class BinASTInterfaceAndField: uint16_t { #define EMIT_ENUM(name, _) name, FOR_EACH_BIN_INTERFACE_AND_FIELD(EMIT_ENUM) #undef EMIT_ENUM }; -"); +", + ); - for (sum_name, sum) in self.syntax.resolved_sums_of_interfaces_by_name() + for (sum_name, sum) in self + .syntax + .resolved_sums_of_interfaces_by_name() .iter() .sorted_by_key(|a| a.0) { @@ -1592,11 +1840,8 @@ const size_t BINAST_SUM_{sum_macro_name}_LIMIT = {limit}; ) }) .format(" \\\n"))); - - } - buffer.push_str(" // Strongly typed iterations through the fields of interfaces. // @@ -1617,7 +1862,12 @@ const size_t BINAST_SUM_{sum_macro_name}_LIMIT = {limit}; F, PRIMITIVE, INTERFACE, OPTIONAL_INTERFACE, LIST, SUM, OPTIONAL_SUM, \ STRING_ENUM, OPTIONAL_STRING_ENUM) "); - for (interface_name, interface) in self.syntax.interfaces_by_name().iter().sorted_by_key(|a| a.0) { + for (interface_name, interface) in self + .syntax + .interfaces_by_name() + .iter() + .sorted_by_key(|a| a.0) + { let interface_enum_name = interface_name.to_cpp_enum_case(); let interface_spec_name = interface_name.clone(); let interface_macro_name = interface.name().to_cpp_macro_case(); @@ -1644,15 +1894,19 @@ const size_t BINAST_SUM_{sum_macro_name}_LIMIT = {limit}; ) }) .format(" \\\n"))); - buffer.push_str(&format!(" + buffer.push_str(&format!( + " // The number of fields of interface {interface_spec_name}. const size_t BINAST_NUMBER_OF_FIELDS_IN_INTERFACE_{interface_macro_name} = {len};", interface_spec_name = interface_spec_name, interface_macro_name = interface_macro_name, - len = interface.contents().fields().len())); + len = interface.contents().fields().len() + )); } - let total_number_of_fields: usize = self.syntax.interfaces_by_name() + let total_number_of_fields: usize = self + .syntax + .interfaces_by_name() .values() .map(|interface| interface.contents().fields().len()) .sum(); @@ -1671,82 +1925,107 @@ const size_t BINAST_INTERFACE_AND_FIELD_LIMIT = {number}; if self.rules.hpp_tokens_variants_doc.is_some() { buffer.push_str(&self.rules.hpp_tokens_variants_doc.reindent("")); } - let enum_variants : Vec<_> = self.variants_by_symbol + let enum_variants: Vec<_> = self + .variants_by_symbol .iter() .sorted_by_key(|a| a.0) .collect_vec(); let variants_limit = enum_variants.len(); - buffer.push_str(&format!(" + buffer.push_str(&format!( + " #define FOR_EACH_BIN_VARIANT(F) \\ {nodes} ", - nodes = enum_variants.into_iter() - .map(|(symbol, name)| format!(" F({variant_name}, \"{spec_name}\")", + nodes = enum_variants + .into_iter() + .map(|(symbol, name)| format!( + " F({variant_name}, \"{spec_name}\")", spec_name = symbol, - variant_name = name)) - .format(" \\\n"))); + variant_name = name + )) + .format(" \\\n") + )); - buffer.push_str(" + buffer.push_str( + " enum class BinASTVariant: uint16_t { #define EMIT_ENUM(name, _) name, FOR_EACH_BIN_VARIANT(EMIT_ENUM) #undef EMIT_ENUM }; -"); - buffer.push_str(&format!(" +", + ); + buffer.push_str(&format!( + " // The number of distinct values of BinASTVariant. const size_t BINASTVARIANT_LIMIT = {}; ", - variants_limit)); + variants_limit + )); - buffer.push_str(&format!(" + buffer.push_str(&format!( + " #define FOR_EACH_BIN_STRING_ENUM(F) \\ {nodes} ", - nodes = self.syntax.string_enums_by_name() + nodes = self + .syntax + .string_enums_by_name() .keys() .sorted() .into_iter() - .map(|name| format!(" F({enum_name}, \"{spec_name}\", {macro_name})", + .map(|name| format!( + " F({enum_name}, \"{spec_name}\", {macro_name})", enum_name = name.to_cpp_enum_case(), spec_name = name.to_str(), - macro_name = name.to_cpp_macro_case())) - .format(" \\\n"))); + macro_name = name.to_cpp_macro_case() + )) + .format(" \\\n") + )); - buffer.push_str(" + buffer.push_str( + " enum class BinASTStringEnum: uint16_t { #define EMIT_ENUM(NAME, _HUMAN_NAME, _MACRO_NAME) NAME, FOR_EACH_BIN_STRING_ENUM(EMIT_ENUM) #undef EMIT_ENUM }; -"); - buffer.push_str(&format!(" +", + ); + buffer.push_str(&format!( + " // The number of distinct values of BinASTStringEnum. const size_t BINASTSTRINGENUM_LIMIT = {}; ", - self.syntax.string_enums_by_name().len())); + self.syntax.string_enums_by_name().len() + )); - for (name, enum_) in self.syntax.string_enums_by_name() + for (name, enum_) in self + .syntax + .string_enums_by_name() .iter() .sorted_by_key(|kv| kv.0) .into_iter() { let enum_name = name.to_str().to_class_cases(); let enum_macro_name = name.to_cpp_macro_case(); - buffer.push_str(&format!(" + buffer.push_str(&format!( + " #define FOR_EACH_BIN_VARIANT_IN_STRING_ENUM_{enum_macro_name}_BY_STRING_ORDER(F) \\ {variants} ", enum_macro_name = enum_macro_name, - variants = enum_.strings() + variants = enum_ + .strings() .iter() .sorted() .into_iter() .map(|variant_string| { - format!(" F({enum_name}, {variant_name}, \"{variant_string}\")", + format!( + " F({enum_name}, {variant_name}, \"{variant_string}\")", enum_name = enum_name, variant_name = self.variants_by_symbol.get(variant_string).unwrap(), variant_string = variant_string @@ -1754,15 +2033,18 @@ const size_t BINASTSTRINGENUM_LIMIT = {}; }) .format("\\\n") )); - buffer.push_str(&format!(" + buffer.push_str(&format!( + " #define FOR_EACH_BIN_VARIANT_IN_STRING_ENUM_{enum_macro_name}_BY_WEBIDL_ORDER(F) \\ {variants} ", enum_macro_name = enum_macro_name, - variants = enum_.strings() + variants = enum_ + .strings() .iter() .map(|variant_string| { - format!(" F({enum_name}, {variant_name}, \"{variant_string}\")", + format!( + " F({enum_name}, {variant_name}, \"{variant_string}\")", enum_name = enum_name, variant_name = self.variants_by_symbol.get(variant_string).unwrap(), variant_string = variant_string @@ -1770,7 +2052,8 @@ const size_t BINASTSTRINGENUM_LIMIT = {}; }) .format("\\\n") )); - buffer.push_str(&format!(" + buffer.push_str(&format!( + " const size_t BIN_AST_STRING_ENUM_{enum_macro_name}_LIMIT = {len}; ", @@ -1834,27 +2117,41 @@ const size_t BINAST_NUMBER_OF_LIST_TYPES = {number}; .map(|_| "(X)") .format(","))); - buffer.push_str(&format!(" + buffer.push_str(&format!( + " #define FOR_EACH_BIN_SUM(F) \\ {nodes} ", - nodes = self.syntax.resolved_sums_of_interfaces_by_name() + nodes = self + .syntax + .resolved_sums_of_interfaces_by_name() .iter() .sorted_by_key(|a| a.0) .into_iter() - .map(|(name, _)| format!(" F({name}, \"{spec_name}\", {macro_name}, {type_name})", + .map(|(name, _)| format!( + " F({name}, \"{spec_name}\", {macro_name}, {type_name})", name = name.to_cpp_enum_case(), spec_name = name.to_str(), macro_name = name.to_cpp_macro_case(), - type_name = Self::get_field_type_name(&self.canonical_list_parsers, Some(name.to_str()), &self.syntax, self.syntax.typedefs_by_name().get(name).unwrap(), false))) - .format(" \\\n"))); - buffer.push_str(" + type_name = Self::get_field_type_name( + &self.canonical_list_parsers, + Some(name.to_str()), + &self.syntax, + self.syntax.typedefs_by_name().get(name).unwrap(), + false + ) + )) + .format(" \\\n") + )); + buffer.push_str( + " enum class BinASTSum: uint16_t { #define EMIT_ENUM(name, _user, _macro, _type) name, FOR_EACH_BIN_SUM(EMIT_ENUM) #undef EMIT_ENUM }; -"); +", + ); buffer.push_str(&format!(" // The number of distinct sum types in the grammar. Used typically to maintain a probability table per sum type. const size_t BINAST_NUMBER_OF_SUM_TYPES = {}; @@ -1864,45 +2161,59 @@ const size_t BINAST_NUMBER_OF_SUM_TYPES = {}; buffer.push_str(&self.rules.hpp_tokens_footer.reindent("")); buffer.push_str("\n"); - } /// Declare string enums fn export_declare_string_enums(&self, buffer: &mut String) { - buffer.push_str(" + buffer.push_str( + " // ----- Declaring string enums (by lexicographical order) -"); - let string_enums_by_name = self.syntax.string_enums_by_name() +", + ); + let string_enums_by_name = self + .syntax + .string_enums_by_name() .iter() .sorted_by(|a, b| str::cmp(a.0.to_str(), b.0.to_str())); for (name, enum_) in string_enums_by_name { - let rendered_cases = enum_.strings() + let rendered_cases = enum_ + .strings() .iter() - .map(|str| format!(" // \"{original}\" + .map(|str| { + format!( + " // \"{original}\" {case},", - case = str.to_cpp_enum_case(), - original = str)) + case = str.to_cpp_enum_case(), + original = str + ) + }) .format("\n"); - let rendered = format!(" + let rendered = format!( + " enum class {name} {{ {cases} }}; ", cases = rendered_cases, - name = name.to_class_cases()); + name = name.to_class_cases() + ); buffer.push_str(&rendered); } } fn export_declare_sums_of_interface_methods(&self, buffer: &mut String) { - let sums_of_interfaces = self.syntax.resolved_sums_of_interfaces_by_name() + let sums_of_interfaces = self + .syntax + .resolved_sums_of_interfaces_by_name() .iter() .sorted_by(|a, b| a.0.cmp(&b.0)) .collect_vec(); - buffer.push_str(" + buffer.push_str( + " // ----- Sums of interfaces (by lexicographical order) // `ParseNode*` may never be nullptr -"); +", + ); for &(ref name, _) in &sums_of_interfaces { if !self.refgraph.is_used(name.to_rc_string().clone()) { continue; @@ -1910,33 +2221,36 @@ enum class {name} {{ let rules_for_this_sum = self.rules.get(name); let extra_params = rules_for_this_sum.extra_params; - let rendered = self.get_method_signature(name, "", "", - &extra_params); - buffer.push_str(&rendered.reindent(" ") - .newline_if_not_empty()); + let rendered = self.get_method_signature(name, "", "", &extra_params); + buffer.push_str(&rendered.reindent(" ").newline_if_not_empty()); } for (name, _) in sums_of_interfaces { let prefix = "Sum"; - if !self.refgraph.is_used(Rc::new(format!("{}{}", prefix, name))) { + if !self + .refgraph + .is_used(Rc::new(format!("{}{}", prefix, name))) + { continue; } let rules_for_this_sum = self.rules.get(name); let extra_params = rules_for_this_sum.extra_params; - let rendered = self.get_method_signature(name, prefix, - SUM_INTERFACE_PARAMS, - &extra_params); - buffer.push_str(&rendered.reindent(" ") - .newline_if_not_empty()); + let rendered = + self.get_method_signature(name, prefix, SUM_INTERFACE_PARAMS, &extra_params); + buffer.push_str(&rendered.reindent(" ").newline_if_not_empty()); } } fn export_declare_single_interface_methods(&self, buffer: &mut String) { - buffer.push_str(" + buffer.push_str( + " // ----- Interfaces (by lexicographical order) // `ParseNode*` may never be nullptr -"); - let interfaces_by_name = self.syntax.interfaces_by_name() +", + ); + let interfaces_by_name = self + .syntax + .interfaces_by_name() .iter() .sorted_by(|a, b| str::cmp(a.0.to_str(), b.0.to_str())) .collect_vec(); @@ -1954,12 +2268,14 @@ enum class {name} {{ } let inner_prefix = "Interface"; - if !self.refgraph.is_used(Rc::new(format!("{}{}", inner_prefix, name))) { + if !self + .refgraph + .is_used(Rc::new(format!("{}{}", inner_prefix, name))) + { continue; } - let inner = self.get_method_signature(name, inner_prefix, - INTERFACE_PARAMS, - &extra_params); + let inner = + self.get_method_signature(name, inner_prefix, INTERFACE_PARAMS, &extra_params); inner_parsers.push(inner.reindent(" ")); } @@ -1975,10 +2291,14 @@ enum class {name} {{ } fn export_declare_string_enums_methods(&self, buffer: &mut String) { - buffer.push_str(" + buffer.push_str( + " // ----- String enums (by lexicographical order) -"); - let string_enums_by_name = self.syntax.string_enums_by_name() +", + ); + let string_enums_by_name = self + .syntax + .string_enums_by_name() .iter() .sorted_by(|a, b| str::cmp(a.0.to_str(), b.0.to_str())); for (kind, _) in string_enums_by_name { @@ -1993,9 +2313,11 @@ enum class {name} {{ } fn export_declare_list_methods(&self, buffer: &mut String) { - buffer.push_str(" + buffer.push_str( + " // ----- Lists (by lexicographical order) -"); +", + ); for parser in &self.list_parsers_to_generate { if !self.refgraph.is_used(parser.name.to_rc_string().clone()) { continue; @@ -2003,17 +2325,18 @@ enum class {name} {{ let rules_for_this_node = self.rules.get(&parser.name); let extra_params = rules_for_this_node.extra_params; - let rendered = self.get_method_signature(&parser.name, "", "", - &extra_params); + let rendered = self.get_method_signature(&parser.name, "", "", &extra_params); buffer.push_str(&rendered.reindent(" ")); buffer.push_str("\n"); } } fn export_declare_option_methods(&self, buffer: &mut String) { - buffer.push_str(" + buffer.push_str( + " // ----- Default values (by lexicographical order) -"); +", + ); for parser in &self.option_parsers_to_generate { if !self.refgraph.is_used(parser.name.to_rc_string().clone()) { continue; @@ -2021,17 +2344,18 @@ enum class {name} {{ let rules_for_this_node = self.rules.get(&parser.name); let extra_params = rules_for_this_node.extra_params; - let rendered = self.get_method_signature(&parser.name, "", "", - &extra_params); + let rendered = self.get_method_signature(&parser.name, "", "", &extra_params); buffer.push_str(&rendered.reindent(" ")); buffer.push_str("\n"); } } fn generate_autogenerated_warning(&self) -> String { - let warning = format!("// This file was autogenerated by binjs_generate_spidermonkey, + let warning = format!( + "// This file was autogenerated by binjs_generate_spidermonkey, // please DO NOT EDIT BY HAND. -"); +" + ); warning } @@ -2085,26 +2409,31 @@ enum class {name} {{ impl CPPExporter { /// Generate implementation of a single typesum. - fn generate_implement_sum(&self, buffer: &mut String, name: &NodeName, nodes: &HashSet) { + fn generate_implement_sum( + &self, + buffer: &mut String, + name: &NodeName, + nodes: &HashSet, + ) { // Generate comments (FIXME: We should use the actual webidl, not the resolved sum) let rules_for_this_sum = self.rules.get(name); let extra_params = rules_for_this_sum.extra_params; let extra_args = rules_for_this_sum.extra_args; - let nodes = nodes.iter() - .sorted() - .collect_vec(); + let nodes = nodes.iter().sorted().collect_vec(); let kind = name.to_class_cases(); if self.refgraph.is_used(name.to_rc_string().clone()) { - let rendered_bnf = format!("/* + let rendered_bnf = format!( + "/* {name} ::= {nodes} */", - nodes = nodes.iter() - .format("\n "), - name = name.to_str()); + nodes = nodes.iter().format("\n "), + name = name.to_str() + ); // Generate outer method - buffer.push_str(&format!("{bnf} + buffer.push_str(&format!( + "{bnf} {first_line} {{ BinASTKind kind = BinASTKind::_Uninitialized; @@ -2121,26 +2450,35 @@ impl CPPExporter { }} ", bnf = rendered_bnf, - call = self.get_method_call("result", name, - "Sum", SUM_INTERFACE_ARGS, - &extra_args, - "context".to_string(), - MethodCallKind::AlwaysDecl) + call = self + .get_method_call( + "result", + name, + "Sum", + SUM_INTERFACE_ARGS, + &extra_args, + "context".to_string(), + MethodCallKind::AlwaysDecl + ) .reindent(" "), - first_line = self.get_method_definition_start(name, "", "", - &extra_params) + first_line = self.get_method_definition_start(name, "", "", &extra_params) )); } let inner_prefix = "Sum"; - if !self.refgraph.is_used(Rc::new(format!("{}{}", inner_prefix, name))) { + if !self + .refgraph + .is_used(Rc::new(format!("{}{}", inner_prefix, name))) + { return; } // Generate inner method let mut buffer_cases = String::new(); for node in nodes { - let rule_for_this_arm = rules_for_this_sum.by_sum.get(&node) + let rule_for_this_arm = rules_for_this_sum + .by_sum + .get(&node) .cloned() .unwrap_or_default(); @@ -2152,22 +2490,31 @@ impl CPPExporter { continue; } - buffer_cases.push_str(&format!(" + buffer_cases.push_str(&format!( + " case BinASTKind::{variant_name}: {call} {arm_after} break;", - call = self.get_method_call("result", node, - "Interface", INTERFACE_ARGS, - &extra_args, - self.get_context_param_for_sum( - name, node, "context"), - MethodCallKind::AlwaysVar) + call = self + .get_method_call( + "result", + node, + "Interface", + INTERFACE_ARGS, + &extra_args, + self.get_context_param_for_sum(name, node, "context"), + MethodCallKind::AlwaysVar + ) .reindent(" "), variant_name = node.to_cpp_enum_case(), - arm_after = rule_for_this_arm.after_arm.reindent(" ") - .newline_if_not_empty())); + arm_after = rule_for_this_arm + .after_arm + .reindent(" ") + .newline_if_not_empty() + )); } - buffer.push_str(&format!(" + buffer.push_str(&format!( + " {first_line} {{ @@ -2186,9 +2533,12 @@ impl CPPExporter { ", kind = kind, cases = buffer_cases, - first_line = self.get_method_definition_start(name, inner_prefix, - SUM_INTERFACE_PARAMS, - &extra_params), + first_line = self.get_method_definition_start( + name, + inner_prefix, + SUM_INTERFACE_PARAMS, + &extra_params + ), type_ok = self.get_type_ok(name) )); } @@ -2211,19 +2561,22 @@ impl CPPExporter { (rules_for_this_list.by_sum.len() > 0, "sum-arms:"), ] { if condition { - warn!("In {}, rule `{}` was specified but is ignored.", parser.name, name); + warn!( + "In {}, rule `{}` was specified but is ignored.", + parser.name, name + ); } } let kind = parser.name.to_class_cases(); - let first_line = self.get_method_definition_start(&parser.name, "", "", - &extra_params); + let first_line = self.get_method_definition_start(&parser.name, "", "", &extra_params); let init = match rules_for_this_list.init { Some(str) => str.reindent(" "), None => { // We cannot generate the method if we don't know how to initialize the list. - let rendered = format!(" + let rendered = format!( + " {first_line} {{ return raiseError(\"FIXME: Not implemented yet in this preview release ({kind})\"); @@ -2238,16 +2591,14 @@ impl CPPExporter { }; let append = match rules_for_this_list.append { Some(str) => str.reindent(" ").newline_if_not_empty(), - None => { - match self.rules.parser_list_append { - Some(ref str) => str.reindent(" ").newline_if_not_empty(), - None => "".to_string(), - } - } + None => match self.rules.parser_list_append { + Some(ref str) => str.reindent(" ").newline_if_not_empty(), + None => "".to_string(), + }, }; - - let rendered = format!(" + let rendered = format!( + " {first_line} {{ @@ -2269,30 +2620,38 @@ impl CPPExporter { }} ", first_line = first_line, - content_kind = - self.canonical_list_parsers.get(&parser.elements).unwrap() // Each list parser has a deduplicated representative - .name.to_class_cases(), - empty_check = - if parser.supports_empty { - "".to_string() - } else { - format!(" + content_kind = self + .canonical_list_parsers + .get(&parser.elements) + .unwrap() // Each list parser has a deduplicated representative + .name + .to_class_cases(), + empty_check = if parser.supports_empty { + "".to_string() + } else { + format!( + " if (MOZ_UNLIKELY(length == 0)) {{ return raiseEmpty(\"{kind}\"); }} ", - kind = kind) - }, - call = self.get_method_call("item", - &parser.elements, "", "", - &extra_args, - self.get_context_param_for_list( - &parser.elements, - "childContext"), - MethodCallKind::Decl) + kind = kind + ) + }, + call = self + .get_method_call( + "item", + &parser.elements, + "", + "", + &extra_args, + self.get_context_param_for_list(&parser.elements, "childContext"), + MethodCallKind::Decl + ) .reindent(" "), init = init, - append = append); + append = append + ); buffer.push_str(&rendered); } @@ -2316,7 +2675,10 @@ impl CPPExporter { (rules_for_this_node.by_sum.len() > 0, "sum-arms:"), ] { if condition { - warn!("In {}, rule `{}` was specified but is ignored.", parser.name, name); + warn!( + "In {}, rule `{}` was specified but is ignored.", + parser.name, name + ); } } @@ -2325,24 +2687,34 @@ impl CPPExporter { // At this stage, thanks to deanonymization, `contents` // is something like `OptionalFooBar`. - let named_implementation = - if let Some(NamedType::Typedef(ref typedef)) = self.syntax.get_type_by_name(&parser.name) { - assert!(typedef.is_optional()); - if let TypeSpec::NamedType(ref named) = *typedef.spec() { - self.syntax.get_type_by_name(named) - .unwrap_or_else(|| panic!("Internal error: Could not find type {}, which should have been generated.", named.to_str())) - } else { - panic!("Internal error: In {}, type {:?} should have been a named type", - parser.name.to_str(), - typedef); - } + let named_implementation = if let Some(NamedType::Typedef(ref typedef)) = + self.syntax.get_type_by_name(&parser.name) + { + assert!(typedef.is_optional()); + if let TypeSpec::NamedType(ref named) = *typedef.spec() { + self.syntax.get_type_by_name(named).unwrap_or_else(|| { + panic!( + "Internal error: Could not find type {}, which should have been generated.", + named.to_str() + ) + }) } else { - panic!("Internal error: In {}, there should be a type with that name", - parser.name.to_str()); - }; + panic!( + "Internal error: In {}, type {:?} should have been a named type", + parser.name.to_str(), + typedef + ); + } + } else { + panic!( + "Internal error: In {}, there should be a type with that name", + parser.name.to_str() + ); + }; match named_implementation { NamedType::Interface(_) => { - buffer.push_str(&format!("{first_line} + buffer.push_str(&format!( + "{first_line} {{ BinASTKind kind = BinASTKind::_Uninitialized; AutoTaggedTuple guard(*tokenizer_); @@ -2368,42 +2740,46 @@ impl CPPExporter { }} ", - first_line = self.get_method_definition_start(&parser.name, "", "", - &extra_params), + first_line = + self.get_method_definition_start(&parser.name, "", "", &extra_params), null = self.syntax.get_null_name().to_cpp_enum_case(), - call = self.get_method_call("result", - &parser.elements, - "Interface", INTERFACE_ARGS, - &extra_args, - self.get_context_param_for_optional( - &parser.name, - "Interface", &parser.elements, - "context"), - MethodCallKind::AlwaysVar) + call = self + .get_method_call( + "result", + &parser.elements, + "Interface", + INTERFACE_ARGS, + &extra_args, + self.get_context_param_for_optional( + &parser.name, + "Interface", + &parser.elements, + "context" + ), + MethodCallKind::AlwaysVar + ) .reindent(" "), - before = rules_for_this_node.some_before - .map_or_else(|| "".to_string(), - |s| s - .reindent(" ") - .newline_if_not_empty()), - after = rules_for_this_node.some_after - .map_or_else(|| "".to_string(), - |s| s - .reindent(" ") - .newline_if_not_empty()), - none_block = rules_for_this_node.none_replace - .map_or_else(|| format!("result = {default_value};", - default_value = default_value) - .reindent(" "), - |s| s.reindent(" ")), + before = rules_for_this_node.some_before.map_or_else( + || "".to_string(), + |s| s.reindent(" ").newline_if_not_empty() + ), + after = rules_for_this_node.some_after.map_or_else( + || "".to_string(), + |s| s.reindent(" ").newline_if_not_empty() + ), + none_block = rules_for_this_node.none_replace.map_or_else( + || format!("result = {default_value};", default_value = default_value) + .reindent(" "), + |s| s.reindent(" ") + ), type_ok = type_ok, kind = parser.elements.to_cpp_enum_case(), )); } - NamedType::Typedef(ref type_) => { - match type_.spec() { - &TypeSpec::TypeSum(_) => { - buffer.push_str(&format!("{first_line} + NamedType::Typedef(ref type_) => match type_.spec() { + &TypeSpec::TypeSum(_) => { + buffer.push_str(&format!( + "{first_line} {{ BinASTKind kind = BinASTKind::_Uninitialized; AutoTaggedTuple guard(*tokenizer_); @@ -2423,51 +2799,59 @@ impl CPPExporter { }} ", - first_line = self.get_method_definition_start(&parser.name, "", "", - &extra_params), - call = self.get_method_call("result", &parser.elements, - "Sum", SUM_INTERFACE_ARGS, - &extra_args, - self.get_context_param_for_optional( - &parser.name, - "Sum", &parser.elements, - "context"), - MethodCallKind::AlwaysVar) + first_line = + self.get_method_definition_start(&parser.name, "", "", &extra_params), + call = self + .get_method_call( + "result", + &parser.elements, + "Sum", + SUM_INTERFACE_ARGS, + &extra_args, + self.get_context_param_for_optional( + &parser.name, + "Sum", + &parser.elements, + "context" + ), + MethodCallKind::AlwaysVar + ) + .reindent(" "), + before = rules_for_this_node.some_before.map_or_else( + || "".to_string(), + |s| s.reindent(" ").newline_if_not_empty() + ), + after = rules_for_this_node.some_after.map_or_else( + || "".to_string(), + |s| s.reindent(" ").newline_if_not_empty() + ), + none_block = rules_for_this_node.none_replace.map_or_else( + || format!("result = {default_value};", default_value = default_value) .reindent(" "), - before = rules_for_this_node.some_before - .map_or_else(|| "".to_string(), - |s| s - .reindent(" ") - .newline_if_not_empty()), - after = rules_for_this_node.some_after - .map_or_else(|| "".to_string(), - |s| s - .reindent(" ") - .newline_if_not_empty()), - none_block = rules_for_this_node.none_replace - .map_or_else(|| format!("result = {default_value};", - default_value = default_value) - .reindent(" "), - |s| s.reindent(" ")), - type_ok = type_ok, - null = self.syntax.get_null_name().to_cpp_enum_case(), - )); - } - &TypeSpec::String => { - let build_result = rules_for_this_node.init.reindent(" "); - let first_line = self.get_method_definition_start(&parser.name, "", "", - &extra_params); - if build_result.len() == 0 { - buffer.push_str(&format!("{first_line} + |s| s.reindent(" ") + ), + type_ok = type_ok, + null = self.syntax.get_null_name().to_cpp_enum_case(), + )); + } + &TypeSpec::String => { + let build_result = rules_for_this_node.init.reindent(" "); + let first_line = + self.get_method_definition_start(&parser.name, "", "", &extra_params); + if build_result.len() == 0 { + buffer.push_str(&format!( + "{first_line} {{ return raiseError(\"FIXME: Not implemented yet in this preview release ({kind})\"); }} ", - first_line = first_line, - kind = parser.name.to_str())); - } else { - buffer.push_str(&format!("{first_line} + first_line = first_line, + kind = parser.name.to_str() + )); + } else { + buffer.push_str(&format!( + "{first_line} {{ BINJS_MOZ_TRY_DECL(result, tokenizer_->readMaybeAtom(context)); @@ -2477,26 +2861,29 @@ impl CPPExporter { }} ", - first_line = first_line, - build = build_result, - )); - } + first_line = first_line, + build = build_result, + )); } - &TypeSpec::IdentifierName => { - let build_result = rules_for_this_node.init.reindent(" "); - let first_line = self.get_method_definition_start(&parser.name, "", "", - &extra_params); - if build_result.len() == 0 { - buffer.push_str(&format!("{first_line} + } + &TypeSpec::IdentifierName => { + let build_result = rules_for_this_node.init.reindent(" "); + let first_line = + self.get_method_definition_start(&parser.name, "", "", &extra_params); + if build_result.len() == 0 { + buffer.push_str(&format!( + "{first_line} {{ return raiseError(\"FIXME: Not implemented yet in this preview release ({kind})\"); }} ", - first_line = first_line, - kind = parser.name.to_str())); - } else { - buffer.push_str(&format!("{first_line} + first_line = first_line, + kind = parser.name.to_str() + )); + } else { + buffer.push_str(&format!( + "{first_line} {{ BINJS_MOZ_TRY_DECL(result, tokenizer_->readMaybeIdentifierName(context)); @@ -2506,61 +2893,70 @@ impl CPPExporter { }} ", - first_line = first_line, - build = build_result, - )); - } + first_line = first_line, + build = build_result, + )); } - &TypeSpec::PropertyKey => { - debug!(target: "generate_spidermonkey", "Generating method for PropertyKey: {:?}", parser.name); - let build_result = rules_for_this_node.init.reindent(" "); - let first_line = self.get_method_definition_start(&parser.name, "", "", - &extra_params); - if build_result.len() == 0 { - buffer.push_str(&format!("{first_line} + } + &TypeSpec::PropertyKey => { + debug!(target: "generate_spidermonkey", "Generating method for PropertyKey: {:?}", parser.name); + let build_result = rules_for_this_node.init.reindent(" "); + let first_line = + self.get_method_definition_start(&parser.name, "", "", &extra_params); + if build_result.len() == 0 { + buffer.push_str(&format!( + "{first_line} {{ return raiseError(\"FIXME: Not implemented yet in this preview release ({kind})\"); }} ", - first_line = first_line, - kind = parser.name.to_str())); - } else { - panic!("PropertyKey shouldn't be optional"); - } + first_line = first_line, + kind = parser.name.to_str() + )); + } else { + panic!("PropertyKey shouldn't be optional"); } - _else => unimplemented!("{:?}", _else) } - } - NamedType::StringEnum(_) => { - unimplemented!() - } + _else => unimplemented!("{:?}", _else), + }, + NamedType::StringEnum(_) => unimplemented!(), } } - fn generate_implement_interface(&self, buffer: &mut String, name: &NodeName, interface: &Interface) { + fn generate_implement_interface( + &self, + buffer: &mut String, + name: &NodeName, + interface: &Interface, + ) { let rules_for_this_interface = self.rules.get(name); let extra_params = rules_for_this_interface.extra_params; let extra_args = rules_for_this_interface.extra_args; - for &(condition, rule_name) in &[ - (rules_for_this_interface.append.is_some(), "build:"), - ] { + for &(condition, rule_name) in &[(rules_for_this_interface.append.is_some(), "build:")] { if condition { - warn!("In {}, rule `{}` was specified but is ignored.", name, rule_name); + warn!( + "In {}, rule `{}` was specified but is ignored.", + name, rule_name + ); } } if self.refgraph.is_used(name.to_rc_string().clone()) { // Generate comments - let comment = format!(" + let comment = format!( + " /* {}*/ -", ToWebidl::interface(interface, "", " ")); +", + ToWebidl::interface(interface, "", " ") + ); buffer.push_str(&comment); // Generate public method - buffer.push_str(&format!("{first_line} + buffer.push_str(&format!( + "{first_line} {{ BinASTKind kind = BinASTKind::{kind}; AutoTaggedTuple guard(*tokenizer_); @@ -2575,47 +2971,65 @@ impl CPPExporter { }} ", - first_line = self.get_method_definition_start(name, "", "", - &extra_params), + first_line = self.get_method_definition_start(name, "", "", &extra_params), kind = name.to_cpp_enum_case(), - call = self.get_method_call("result", name, - "Interface", INTERFACE_ARGS, - &extra_args, - "context".to_string(), - MethodCallKind::AlwaysDecl) + call = self + .get_method_call( + "result", + name, + "Interface", + INTERFACE_ARGS, + &extra_args, + "context".to_string(), + MethodCallKind::AlwaysDecl + ) .reindent(" ") )); } let inner_prefix = "Interface"; - if !self.refgraph.is_used(Rc::new(format!("{}{}", inner_prefix, name))) { + if !self + .refgraph + .is_used(Rc::new(format!("{}{}", inner_prefix, name))) + { return; } // Generate aux method - let first_line = self.get_method_definition_start(name, inner_prefix, - INTERFACE_PARAMS, - &extra_params); + let first_line = + self.get_method_definition_start(name, inner_prefix, INTERFACE_PARAMS, &extra_params); let mut fields_implem = String::new(); for field in interface.contents().fields() { - let context = format!("FieldContext(BinASTInterfaceAndField::{kind}__{field})", + let context = format!( + "FieldContext(BinASTInterfaceAndField::{kind}__{field})", kind = name.to_cpp_enum_case(), - field = field.name().to_cpp_enum_case()); + field = field.name().to_cpp_enum_case() + ); - let rules_for_this_field = rules_for_this_interface.by_field.get(field.name()) + let rules_for_this_field = rules_for_this_interface + .by_field + .get(field.name()) .cloned() .unwrap_or_default(); - let needs_block = rules_for_this_field.block_before_field.is_some() || rules_for_this_field.block_after_field.is_some(); + let needs_block = rules_for_this_field.block_before_field.is_some() + || rules_for_this_field.block_after_field.is_some(); let var_name = field.name().to_cpp_field_case(); let (decl_var, parse_var) = match field.type_().get_primitive(&self.syntax) { - Some(IsNullable { is_nullable: false, content: Primitive::Number }) => { + Some(IsNullable { + is_nullable: false, + content: Primitive::Number, + }) => { if needs_block { - (Some(format!("double {var_name};", var_name = var_name)), - Some(format!("MOZ_TRY_VAR({var_name}, tokenizer_->readDouble({context}));", + ( + Some(format!("double {var_name};", var_name = var_name)), + Some(format!( + "MOZ_TRY_VAR({var_name}, tokenizer_->readDouble({context}));", var_name = var_name, - context = context))) + context = context + )), + ) } else { (None, Some(format!("BINJS_MOZ_TRY_DECL({var_name}, tokenizer_->readDouble({context}));", @@ -2623,12 +3037,19 @@ impl CPPExporter { context = context))) } } - Some(IsNullable { is_nullable: false, content: Primitive::UnsignedLong }) => { + Some(IsNullable { + is_nullable: false, + content: Primitive::UnsignedLong, + }) => { if needs_block { - (Some(format!("uint32_t {var_name};", var_name = var_name)), - Some(format!("MOZ_TRY_VAR({var_name}, tokenizer_->readUnsignedLong({context}));", + ( + Some(format!("uint32_t {var_name};", var_name = var_name)), + Some(format!( + "MOZ_TRY_VAR({var_name}, tokenizer_->readUnsignedLong({context}));", var_name = var_name, - context = context))) + context = context + )), + ) } else { (None, Some(format!("BINJS_MOZ_TRY_DECL({var_name}, tokenizer_->readUnsignedLong({context}));", @@ -2636,20 +3057,34 @@ impl CPPExporter { context = context))) } } - Some(IsNullable { is_nullable: false, content: Primitive::Boolean }) => { + Some(IsNullable { + is_nullable: false, + content: Primitive::Boolean, + }) => { if needs_block { - (Some(format!("bool {var_name};", var_name = var_name)), - Some(format!("MOZ_TRY_VAR({var_name}, tokenizer_->readBool({context}));", - var_name = var_name, - context = context))) + ( + Some(format!("bool {var_name};", var_name = var_name)), + Some(format!( + "MOZ_TRY_VAR({var_name}, tokenizer_->readBool({context}));", + var_name = var_name, + context = context + )), + ) } else { - (None, - Some(format!("BINJS_MOZ_TRY_DECL({var_name}, tokenizer_->readBool({context}));", - var_name = var_name, - context = context))) + ( + None, + Some(format!( + "BINJS_MOZ_TRY_DECL({var_name}, tokenizer_->readBool({context}));", + var_name = var_name, + context = context + )), + ) } } - Some(IsNullable { is_nullable: false, content: Primitive::Offset }) => { + Some(IsNullable { + is_nullable: false, + content: Primitive::Offset, + }) => { if needs_block { (Some(format!("BinASTTokenReaderBase::SkippableSubTree {var_name};", var_name = var_name)), Some(format!("MOZ_TRY_VAR({var_name}, tokenizer_->readSkippableSubTree({context}));", @@ -2662,67 +3097,110 @@ impl CPPExporter { context = context))) } } - Some(IsNullable { content: Primitive::Void, .. }) => { + Some(IsNullable { + content: Primitive::Void, + .. + }) => { warn!("Internal error: We shouldn't have any `void` types at this stage."); - (Some(format!("// Skipping void field {}", field.name().to_str())), - None) + ( + Some(format!("// Skipping void field {}", field.name().to_str())), + None, + ) } - Some(IsNullable { is_nullable: false, content: Primitive::String }) => { - (Some(format!("RootedAtom {var_name}(cx_);", var_name = var_name)), - Some(format!("MOZ_TRY_VAR({var_name}, tokenizer_->readAtom({context}));", - var_name = var_name, - context = context))) - } - Some(IsNullable { is_nullable: false, content: Primitive::IdentifierName }) => { - (Some(format!("RootedAtom {var_name}(cx_);", var_name = var_name)), - Some(format!("MOZ_TRY_VAR({var_name}, tokenizer_->readIdentifierName({context}));", - var_name = var_name, - context = context))) - } - Some(IsNullable { is_nullable: false, content: Primitive::PropertyKey }) => { - (Some(format!("RootedAtom {var_name}(cx_);", var_name = var_name)), - Some(format!("MOZ_TRY_VAR({var_name}, tokenizer_->readPropertyKey({context}));", - var_name = var_name, - context = context))) - } - Some(IsNullable { is_nullable: true, content: Primitive::String }) => { - (Some(format!("RootedAtom {var_name}(cx_);", var_name = var_name)), - Some(format!("MOZ_TRY_VAR({var_name}, tokenizer_->readMaybeAtom({context}));", - var_name = var_name, - context = context))) - } - Some(IsNullable { is_nullable: true, content: Primitive::IdentifierName }) => { - (Some(format!("RootedAtom {var_name}(cx_);", var_name = var_name)), - Some(format!("MOZ_TRY_VAR({var_name}, tokenizer_->readMaybeIdentifierName({context}));", - var_name = var_name, - context = context))) - } - Some(IsNullable { is_nullable: true, content: Primitive::PropertyKey }) => { + Some(IsNullable { + is_nullable: false, + content: Primitive::String, + }) => ( + Some(format!("RootedAtom {var_name}(cx_);", var_name = var_name)), + Some(format!( + "MOZ_TRY_VAR({var_name}, tokenizer_->readAtom({context}));", + var_name = var_name, + context = context + )), + ), + Some(IsNullable { + is_nullable: false, + content: Primitive::IdentifierName, + }) => ( + Some(format!("RootedAtom {var_name}(cx_);", var_name = var_name)), + Some(format!( + "MOZ_TRY_VAR({var_name}, tokenizer_->readIdentifierName({context}));", + var_name = var_name, + context = context + )), + ), + Some(IsNullable { + is_nullable: false, + content: Primitive::PropertyKey, + }) => ( + Some(format!("RootedAtom {var_name}(cx_);", var_name = var_name)), + Some(format!( + "MOZ_TRY_VAR({var_name}, tokenizer_->readPropertyKey({context}));", + var_name = var_name, + context = context + )), + ), + Some(IsNullable { + is_nullable: true, + content: Primitive::String, + }) => ( + Some(format!("RootedAtom {var_name}(cx_);", var_name = var_name)), + Some(format!( + "MOZ_TRY_VAR({var_name}, tokenizer_->readMaybeAtom({context}));", + var_name = var_name, + context = context + )), + ), + Some(IsNullable { + is_nullable: true, + content: Primitive::IdentifierName, + }) => ( + Some(format!("RootedAtom {var_name}(cx_);", var_name = var_name)), + Some(format!( + "MOZ_TRY_VAR({var_name}, tokenizer_->readMaybeIdentifierName({context}));", + var_name = var_name, + context = context + )), + ), + Some(IsNullable { + is_nullable: true, + content: Primitive::PropertyKey, + }) => { panic!("PropertyKey shouldn't be optional"); } _else => { let typename = TypeName::type_(field.type_()); - let name = self.syntax.get_node_name(typename.to_str()) + let name = self + .syntax + .get_node_name(typename.to_str()) .expect("NodeName for the field type should exist."); let field_extra_args = rules_for_this_field.extra_args; let (decl_var, call_kind) = if needs_block { - (Some(format!("{typename} {var_name};", - var_name = var_name, - typename = typename)), - MethodCallKind::Var) + ( + Some(format!( + "{typename} {var_name};", + var_name = var_name, + typename = typename + )), + MethodCallKind::Var, + ) } else { - (None, - MethodCallKind::Decl) + (None, MethodCallKind::Decl) }; - (decl_var, - Some(self.get_method_call(var_name.to_str(), - &name, "", "", &field_extra_args, - self.get_context_param_for_field( - name, - &context), - call_kind))) + ( + decl_var, + Some(self.get_method_call( + var_name.to_str(), + &name, + "", + "", + &field_extra_args, + self.get_context_param_for_field(name, &context), + call_kind, + )), + ) } }; let rendered = { @@ -2736,8 +3214,7 @@ impl CPPExporter { warn!("In {}, rule `{}` was specified but is ignored because `replace:` is also specified.", name, rule_name); } } - rules_for_this_field.replace.reindent(" ") - .newline() + rules_for_this_field.replace.reindent(" ").newline() } else { let before_field = rules_for_this_field.before_field.reindent(" "); let after_field = rules_for_this_field.after_field.reindent(" "); @@ -2748,27 +3225,34 @@ impl CPPExporter { }; if needs_block { let parse_var = parse_var.reindent(" "); - format!(" + format!( + " {before_field}{decl_var} {{ {block_before_field}{parse_var}{block_after_field} }} {after_field}", before_field = before_field.reindent(" ").newline_if_not_empty(), decl_var = decl_var.reindent(" ").newline_if_not_empty(), - block_before_field = rules_for_this_field.block_before_field.reindent(" ").newline_if_not_empty(), + block_before_field = rules_for_this_field + .block_before_field + .reindent(" ") + .newline_if_not_empty(), parse_var = parse_var.reindent(" ").newline_if_not_empty(), - block_after_field = rules_for_this_field.block_after_field.reindent(" "), + block_after_field = + rules_for_this_field.block_after_field.reindent(" "), after_field = after_field.reindent(" "), ) } else { // We have a before_field and an after_field. This will create newlines // for them. - format!(" + format!( + " {before_field}{decl_var}{parse_var}{after_field}", before_field = before_field.reindent(" ").newline_if_not_empty(), decl_var = decl_var.reindent(" ").newline_if_not_empty(), parse_var = parse_var.reindent(" ").newline_if_not_empty(), - after_field = after_field.reindent(" ")) + after_field = after_field.reindent(" ") + ) } } }; @@ -2779,7 +3263,8 @@ impl CPPExporter { let build_result = rules_for_this_interface.build_result.reindent(" "); if build_result == "" { - buffer.push_str(&format!("{first_line} + buffer.push_str(&format!( + "{first_line} {{ return raiseError(\"FIXME: Not implemented yet in this preview release ({class_name})\"); }} @@ -2789,7 +3274,8 @@ impl CPPExporter { first_line = first_line, )); } else { - buffer.push_str(&format!("{first_line} + buffer.push_str(&format!( + "{first_line} {{ BINJS_TRY(CheckRecursionLimit(cx_)); {pre}{fields_implem} @@ -2816,14 +3302,20 @@ impl CPPExporter { buffer.push_str("\n"); // 1. Typesums - buffer.push_str(" + buffer.push_str( + " // ----- Sums of interfaces (autogenerated, by lexicographical order) -"); - buffer.push_str("// Sums of sums are flattened. -"); +", + ); + buffer.push_str( + "// Sums of sums are flattened. +", + ); - let sums_of_interfaces = self.syntax.resolved_sums_of_interfaces_by_name() + let sums_of_interfaces = self + .syntax + .resolved_sums_of_interfaces_by_name() .iter() .sorted_by(|a, b| a.0.cmp(&b.0)); @@ -2832,13 +3324,17 @@ impl CPPExporter { } // 2. Single interfaces - buffer.push_str(" + buffer.push_str( + " // ----- Interfaces (autogenerated, by lexicographical order) -"); +", + ); buffer.push_str("// When fields have a non-trivial type, implementation is deanonymized and delegated to another parser. "); - let interfaces_by_name = self.syntax.interfaces_by_name() + let interfaces_by_name = self + .syntax + .interfaces_by_name() .iter() .sorted_by(|a, b| str::cmp(a.0.to_str(), b.0.to_str())); @@ -2847,12 +3343,16 @@ impl CPPExporter { } // 3. String Enums - buffer.push_str(" + buffer.push_str( + " // ----- String enums (autogenerated, by lexicographical order) -"); +", + ); { - let string_enums_by_name = self.syntax.string_enums_by_name() + let string_enums_by_name = self + .syntax + .string_enums_by_name() .iter() .sorted_by(|a, b| str::cmp(a.0.to_str(), b.0.to_str())); for (kind, enum_) in string_enums_by_name { @@ -2860,7 +3360,8 @@ impl CPPExporter { continue; } - let convert = format!(" switch (variant) {{ + let convert = format!( + " switch (variant) {{ {cases} default: if (isInvalidVariantPossible()) {{ @@ -2870,33 +3371,38 @@ impl CPPExporter { }} }}", kind = kind, - cases = enum_.strings() + cases = enum_ + .strings() .iter() .map(|symbol| { - format!(" case BinASTVariant::{binastvariant_variant}: + format!( + " case BinASTVariant::{binastvariant_variant}: return {kind}::{specialized_variant};", kind = kind, specialized_variant = symbol.to_cpp_enum_case(), - binastvariant_variant = self.variants_by_symbol.get(symbol) - .unwrap() + binastvariant_variant = + self.variants_by_symbol.get(symbol).unwrap() ) }) .format("\n") ); - let rendered_doc = format!("/* + let rendered_doc = format!( + "/* enum {kind} {{ {cases} }}; */ ", kind = kind, - cases = enum_.strings() - .iter() - .map(|s| format!(" \"{}\"", s)) - .format(",\n") + cases = enum_ + .strings() + .iter() + .map(|s| format!(" \"{}\"", s)) + .format(",\n") ); - buffer.push_str(&format!("{rendered_doc}{first_line} + buffer.push_str(&format!( + "{rendered_doc}{first_line} {{ BINJS_MOZ_TRY_DECL(variant, tokenizer_->readVariant(context)); @@ -2906,26 +3412,29 @@ enum {kind} {{ ", rendered_doc = rendered_doc, convert = convert, - first_line = self.get_method_definition_start(kind, "", "", - &None) + first_line = self.get_method_definition_start(kind, "", "", &None) )); } } // 4. Lists - buffer.push_str(" + buffer.push_str( + " // ----- Lists (autogenerated, by lexicographical order) -"); +", + ); for parser in &self.list_parsers_to_generate { self.generate_implement_list(&mut buffer, parser); } // 5. Optional values - buffer.push_str(" + buffer.push_str( + " // ----- Default values (by lexicographical order) -"); +", + ); for parser in &self.option_parsers_to_generate { self.generate_implement_option(&mut buffer, parser); } @@ -2940,7 +3449,7 @@ enum {kind} {{ fn update_rule(rule: &mut Option, entry: &yaml_rust::Yaml) -> Result, ()> { if entry.is_badvalue() { - return Ok(None) + return Ok(None); } else if let Some(as_str) = entry.as_str() { *rule = Some(as_str.to_string()); Ok(Some(())) @@ -2948,7 +3457,10 @@ fn update_rule(rule: &mut Option, entry: &yaml_rust::Yaml) -> Result>, entry: &yaml_rust::Yaml) -> Result, ()> { +fn update_rule_rc( + rule: &mut Option>, + entry: &yaml_rust::Yaml, +) -> Result, ()> { let mut value = None; let ret = update_rule(&mut value, entry)?; if let Some(s) = value { @@ -2993,22 +3505,20 @@ fn main() { ]) .get_matches(); - let source_path = matches.value_of("INPUT.webidl") + let source_path = matches + .value_of("INPUT.webidl") .expect("Expected INPUT.webidl"); - let mut file = File::open(source_path) - .expect("Could not open source"); + let mut file = File::open(source_path).expect("Could not open source"); let mut source = String::new(); file.read_to_string(&mut source) .expect("Could not read source"); println!("...verifying grammar"); - let mut builder = Importer::import(vec![source.as_ref()]) - .expect("Invalid grammar"); + let mut builder = Importer::import(vec![source.as_ref()]).expect("Invalid grammar"); let fake_root = builder.node_name("@@ROOT@@"); // Unused let null = builder.node_name(""); // Used - builder.add_interface(&null) - .unwrap(); + builder.add_interface(&null).unwrap(); let syntax = builder.into_spec(SpecOptions { root: &fake_root, null: &null, @@ -3023,14 +3533,12 @@ fn main() { let rules_source_path = matches.value_of("INPUT.yaml").unwrap(); println!("...generating rules"); - let mut file = File::open(rules_source_path) - .expect("Could not open rules"); + let mut file = File::open(rules_source_path).expect("Could not open rules"); let mut data = String::new(); file.read_to_string(&mut data) .expect("Could not read rules"); - let yaml = yaml_rust::YamlLoader::load_from_str(&data) - .expect("Could not parse rules"); + let yaml = yaml_rust::YamlLoader::load_from_str(&data).expect("Could not parse rules"); assert_eq!(yaml.len(), 1); let global_rules = GlobalRules::new(&new_syntax, &yaml[0]); @@ -3041,34 +3549,53 @@ fn main() { exporter.collect_context(); let write_to = |description, arg, data: &String| { - let dest_path = matches.value_of(arg) - .unwrap(); - print!("...exporting {description}: {path} ... ", + let dest_path = matches.value_of(arg).unwrap(); + print!( + "...exporting {description}: {path} ... ", description = description, - path = dest_path); + path = dest_path + ); - let mut dest = File::create(&dest_path) - .unwrap_or_else(|e| panic!("Could not create {description} at {path}: {error}", - description = description, - path = dest_path, - error = e)); - dest.write_all(data.as_bytes()) - .unwrap_or_else(|e| panic!("Could not write {description} at {path}: {error}", - description = description, - path = dest_path, - error = e)); + let mut dest = File::create(&dest_path).unwrap_or_else(|e| { + panic!( + "Could not create {description} at {path}: {error}", + description = description, + path = dest_path, + error = e + ) + }); + dest.write_all(data.as_bytes()).unwrap_or_else(|e| { + panic!( + "Could not write {description} at {path}: {error}", + description = description, + path = dest_path, + error = e + ) + }); println!("done"); }; - write_to("C++ class header code", "OUT_HEADER_CLASS_FILE", - &exporter.to_spidermonkey_class_hpp()); - write_to("C++ enum header code", "OUT_HEADER_ENUM_FILE", - &exporter.to_spidermonkey_enum_hpp()); - write_to("C++ token header code", "OUT_TOKEN_FILE", - &exporter.to_spidermonkey_token_hpp()); - write_to("C++ token implementation code", "OUT_IMPL_FILE", - &exporter.to_spidermonkey_cpp()); + write_to( + "C++ class header code", + "OUT_HEADER_CLASS_FILE", + &exporter.to_spidermonkey_class_hpp(), + ); + write_to( + "C++ enum header code", + "OUT_HEADER_ENUM_FILE", + &exporter.to_spidermonkey_enum_hpp(), + ); + write_to( + "C++ token header code", + "OUT_TOKEN_FILE", + &exporter.to_spidermonkey_token_hpp(), + ); + write_to( + "C++ token implementation code", + "OUT_IMPL_FILE", + &exporter.to_spidermonkey_cpp(), + ); println!("...done"); } diff --git a/js/src/frontend/binast/src/refgraph.rs b/js/src/frontend/binast/src/refgraph.rs index 3c8b638103fa..534e3420dc62 100644 --- a/js/src/frontend/binast/src/refgraph.rs +++ b/js/src/frontend/binast/src/refgraph.rs @@ -3,7 +3,7 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cell::RefCell; -use std::collections::{ HashMap, HashSet }; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; /// A node in the reference graph @@ -40,7 +40,7 @@ pub struct ReferenceGraph { impl ReferenceGraph { pub fn new() -> Self { ReferenceGraph { - refnodes: HashMap::new() + refnodes: HashMap::new(), } } @@ -57,8 +57,9 @@ impl ReferenceGraph { let mut next_edges: HashSet> = HashSet::new(); for edge in edges { - let refnode = self.refnodes.get(&edge) - .unwrap_or_else(|| panic!("While computing dependencies, node {} doesn't exist", edge)); + let refnode = self.refnodes.get(&edge).unwrap_or_else(|| { + panic!("While computing dependencies, node {} doesn't exist", edge) + }); if *refnode.used.borrow() { continue; } @@ -83,12 +84,13 @@ impl ReferenceGraph { pub fn is_used(&self, name: Rc) -> bool { match self.refnodes.get(&name) { Some(refnode) => *refnode.used.borrow(), - None => false + None => false, } } /// Insert a node with `name` to the graph. pub fn insert(&mut self, name: Rc, edges: HashSet>) { - self.refnodes.insert(name, Rc::new(ReferenceGraphNode::new(edges))); + self.refnodes + .insert(name, Rc::new(ReferenceGraphNode::new(edges))); } } diff --git a/js/src/lib.rs b/js/src/lib.rs index 20bc3a88b577..597f6e90beef 100644 --- a/js/src/lib.rs +++ b/js/src/lib.rs @@ -3,4 +3,3 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate libz_sys; - diff --git a/js/src/wasm/cranelift/src/bindings/low_level.rs b/js/src/wasm/cranelift/src/bindings/low_level.rs index 1913e102b084..b3e066e0b69e 100644 --- a/js/src/wasm/cranelift/src/bindings/low_level.rs +++ b/js/src/wasm/cranelift/src/bindings/low_level.rs @@ -20,7 +20,6 @@ #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] - // We need to allow dead code because the Rustc compiler complains about variants never being // constructed in TypeCode, which is true because these values come from C++. #![allow(dead_code)] diff --git a/tools/lint/rustfmt.yml b/tools/lint/rustfmt.yml index bd997d0afe72..7fe792d6c3db 100644 --- a/tools/lint/rustfmt.yml +++ b/tools/lint/rustfmt.yml @@ -4,7 +4,7 @@ rust: include: - build/workspace-hack/ - gfx/wr/peek-poke/peek-poke-derive/ - - js/src/rust/shared/ + - js/ - security/manager/ssl/osclientcerts/ - servo/components/size_of_test/ - servo/components/to_shmem_derive/ @@ -23,9 +23,6 @@ rust: - gfx/wr/peek-poke/ - gfx/wr/webrender_build/ - gfx/wr/wr_malloc_size_of/ - - js/src/ - - js/src/frontend/binast/ - - js/src/wasm/cranelift/ - media/mp4parse-rust/mp4parse/ - media/mp4parse-rust/mp4parse_capi/ - media/mp4parse-rust/mp4parse_fallible/