diff --git a/Cargo.lock b/Cargo.lock index 3551e3bf1866..8770e9e71ac2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -171,6 +171,26 @@ dependencies = [ "serde 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "bindgen" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "aster 0.41.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cexpr 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "clang-sys 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.20.5 (registry+https://github.com/rust-lang/crates.io-index)", + "env_logger 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", + "peeking_take_while 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "quasi 0.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "quasi_codegen 0.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "regex 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_syntax 0.58.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "bindgen" version = "0.29.0" @@ -1453,15 +1473,18 @@ dependencies = [ [[package]] name = "js" -version = "0.1.6" -source = "git+https://github.com/servo/rust-mozjs#3de4ff3d52361a47a17e3b4fcb02c779b99d93d4" +version = "0.1.4" +source = "git+https://github.com/fitzgen/mozjs?branch=smup#182973d9a81797bec97a001b229d3def0f5ee774" dependencies = [ + "bindgen 0.26.3 (registry+https://github.com/rust-lang/crates.io-index)", "cmake 0.1.22 (registry+https://github.com/rust-lang/crates.io-index)", + "env_logger 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", + "glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "heapsize 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", - "mozjs_sys 0.0.0 (git+https://github.com/servo/mozjs)", + "mozjs_sys 0.0.0 (git+https://github.com/fitzgen/mozjs?branch=smup)", "num-traits 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1844,10 +1867,11 @@ dependencies = [ [[package]] name = "mozjs_sys" version = "0.0.0" -source = "git+https://github.com/servo/mozjs#834ce35c3f008010213351107b68f397989d2ffd" +source = "git+https://github.com/fitzgen/mozjs?branch=smup#182973d9a81797bec97a001b229d3def0f5ee774" dependencies = [ "libc 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", "libz-sys 1.0.16 (registry+https://github.com/rust-lang/crates.io-index)", + "num_cpus 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2539,7 +2563,7 @@ dependencies = [ "hyper_serde 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "image 0.12.4 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", - "js 0.1.6 (git+https://github.com/servo/rust-mozjs)", + "js 0.1.4 (git+https://github.com/fitzgen/mozjs?branch=smup)", "jstraceable_derive 0.0.1", "lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3711,6 +3735,7 @@ dependencies = [ "checksum base64 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "30e93c03064e7590d0466209155251b90c22e37fab1daf2771582598b5827557" "checksum binary-space-partition 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "88ceb0d16c4fd0e42876e298d7d3ce3780dd9ebdcbe4199816a32c77e08597ff" "checksum bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e103c8b299b28a9c6990458b7013dc4a8356a9b854c51b9883241f5866fac36e" +"checksum bindgen 0.26.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c57d6c0f6e31f8dcf4d12720a3c2a9ffb70638772a5784976cf4fce52145f22a" "checksum bindgen 0.29.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0c338079dafc81bef7d581f494b906603d12359c4306979eae6ca081925a4984" "checksum bit-set 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d9bf6104718e80d7b26a68fdbacff3481cfc05df670821affc7e9cbc1884400c" "checksum bit-vec 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "5b97c2c8e8bbb4251754f559df8af22fb264853c7d009084a576cdf12565089d" @@ -3822,7 +3847,7 @@ dependencies = [ "checksum itertools 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4833d6978da405305126af4ac88569b5d71ff758581ce5a987dbfa3755f694fc" "checksum itoa 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "eb2f404fbc66fd9aac13e998248505e7ecb2ad8e44ab6388684c5fb11c6c251c" "checksum jpeg-decoder 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "2805ccb10ffe4d10e06ef68a158ff94c255211ecbae848fbde2146b098f93ce7" -"checksum js 0.1.6 (git+https://github.com/servo/rust-mozjs)" = "" +"checksum js 0.1.4 (git+https://github.com/fitzgen/mozjs?branch=smup)" = "" "checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" "checksum khronos_api 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d5a08e2a31d665af8f1ca437eab6d00a93c9d62a549f73f9ed8fc2e55b5a91a7" "checksum language-tags 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a91d884b6667cd606bb5a69aa0c99ba811a115fc68915e7056ec08a46e93199a" @@ -3847,7 +3872,7 @@ dependencies = [ "checksum miniz-sys 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "28eaee17666671fa872e567547e8428e83308ebe5808cdf6a0e28397dbe2c726" "checksum mio 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)" = "9e965267d4d58496fc4f740e9861118367f13570cadf66316ed2c3f2f14d87c7" "checksum miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" -"checksum mozjs_sys 0.0.0 (git+https://github.com/servo/mozjs)" = "" +"checksum mozjs_sys 0.0.0 (git+https://github.com/fitzgen/mozjs?branch=smup)" = "" "checksum mp3-metadata 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2f61cf32f7fc3cec83a15a255ac60bceb6cac59a7ce190cb824ca25c0fce0feb" "checksum mp4parse 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7b81651f9ede53d59281b54c7eb51ae50a868ac4765dd3bdfbbc79ce3d8aca7a" "checksum multistr 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "60a0c9d992b79e7385ced5a7cbda426d9129de49b4e8d4ac224d3f175a631b7d" diff --git a/Cargo.toml b/Cargo.toml index a8396d3480eb..80cd060d24f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ members = [ ] [profile.dev] -codegen-units = 4 +codegen-units = 48 [profile.release] opt-level = 3 diff --git a/components/domobject_derive/lib.rs b/components/domobject_derive/lib.rs index c718b514fc5f..961607787545 100644 --- a/components/domobject_derive/lib.rs +++ b/components/domobject_derive/lib.rs @@ -39,7 +39,7 @@ fn expand_string(input: &str) -> String { #[allow(unsafe_code)] unsafe fn to_jsval(&self, cx: *mut ::js::jsapi::JSContext, - rval: ::js::jsapi::MutableHandleValue) { + rval: ::js::jsapi::JS::MutableHandleValue) { let object = ::dom::bindings::reflector::DomObject::reflector(self).get_jsobject(); object.to_jsval(cx, rval) } diff --git a/components/script/Cargo.toml b/components/script/Cargo.toml index 60f723055ffb..8d56236498f9 100644 --- a/components/script/Cargo.toml +++ b/components/script/Cargo.toml @@ -50,7 +50,7 @@ hyper = "0.10" hyper_serde = "0.7" image = "0.12" ipc-channel = "0.8" -js = {git = "https://github.com/servo/rust-mozjs", features = ["promises"]} +js = { git = "https://github.com/fitzgen/mozjs", branch = "smup", features = ["promises"] } jstraceable_derive = {path = "../jstraceable_derive"} lazy_static = "0.2" libc = "0.2" diff --git a/components/script/body.rs b/components/script/body.rs index 19a38cfe9f8e..00e2db64220f 100644 --- a/components/script/body.rs +++ b/components/script/body.rs @@ -11,10 +11,7 @@ use dom::blob::{Blob, BlobImpl}; use dom::formdata::FormData; use dom::globalscope::GlobalScope; use dom::promise::Promise; -use js::jsapi::JSContext; -use js::jsapi::JS_ClearPendingException; -use js::jsapi::JS_ParseJSON; -use js::jsapi::Value as JSValue; +use js::jsapi; use js::jsval::UndefinedValue; use mime::{Mime, TopLevel, SubLevel}; use std::cell::Ref; @@ -32,7 +29,7 @@ pub enum BodyType { pub enum FetchedData { Text(String), - Json(JSValue), + Json(jsapi::JS::Value), BlobData(Root), FormData(Root), } @@ -112,17 +109,17 @@ fn run_text_data_algorithm(bytes: Vec) -> Fallible { } #[allow(unsafe_code)] -fn run_json_data_algorithm(cx: *mut JSContext, +fn run_json_data_algorithm(cx: *mut jsapi::JSContext, bytes: Vec) -> Fallible { let json_text = String::from_utf8_lossy(&bytes); let json_text: Vec = json_text.encode_utf16().collect(); rooted!(in(cx) let mut rval = UndefinedValue()); unsafe { - if !JS_ParseJSON(cx, + if !jsapi::JS_ParseJSON(cx, json_text.as_ptr(), json_text.len() as u32, rval.handle_mut()) { - JS_ClearPendingException(cx); + jsapi::JS_ClearPendingException(cx); // TODO: See issue #13464. Exception should be thrown instead of cleared. return Err(Error::Type("Failed to parse JSON".to_string())); } diff --git a/components/script/build.rs b/components/script/build.rs index a19e286ba250..2ed119943e39 100644 --- a/components/script/build.rs +++ b/components/script/build.rs @@ -54,7 +54,11 @@ fn main() { } let phf = PathBuf::from(env::var("OUT_DIR").unwrap()).join("InterfaceObjectMapPhf.rs"); let mut phf = File::create(&phf).unwrap(); - write!(&mut phf, "pub static MAP: phf::Map<&'static [u8], unsafe fn(*mut JSContext, HandleObject)> = ").unwrap(); + write!(&mut phf, + "pub static MAP: phf::Map<\ + &'static [u8],\ + unsafe fn(*mut jsapi::JSContext, jsapi::JS::HandleObject)\ + > = ").unwrap(); map.build(&mut phf).unwrap(); write!(&mut phf, ";\n").unwrap(); } diff --git a/components/script/devtools.rs b/components/script/devtools.rs index 7172f2bdf9d9..42e630cab0c7 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -22,7 +22,8 @@ use dom::globalscope::GlobalScope; use dom::node::{Node, window_from_node}; use dom::window::Window; use ipc_channel::ipc::IpcSender; -use js::jsapi::{JSAutoCompartment, ObjectClassName}; +use js::ac::AutoCompartment; +use js::jsapi; use js::jsval::UndefinedValue; use msg::constellation_msg::PipelineId; use script_thread::Documents; @@ -34,11 +35,11 @@ use uuid::Uuid; #[allow(unsafe_code)] pub fn handle_evaluate_js(global: &GlobalScope, eval: String, reply: IpcSender) { - // global.get_cx() returns a valid `JSContext` pointer, so this is safe. + // global.get_cx() returns a valid `jsapi::JSContext` pointer, so this is safe. let result = unsafe { let cx = global.get_cx(); let globalhandle = global.reflector().get_jsobject(); - let _ac = JSAutoCompartment::new(cx, globalhandle.get()); + let _ac = AutoCompartment::with_obj(cx, globalhandle.get()); rooted!(in(cx) let mut rval = UndefinedValue()); global.evaluate_js_on_global_with_result(&eval, rval.handle_mut()); @@ -60,7 +61,7 @@ pub fn handle_evaluate_js(global: &GlobalScope, eval: String, reply: IpcSender JSTraceable for JS { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { trace_reflector(trc, "", unsafe { (**self.ptr).reflector() }); } } diff --git a/components/script/dom/abstractworker.rs b/components/script/dom/abstractworker.rs index fec714956130..ee68e2770611 100644 --- a/components/script/dom/abstractworker.rs +++ b/components/script/dom/abstractworker.rs @@ -5,7 +5,7 @@ use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::DomObject; use dom::bindings::structuredclone::StructuredCloneData; -use js::jsapi::{JSRuntime, JS_RequestInterruptCallback}; +use js::jsapi; use js::rust::Runtime; use script_runtime::CommonScriptMsg; @@ -31,20 +31,20 @@ impl SimpleWorkerErrorHandler { #[derive(Clone, Copy)] pub struct SharedRt { - rt: *mut JSRuntime + cx: *mut jsapi::JSContext } impl SharedRt { pub fn new(rt: &Runtime) -> SharedRt { SharedRt { - rt: rt.rt() + cx: rt.cx() } } #[allow(unsafe_code)] pub fn request_interrupt(&self) { unsafe { - JS_RequestInterruptCallback(self.rt); + jsapi::JS_RequestInterruptCallback(self.cx); } } } diff --git a/components/script/dom/bindings/callback.rs b/components/script/dom/bindings/callback.rs index 4dfb6584989d..9252b14acf2e 100644 --- a/components/script/dom/bindings/callback.rs +++ b/components/script/dom/bindings/callback.rs @@ -10,12 +10,10 @@ use dom::bindings::reflector::DomObject; use dom::bindings::settings_stack::{AutoEntryScript, AutoIncumbentScript}; use dom::bindings::utils::AsCCharPtrPtr; use dom::globalscope::GlobalScope; -use js::jsapi::{Heap, MutableHandleObject}; -use js::jsapi::{IsCallable, JSContext, JSObject, JS_WrapObject, AddRawValueRoot}; -use js::jsapi::{JSCompartment, JS_EnterCompartment, JS_LeaveCompartment, RemoveRawValueRoot}; -use js::jsapi::JSAutoCompartment; -use js::jsapi::JS_GetProperty; -use js::jsval::{JSVal, UndefinedValue, ObjectValue}; +use js::ac::AutoCompartment; +use js::heap::Heap; +use js::jsapi; +use js::jsval::{UndefinedValue, ObjectValue}; use js::rust::Runtime; use std::default::Default; use std::ffi::CString; @@ -38,9 +36,9 @@ pub enum ExceptionHandling { #[derive(JSTraceable)] #[must_root] pub struct CallbackObject { - /// The underlying `JSObject`. - callback: Heap<*mut JSObject>, - permanent_js_root: Heap, + /// The underlying `jsapi::JSObject`. + callback: Heap<*mut jsapi::JSObject>, + permanent_js_root: Heap, /// The ["callback context"], that is, the global to use as incumbent /// global when calling the callback. @@ -73,16 +71,16 @@ impl CallbackObject { } } - pub fn get(&self) -> *mut JSObject { + pub fn get(&self) -> *mut jsapi::JSObject { self.callback.get() } #[allow(unsafe_code)] - unsafe fn init(&mut self, cx: *mut JSContext, callback: *mut JSObject) { + unsafe fn init(&mut self, cx: *mut jsapi::JSContext, callback: *mut jsapi::JSObject) { self.callback.set(callback); self.permanent_js_root.set(ObjectValue(callback)); - assert!(AddRawValueRoot(cx, self.permanent_js_root.get_unsafe(), - b"CallbackObject::root\n".as_c_char_ptr())); + assert!(jsapi::js::AddRawValueRoot(cx, self.permanent_js_root.get_unsafe(), + b"CallbackObject::root\n".as_c_char_ptr())); } } @@ -91,7 +89,7 @@ impl Drop for CallbackObject { fn drop(&mut self) { unsafe { let cx = Runtime::get(); - RemoveRawValueRoot(cx, self.permanent_js_root.get_unsafe()); + jsapi::js::RemoveRawValueRoot(cx, self.permanent_js_root.get_unsafe()); } } @@ -107,12 +105,12 @@ impl PartialEq for CallbackObject { /// A trait to be implemented by concrete IDL callback function and /// callback interface types. pub trait CallbackContainer { - /// Create a new CallbackContainer object for the given `JSObject`. - unsafe fn new(cx: *mut JSContext, callback: *mut JSObject) -> Rc; + /// Create a new CallbackContainer object for the given `jsapi::JSObject`. + unsafe fn new(cx: *mut jsapi::JSContext, callback: *mut jsapi::JSObject) -> Rc; /// Returns the underlying `CallbackObject`. fn callback_holder(&self) -> &CallbackObject; - /// Returns the underlying `JSObject`. - fn callback(&self) -> *mut JSObject { + /// Returns the underlying `jsapi::JSObject`. + fn callback(&self) -> *mut jsapi::JSObject { self.callback_holder().get() } /// Returns the ["callback context"], that is, the global to use as @@ -148,7 +146,7 @@ impl CallbackFunction { /// Initialize the callback function with a value. /// Should be called once this object is done moving. - pub unsafe fn init(&mut self, cx: *mut JSContext, callback: *mut JSObject) { + pub unsafe fn init(&mut self, cx: *mut jsapi::JSContext, callback: *mut jsapi::JSObject) { self.object.init(cx, callback); } } @@ -164,7 +162,7 @@ pub struct CallbackInterface { } impl CallbackInterface { - /// Create a new CallbackInterface object for the given `JSObject`. + /// Create a new CallbackInterface object for the given `jsapi::JSObject`. pub fn new() -> CallbackInterface { CallbackInterface { object: CallbackObject::new(), @@ -178,22 +176,22 @@ impl CallbackInterface { /// Initialize the callback function with a value. /// Should be called once this object is done moving. - pub unsafe fn init(&mut self, cx: *mut JSContext, callback: *mut JSObject) { + pub unsafe fn init(&mut self, cx: *mut jsapi::JSContext, callback: *mut jsapi::JSObject) { self.object.init(cx, callback); } /// Returns the property with the given `name`, if it is a callable object, /// or an error otherwise. - pub fn get_callable_property(&self, cx: *mut JSContext, name: &str) -> Fallible { + pub fn get_callable_property(&self, cx: *mut jsapi::JSContext, name: &str) -> Fallible { rooted!(in(cx) let mut callable = UndefinedValue()); rooted!(in(cx) let obj = self.callback_holder().get()); unsafe { let c_name = CString::new(name).unwrap(); - if !JS_GetProperty(cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) { + if !jsapi::JS_GetProperty(cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) { return Err(Error::JSFailed); } - if !callable.is_object() || !IsCallable(callable.to_object()) { + if !callable.is_object() || !jsapi::JS::IsCallable(callable.to_object()) { return Err(Error::Type(format!("The value of the {} property is not callable", name))); } @@ -204,14 +202,14 @@ impl CallbackInterface { /// Wraps the reflector for `p` into the compartment of `cx`. -pub fn wrap_call_this_object(cx: *mut JSContext, +pub fn wrap_call_this_object(cx: *mut jsapi::JSContext, p: &T, - rval: MutableHandleObject) { + rval: jsapi::JS::MutableHandleObject) { rval.set(p.reflector().get_jsobject().get()); assert!(!rval.get().is_null()); unsafe { - if !JS_WrapObject(cx, rval) { + if !jsapi::JS_WrapObject(cx, rval) { rval.set(ptr::null_mut()); } } @@ -224,10 +222,10 @@ pub struct CallSetup { /// The global for reporting exceptions. This is the global object of the /// (possibly wrapped) callback object. exception_global: Root, - /// The `JSContext` used for the call. - cx: *mut JSContext, + /// The `jsapi::JSContext` used for the call. + cx: *mut jsapi::JSContext, /// The compartment we were in before the call. - old_compartment: *mut JSCompartment, + old_compartment: *mut jsapi::JSCompartment, /// The exception handling used for the call. handling: ExceptionHandling, /// https://heycam.github.io/webidl/#es-invoking-callback-functions @@ -252,15 +250,15 @@ impl CallSetup { CallSetup { exception_global: global, cx: cx, - old_compartment: unsafe { JS_EnterCompartment(cx, callback.callback()) }, + old_compartment: unsafe { jsapi::JS_EnterCompartment(cx, callback.callback()) }, handling: handling, entry_script: Some(aes), incumbent_script: ais, } } - /// Returns the `JSContext` used for the call. - pub fn get_context(&self) -> *mut JSContext { + /// Returns the `jsapi::JSContext` used for the call. + pub fn get_context(&self) -> *mut jsapi::JSContext { self.cx } } @@ -268,10 +266,10 @@ impl CallSetup { impl Drop for CallSetup { fn drop(&mut self) { unsafe { - JS_LeaveCompartment(self.cx, self.old_compartment); + jsapi::JS_LeaveCompartment(self.cx, self.old_compartment); if self.handling == ExceptionHandling::Report { - let _ac = JSAutoCompartment::new(self.cx, - self.exception_global.reflector().get_jsobject().get()); + let _ac = AutoCompartment::with_obj(self.cx, + self.exception_global.reflector().get_jsobject().get()); report_pending_exception(self.cx, true); } drop(self.incumbent_script.take()); diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 7f97868a3788..ebb0f8b65949 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -450,7 +450,7 @@ def pickFirstSignature(condition, filterLambda): pickFirstSignature("%s.get().is_object() && " "{ rooted!(in(cx) let obj = %s.get().to_object()); " "let mut is_date = false; " - "assert!(JS_ObjectIsDate(cx, obj.handle(), &mut is_date)); " + "assert!(jsapi::JS_ObjectIsDate(cx, obj.handle(), &mut is_date)); " "is_date }" % (distinguishingArg, distinguishingArg), lambda s: (s[1][distinguishingIndex].type.isDate() or @@ -542,7 +542,7 @@ def __init__(self, template, default=None, declType=None): template: A string representing the conversion code. This will have template substitution performed on it as follows: - ${val} is a handle to the JS::Value in question + ${val} is a handle to the jsapi::JS::Value in question default: A string or None representing rust code for default value(if any). @@ -607,7 +607,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, 1) A string representing the conversion code. This will have template substitution performed on it as follows: - ${val} replaced by an expression for the JS::Value in question + ${val} replaced by an expression for the jsapi::JS::Value in question 2) A string or None representing Rust code for the default value (if any). @@ -781,11 +781,11 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, """ { // Scope for our JSAutoCompartment. - rooted!(in(cx) let globalObj = CurrentGlobalOrNull(cx)); + rooted!(in(cx) let globalObj = jsapi::JS::CurrentGlobalOrNull(cx)); let promiseGlobal = GlobalScope::from_object_maybe_wrapped(globalObj.handle().get()); rooted!(in(cx) let mut valueToResolve = $${val}.get()); - if !JS_WrapValue(cx, valueToResolve.handle_mut()) { + if !jsapi::JS_WrapValue(cx, valueToResolve.handle_mut()) { $*{exceptionCode} } match Promise::Resolve(&promiseGlobal, cx, valueToResolve.handle()) { @@ -1015,7 +1015,7 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, else: template = conversion else: - template = CGIfElseWrapper("IsCallable(${val}.get().to_object())", + template = CGIfElseWrapper("jsapi::JS::IsCallable(${val}.get().to_object())", conversion, onFailureNotCallable(failureCode)).define() template = wrapObjectTemplate( @@ -1043,7 +1043,7 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, if isMember == "Dictionary": # TODO: Need to properly root dictionaries # https://github.com/servo/servo/issues/6381 - declType = CGGeneric("Heap") + declType = CGGeneric("Heap") if defaultValue is None: default = None @@ -1055,14 +1055,14 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, raise TypeError("Can't handle non-null, non-undefined default value here") return handleOptional("Heap::new(${val}.get())", declType, default) - declType = CGGeneric("HandleValue") + declType = CGGeneric("jsapi::JS::HandleValue") if defaultValue is None: default = None elif isinstance(defaultValue, IDLNullValue): - default = "HandleValue::null()" + default = "jsapi::JS::HandleValue::null()" elif isinstance(defaultValue, IDLUndefinedValue): - default = "HandleValue::undefined()" + default = "jsapi::JS::HandleValue::undefined()" else: raise TypeError("Can't handle non-null, non-undefined default value here") @@ -1079,13 +1079,13 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, isDefinitelyObject, type, failureCode) if isMember in ("Dictionary", "Union"): - declType = CGGeneric("Heap<*mut JSObject>") - templateBody = "Heap::new(%s)" % templateBody - default = "Heap::new(%s)" % default + declType = CGGeneric("js::heap::Heap<*mut jsapi::JSObject>") + templateBody = "js::heap::Heap::new(%s)" % templateBody + default = "js::heap::Heap::new(%s)" % default else: # TODO: Need to root somehow # https://github.com/servo/servo/issues/6382 - declType = CGGeneric("*mut JSObject") + declType = CGGeneric("*mut jsapi::JSObject") return handleOptional(templateBody, declType, handleDefaultNull(default)) @@ -1411,9 +1411,9 @@ def getRetvalDeclarationForType(returnType, descriptorProvider): # TODO: Return the value through a MutableHandleValue outparam # https://github.com/servo/servo/issues/6307 if returnType.isAny(): - return CGGeneric("JSVal") + return CGGeneric("jsapi::JS::Value") if returnType.isObject() or returnType.isSpiderMonkeyInterface(): - result = CGGeneric("NonZero<*mut JSObject>") + result = CGGeneric("NonZero<*mut jsapi::JSObject>") if returnType.nullable(): result = CGWrapper(result, pre="Option<", post=">") return result @@ -1530,17 +1530,21 @@ def generateGuardedArray(self, array, name, specTemplate, specTerminator, currentSpecs = [specTemplate % getDataTuple(m) for m in members] if specTerminator: currentSpecs.append(specTerminator) - specs.append("&[\n" + ",\n".join(currentSpecs) + "]\n") + specs.append("&leak_as_static([\n" + ",\n".join(currentSpecs) + "])[..]\n") prefableSpecs.append( prefableTemplate % (cond, name + "_specs", len(specs) - 1)) - specsArray = ("const %s_specs: &'static [&'static[%s]] = &[\n" + - ",\n".join(specs) + "\n" + - "];\n") % (name, specType) - - prefArray = ("const %s: &'static [Guard<&'static [%s]>] = &[\n" + - ",\n".join(prefableSpecs) + "\n" + - "];\n") % (name, specType) + specsArray = ("lazy_static! {\n" + " pub static ref %s_specs: &'static [&'static[%s]] = &leak_as_static([\n" + " %s,\n" + " ])[..];\n" + "}\n") % (name, specType, ",\n".join(specs)) + + prefArray = ("lazy_static! {\n" + " pub static ref %s: &'static [Guard<&'static [%s]>] = &leak_as_static([\n" + " %s,\n" + " ])[..];\n" + "}\n") % (name, specType, ",\n".join(prefableSpecs)) return specsArray + prefArray @@ -1646,53 +1650,47 @@ def generateArray(self, array, name): def condition(m, d): return m["condition"] - flags = "JSPROP_ENUMERATE" + flags = "jsapi::JSPROP_ENUMERATE" if self.unforgeable: - flags += " | JSPROP_PERMANENT | JSPROP_READONLY" + flags += " | jsapi::JSPROP_PERMANENT | jsapi::JSPROP_READONLY" def specData(m): - # TODO: Use something like JS_FNSPEC + # TODO: Use something like jsapi::JS_FNSPEC # https://github.com/servo/servo/issues/6391 if "selfHostedName" in m: selfHostedName = '%s as *const u8 as *const libc::c_char' % str_to_const_array(m["selfHostedName"]) assert not m.get("methodInfo", True) accessor = "None" - jitinfo = "0 as *const JSJitInfo" + jitinfo = "0 as *const jsapi::JSJitInfo" else: selfHostedName = "0 as *const libc::c_char" if m.get("methodInfo", True): identifier = m.get("nativeName", m["name"]) # Go through an intermediate type here, because it's not - # easy to tell whether the methodinfo is a JSJitInfo or - # a JSTypedMethodJitInfo here. The compiler knows, though, + # easy to tell whether the methodinfo is a jsapi::JSJitInfo or + # a jsapi::JSTypedMethodJitInfo here. The compiler knows, though, # so let it do the work. - jitinfo = "&%s_methodinfo as *const _ as *const JSJitInfo" % identifier + jitinfo = "&*%s_methodinfo as *const _ as *const jsapi::JSJitInfo" % identifier accessor = "Some(generic_method)" else: - jitinfo = "0 as *const JSJitInfo" + jitinfo = "0 as *const jsapi::JSJitInfo" accessor = 'Some(%s)' % m.get("nativeName", m["name"]) if m["name"].startswith("@@"): - return ('(SymbolCode::%s as i32 + 1)' + return ('(jsapi::JS::SymbolCode::%s as i32 + 1)' % m["name"][2:], accessor, jitinfo, m["length"], flags, selfHostedName) return (str_to_const_array(m["name"]), accessor, jitinfo, m["length"], flags, selfHostedName) return self.generateGuardedArray( array, name, - ' JSFunctionSpec {\n' + ' jsapi::JSFunctionSpec {\n' ' name: %s as *const u8 as *const libc::c_char,\n' - ' call: JSNativeWrapper { op: %s, info: %s },\n' + ' call: jsapi::JSNativeWrapper { op: %s, info: %s },\n' ' nargs: %s,\n' ' flags: (%s) as u16,\n' ' selfHostedName: %s\n' ' }', - ' JSFunctionSpec {\n' - ' name: 0 as *const libc::c_char,\n' - ' call: JSNativeWrapper { op: None, info: 0 as *const JSJitInfo },\n' - ' nargs: 0,\n' - ' flags: 0,\n' - ' selfHostedName: 0 as *const libc::c_char\n' - ' }', - 'JSFunctionSpec', + ' unsafe { mem::zeroed() }\n', + 'jsapi::JSFunctionSpec', condition, specData) @@ -1715,41 +1713,45 @@ def generateArray(self, array, name): if len(array) == 0: return "" - flags = "JSPROP_ENUMERATE | JSPROP_SHARED" + flags = "jsapi::JSPROP_ENUMERATE | jsapi::JSPROP_SHARED" if self.unforgeable: - flags += " | JSPROP_PERMANENT" + flags += " | jsapi::JSPROP_PERMANENT" def getter(attr): if self.static: accessor = 'get_' + self.descriptor.internalNameFor(attr.identifier.name) - jitinfo = "0 as *const JSJitInfo" + jitinfo = "0 as *const jsapi::JSJitInfo" else: if attr.hasLenientThis(): accessor = "generic_lenient_getter" else: accessor = "generic_getter" - jitinfo = "&%s_getterinfo" % self.descriptor.internalNameFor(attr.identifier.name) + jitinfo = "&*%s_getterinfo as *const jsapi::JSJitInfo" % ( + self.descriptor.internalNameFor(attr.identifier.name) + ) - return ("JSNativeWrapper { op: Some(%(native)s), info: %(info)s }" + return ("jsapi::JSNativeWrapper { op: Some(%(native)s), info: %(info)s }" % {"info": jitinfo, "native": accessor}) def setter(attr): if (attr.readonly and not attr.getExtendedAttribute("PutForwards") and not attr.getExtendedAttribute("Replaceable")): - return "JSNativeWrapper { op: None, info: 0 as *const JSJitInfo }" + return "jsapi::JSNativeWrapper { op: None, info: 0 as *const jsapi::JSJitInfo }" if self.static: accessor = 'set_' + self.descriptor.internalNameFor(attr.identifier.name) - jitinfo = "0 as *const JSJitInfo" + jitinfo = "0 as *const jsapi::JSJitInfo" else: if attr.hasLenientThis(): accessor = "generic_lenient_setter" else: accessor = "generic_setter" - jitinfo = "&%s_setterinfo" % self.descriptor.internalNameFor(attr.identifier.name) + jitinfo = "&*%s_setterinfo as *const jsapi::JSJitInfo" % ( + self.descriptor.internalNameFor(attr.identifier.name) + ) - return ("JSNativeWrapper { op: Some(%(native)s), info: %(info)s }" + return ("jsapi::JSNativeWrapper { op: Some(%(native)s), info: %(info)s }" % {"info": jitinfo, "native": accessor}) @@ -1759,19 +1761,18 @@ def specData(attr): return self.generateGuardedArray( array, name, - ' JSPropertySpec {\n' + ' jsapi::JSPropertySpec {\n' ' name: %s as *const u8 as *const libc::c_char,\n' ' flags: (%s) as u8,\n' - ' getter: %s,\n' - ' setter: %s\n' - ' }', - ' JSPropertySpec {\n' - ' name: 0 as *const libc::c_char,\n' - ' flags: 0,\n' - ' getter: JSNativeWrapper { op: None, info: 0 as *const JSJitInfo },\n' - ' setter: JSNativeWrapper { op: None, info: 0 as *const JSJitInfo }\n' - ' }', - 'JSPropertySpec', + ' __bindgen_anon_1: jsapi::JSPropertySpec__bindgen_ty_1 {\n' + ' accessors: jsapi::JSPropertySpec__bindgen_ty_1__bindgen_ty_1 {\n' + ' getter: jsapi::JSPropertySpec__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 { native: %s },\n' + ' setter: jsapi::JSPropertySpec__bindgen_ty_1__bindgen_ty_1__bindgen_ty_2 { native: %s }\n' + ' }\n' + ' }\n' + ' }\n', + ' unsafe { mem::zeroed() }\n', + 'jsapi::JSPropertySpec', PropertyDefiner.getControllingCondition, specData) @@ -2072,11 +2073,11 @@ def define(self): args["flags"] = "JSCLASS_IS_GLOBAL | JSCLASS_DOM_GLOBAL" args["slots"] = "JSCLASS_GLOBAL_SLOT_COUNT + 1" args["resolveHook"] = "Some(resolve_global)" - args["traceHook"] = "js::jsapi::JS_GlobalObjectTraceHook" + args["traceHook"] = "jsapi::JS_GlobalObjectTraceHook" elif self.descriptor.weakReferenceable: args["slots"] = "2" return """\ -static CLASS_OPS: js::jsapi::JSClassOps = js::jsapi::JSClassOps { +static CLASS_OPS: jsapi::JSClassOps = jsapi::JSClassOps { addProperty: None, delProperty: None, getProperty: None, @@ -2092,11 +2093,11 @@ def define(self): }; static Class: DOMJSClass = DOMJSClass { - base: js::jsapi::JSClass { + base: jsapi::JSClass { name: %(name)s as *const u8 as *const libc::c_char, - flags: JSCLASS_IS_DOMJSCLASS | %(flags)s | - (((%(slots)s) & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT) - /* JSCLASS_HAS_RESERVED_SLOTS(%(slots)s) */, + flags: jsapi::JSCLASS_IS_DOMJSCLASS | jsapi::JSCLASS_FOREGROUND_FINALIZE | %(flags)s | + (((%(slots)s) & jsapi::JSCLASS_RESERVED_SLOTS_MASK) << jsapi::JSCLASS_RESERVED_SLOTS_SHIFT) + /* jsapi::JSCLASS_HAS_RESERVED_SLOTS(%(slots)s) */, cOps: &CLASS_OPS, reserved: [0 as *mut _; 3], }, @@ -2119,11 +2120,11 @@ def define(self): if self.descriptor.hasUnforgeableMembers: slotCount += 1 return """\ -static PrototypeClass: JSClass = JSClass { +static PrototypeClass: jsapi::JSClass = jsapi::JSClass { name: %(name)s as *const u8 as *const libc::c_char, flags: - // JSCLASS_HAS_RESERVED_SLOTS(%(slotCount)s) - (%(slotCount)s & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT, + // jsapi::JSCLASS_HAS_RESERVED_SLOTS(%(slotCount)s) + (%(slotCount)s & jsapi::JSCLASS_RESERVED_SLOTS_MASK) << jsapi::JSCLASS_RESERVED_SLOTS_SHIFT, cOps: 0 as *const _, reserved: [0 as *mut os::raw::c_void; 3] }; @@ -2263,13 +2264,10 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): 'dom::bindings::str::DOMString', 'dom::bindings::str::USVString', 'dom::types::*', + 'js', 'js::error::throw_type_error', - 'js::jsapi::HandleValue', - 'js::jsapi::Heap', - 'js::jsapi::JSContext', - 'js::jsapi::JSObject', - 'js::jsapi::MutableHandleValue', - 'js::jsval::JSVal', + 'js::heap::Heap', + 'js::jsapi', ] # Now find all the things we'll need as arguments and return values because @@ -2438,8 +2436,8 @@ class CGConstructorEnabled(CGAbstractMethod): def __init__(self, descriptor): CGAbstractMethod.__init__(self, descriptor, 'ConstructorEnabled', 'bool', - [Argument("*mut JSContext", "aCx"), - Argument("HandleObject", "aObj")], + [Argument("*mut jsapi::JSContext", "aCx"), + Argument("jsapi::JS::HandleObject", "aObj")], unsafe=True) def definition_body(self): @@ -2471,23 +2469,28 @@ def CreateBindingJSObject(descriptor, parent=None): create += """ let handler = RegisterBindings::PROXY_HANDLERS[PrototypeList::Proxies::%s as usize]; rooted!(in(cx) let private = PrivateValue(raw as *const libc::c_void)); -let obj = NewProxyObject(cx, handler, - private.handle(), - proto.get(), %s.get(), - ptr::null_mut(), ptr::null_mut()); +let obj = NewProxyObject(cx, + handler, + jsapi::JS::UndefinedHandleValue, + proto.get(), + %s.get(), + ptr::null_mut(), + ptr::null_mut()); assert!(!obj.is_null()); +SetProxyReservedSlot(obj, 0, &private.get()); rooted!(in(cx) let obj = obj);\ """ % (descriptor.name, parent) else: - create += ("rooted!(in(cx) let obj = JS_NewObjectWithGivenProto(\n" - " cx, &Class.base as *const JSClass, proto.handle()));\n" + create += ("rooted!(in(cx) let obj = jsapi::JS_NewObjectWithGivenProto(\n" + " cx, &Class.base as *const jsapi::JSClass, proto.handle()));\n" "assert!(!obj.is_null());\n" "\n" - "JS_SetReservedSlot(obj.get(), DOM_OBJECT_SLOT,\n" - " PrivateValue(raw as *const libc::c_void));") + "let private_value = PrivateValue(raw as *const libc::c_void);\n" + "jsapi::JS_SetReservedSlot(obj.get(), DOM_OBJECT_SLOT,\n" + " &private_value);") if descriptor.weakReferenceable: create += """ -JS_SetReservedSlot(obj.get(), DOM_WEAK_SLOT, PrivateValue(ptr::null()));""" +jsapi::JS_SetReservedSlot(obj.get(), DOM_WEAK_SLOT, &PrivateValue(ptr::null()) as *const _);""" return create @@ -2500,8 +2503,8 @@ def InitUnforgeablePropertiesOnHolder(descriptor, properties): """ unforgeables = [] - defineUnforgeableAttrs = "define_guarded_properties(cx, unforgeable_holder.handle(), %s);" - defineUnforgeableMethods = "define_guarded_methods(cx, unforgeable_holder.handle(), %s);" + defineUnforgeableAttrs = "define_guarded_properties(cx, unforgeable_holder.handle(), &*%s);" + defineUnforgeableMethods = "define_guarded_methods(cx, unforgeable_holder.handle(), &*%s);" unforgeableMembers = [ (defineUnforgeableAttrs, properties.unforgeable_attrs), @@ -2537,13 +2540,13 @@ def CopyUnforgeablePropertiesToInstance(descriptor): # unforgeable holder for those with the right JSClass. Luckily, there # aren't too many globals being created. if descriptor.isGlobal(): - copyFunc = "JS_CopyPropertiesFrom" + copyFunc = "jsapi::JS_CopyPropertiesFrom" else: - copyFunc = "JS_InitializePropertiesFromCompatibleNativeObject" + copyFunc = "jsapi::JS_InitializePropertiesFromCompatibleNativeObject" copyCode += """\ rooted!(in(cx) let mut unforgeable_holder = ptr::null_mut()); unforgeable_holder.handle_mut().set( - JS_GetReservedSlot(proto.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT).to_object()); + jsapi::JS_GetReservedSlot(proto.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT).to_object()); assert!(%(copyFunc)s(cx, %(obj)s.handle(), unforgeable_holder.handle())); """ % {'copyFunc': copyFunc, 'obj': obj} @@ -2558,7 +2561,7 @@ class CGWrapMethod(CGAbstractMethod): def __init__(self, descriptor): assert not descriptor.interface.isCallback() assert not descriptor.isGlobal() - args = [Argument('*mut JSContext', 'cx'), + args = [Argument('*mut jsapi::JSContext', 'cx'), Argument('&GlobalScope', 'scope'), Argument("Box<%s>" % descriptor.concreteType, 'object')] retval = 'Root<%s>' % descriptor.concreteType @@ -2574,7 +2577,7 @@ def definition_body(self): assert!(((*get_object_class(scope.get())).flags & JSCLASS_IS_GLOBAL) != 0); rooted!(in(cx) let mut proto = ptr::null_mut()); -let _ac = JSAutoCompartment::new(cx, scope.get()); +let _ac = js::ac::AutoCompartment::with_obj(cx, scope.get()); GetProtoObject(cx, scope, proto.handle_mut()); assert!(!proto.is_null()); @@ -2593,7 +2596,7 @@ class CGWrapGlobalMethod(CGAbstractMethod): def __init__(self, descriptor, properties): assert not descriptor.interface.isCallback() assert descriptor.isGlobal() - args = [Argument('*mut JSContext', 'cx'), + args = [Argument('*mut jsapi::JSContext', 'cx'), Argument("Box<%s>" % descriptor.concreteType, 'object')] retval = 'Root<%s>' % descriptor.concreteType CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args, @@ -2610,7 +2613,7 @@ def definition_body(self): ("define_guarded_methods", self.properties.methods), ("define_guarded_constants", self.properties.consts) ] - members = ["%s(cx, obj.handle(), %s);" % (function, array.variableName()) + members = ["%s(cx, obj.handle(), &*%s);" % (function, array.variableName()) for (function, array) in pairs if array.length() > 0] values["members"] = "\n".join(members) @@ -2629,12 +2632,12 @@ def definition_body(self): (*raw).init_reflector(obj.get()); -let _ac = JSAutoCompartment::new(cx, obj.get()); +let _ac = js::ac::AutoCompartment::with_obj(cx, obj.get()); rooted!(in(cx) let mut proto = ptr::null_mut()); GetProtoObject(cx, obj.handle(), proto.handle_mut()); -assert!(JS_SplicePrototype(cx, obj.handle(), proto.handle())); +assert!(jsapi::JS_SplicePrototype(cx, obj.handle(), proto.handle())); let mut immutable = false; -assert!(JS_SetImmutablePrototype(cx, obj.handle(), &mut immutable)); +assert!(jsapi::JS_SetImmutablePrototype(cx, obj.handle(), &mut immutable)); assert!(immutable); %(members)s @@ -2737,7 +2740,8 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod): properties should be a PropertyArrays instance. """ def __init__(self, descriptor, properties, haveUnscopables): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'global'), + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', 'global'), Argument('*mut ProtoOrIfaceArray', 'cache')] CGAbstractMethod.__init__(self, descriptor, 'CreateInterfaceObjects', 'void', args, unsafe=True) @@ -2748,9 +2752,9 @@ def definition_body(self): name = self.descriptor.interface.identifier.name if self.descriptor.interface.isNamespace(): if self.descriptor.interface.getExtendedAttribute("ProtoObjectHack"): - proto = "JS_GetObjectPrototype(cx, global)" + proto = "jsapi::JS_GetObjectPrototype(cx, global)" else: - proto = "JS_NewPlainObject(cx)" + proto = "jsapi::JS_NewPlainObject(cx)" if self.properties.static_methods.length(): methods = self.properties.static_methods.variableName() else: @@ -2760,11 +2764,11 @@ def definition_body(self): assert!(!proto.is_null()); rooted!(in(cx) let mut namespace = ptr::null_mut()); create_namespace_object(cx, global, proto.handle(), &NAMESPACE_OBJECT_CLASS, - %(methods)s, %(name)s, namespace.handle_mut()); + &*%(methods)s, %(name)s, namespace.handle_mut()); assert!(!namespace.is_null()); assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); (*cache)[PrototypeList::Constructor::%(id)s as usize] = namespace.get(); -<*mut JSObject>::post_barrier((*cache).as_mut_ptr().offset(PrototypeList::Constructor::%(id)s as isize), +<*mut jsapi::JSObject>::post_barrier((*cache).as_mut_ptr().offset(PrototypeList::Constructor::%(id)s as isize), ptr::null_mut(), namespace.get()); """ % {"id": MakeNativeName(name), "methods": methods, "name": str_to_const_array(name), "proto": proto}) @@ -2772,11 +2776,11 @@ def definition_body(self): assert not self.descriptor.interface.ctor() and self.descriptor.interface.hasConstants() return CGGeneric("""\ rooted!(in(cx) let mut interface = ptr::null_mut()); -create_callback_interface_object(cx, global, sConstants, %(name)s, interface.handle_mut()); +create_callback_interface_object(cx, global, &*sConstants, %(name)s, interface.handle_mut()); assert!(!interface.is_null()); assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); (*cache)[PrototypeList::Constructor::%(id)s as usize] = interface.get(); -<*mut JSObject>::post_barrier((*cache).as_mut_ptr().offset(PrototypeList::Constructor::%(id)s as isize), +<*mut jsapi::JSObject>::post_barrier((*cache).as_mut_ptr().offset(PrototypeList::Constructor::%(id)s as isize), ptr::null_mut(), interface.get()); """ % {"id": name, "name": str_to_const_array(name)}) @@ -2784,11 +2788,11 @@ def definition_body(self): parentName = self.descriptor.getParentName() if not parentName: if self.descriptor.interface.getExtendedAttribute("ExceptionClass"): - getPrototypeProto = "prototype_proto.set(JS_GetErrorPrototype(cx))" + getPrototypeProto = "prototype_proto.set(jsapi::JS_GetErrorPrototype(cx))" elif self.descriptor.interface.isIteratorInterface(): - getPrototypeProto = "prototype_proto.set(JS_GetIteratorPrototype(cx))" + getPrototypeProto = "prototype_proto.set(jsapi::JS_GetIteratorPrototype(cx))" else: - getPrototypeProto = "prototype_proto.set(JS_GetObjectPrototype(cx, global))" + getPrototypeProto = "prototype_proto.set(jsapi::JS_GetObjectPrototype(cx, global))" else: getPrototypeProto = ("%s::GetProtoObject(cx, global, prototype_proto.handle_mut())" % toBindingNamespace(parentName)) @@ -2826,15 +2830,15 @@ def definition_body(self): create_interface_prototype_object(cx, prototype_proto.handle(), &PrototypeClass, - %(methods)s, - %(attrs)s, - %(consts)s, - %(unscopables)s, + &*%(methods)s, + &*%(attrs)s, + &*%(consts)s, + &*%(unscopables)s, prototype.handle_mut()); assert!(!prototype.is_null()); assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null()); (*cache)[PrototypeList::ID::%(id)s as usize] = prototype.get(); -<*mut JSObject>::post_barrier((*cache).as_mut_ptr().offset(PrototypeList::ID::%(id)s as isize), +<*mut jsapi::JSObject>::post_barrier((*cache).as_mut_ptr().offset(PrototypeList::ID::%(id)s as isize), ptr::null_mut(), prototype.get()); """ % proto_properties)) @@ -2853,7 +2857,7 @@ def definition_body(self): %s::GetConstructorObject(cx, global, interface_proto.handle_mut());""" % parentName)) else: code.append(CGGeneric(""" -rooted!(in(cx) let interface_proto = JS_GetFunctionPrototype(cx, global));""")) +rooted!(in(cx) let interface_proto = jsapi::JS_GetFunctionPrototype(cx, global));""")) code.append(CGGeneric("""\ assert!(!interface_proto.is_null()); @@ -2862,9 +2866,9 @@ def definition_body(self): global, interface_proto.handle(), &INTERFACE_OBJECT_CLASS, - %(static_methods)s, - %(static_attrs)s, - %(consts)s, + &*%(static_methods)s, + &*%(static_attrs)s, + &*%(consts)s, prototype.handle(), %(name)s, %(length)s, @@ -2874,25 +2878,28 @@ def definition_body(self): code.append(CGGeneric("""\ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); (*cache)[PrototypeList::Constructor::%(id)s as usize] = interface.get(); -<*mut JSObject>::post_barrier((*cache).as_mut_ptr().offset(PrototypeList::Constructor::%(id)s as isize), - ptr::null_mut(), - interface.get()); +<*mut jsapi::JSObject>::post_barrier( + (*cache).as_mut_ptr().offset(PrototypeList::Constructor::%(id)s as isize), + ptr::null_mut(), + interface.get()); """ % properties)) aliasedMembers = [m for m in self.descriptor.interface.members if m.isMethod() and m.aliases] if aliasedMembers: def defineAlias(alias): if alias == "@@iterator": - symbolJSID = "RUST_SYMBOL_TO_JSID(GetWellKnownSymbol(cx, SymbolCode::iterator))" + symbolJSID = ("RUST_SYMBOL_TO_JSID(jsapi::JS::GetWellKnownSymbol(\n" + " cx,\n" + " jsapi::JS::SymbolCode::iterator))\n") getSymbolJSID = CGGeneric(fill("rooted!(in(cx) let iteratorId = ${symbolJSID});", symbolJSID=symbolJSID)) - defineFn = "JS_DefinePropertyById2" + defineFn = "jsapi::JS_DefinePropertyById2" prop = "iteratorId.handle()" elif alias.startswith("@@"): raise TypeError("Can't handle any well-known Symbol other than @@iterator") else: getSymbolJSID = None - defineFn = "JS_DefineProperty" + defineFn = "jsapi::JS_DefineProperty" prop = '"%s"' % alias return CGList([ getSymbolJSID, @@ -2902,7 +2909,7 @@ def defineAlias(alias): CGGeneric(fill( """ assert!(${defineFn}(cx, prototype.handle(), ${prop}, aliasedVal.handle(), - JSPROP_ENUMERATE, None, None)); + jsapi::JSPROP_ENUMERATE as _, None, None)); """, defineFn=defineFn, prop=prop)) @@ -2912,7 +2919,7 @@ def defineAliasesFor(m): return CGList([ CGGeneric(fill( """ - assert!(JS_GetProperty(cx, prototype.handle(), + assert!(jsapi::JS_GetProperty(cx, prototype.handle(), ${prop} as *const u8 as *const _, aliasedVal.handle_mut())); """, @@ -2944,7 +2951,7 @@ def defineAliasesFor(m): if self.descriptor.hasUnforgeableMembers: # We want to use the same JSClass and prototype as the object we'll # end up defining the unforgeable properties on in the end, so that - # we can use JS_InitializePropertiesFromCompatibleNativeObject to do + # we can use jsapi::JS_InitializePropertiesFromCompatibleNativeObject to do # a fast copy. In the case of proxies that's null, because the # expando object is a vanilla object, but in the case of other DOM # objects it's whatever our class is. @@ -2955,20 +2962,20 @@ def defineAliasesFor(m): # the prototype. if self.descriptor.proxy or self.descriptor.isGlobal(): holderClass = "ptr::null()" - holderProto = "HandleObject::null()" + holderProto = "jsapi::JS::HandleObject::null()" else: - holderClass = "&Class.base as *const JSClass" + holderClass = "&Class.base as *const jsapi::JSClass" holderProto = "prototype.handle()" code.append(CGGeneric(""" rooted!(in(cx) let mut unforgeable_holder = ptr::null_mut()); unforgeable_holder.handle_mut().set( - JS_NewObjectWithoutMetadata(cx, %(holderClass)s, %(holderProto)s)); + jsapi::JS_NewObjectWithoutMetadata(cx, %(holderClass)s, %(holderProto)s)); assert!(!unforgeable_holder.is_null()); """ % {'holderClass': holderClass, 'holderProto': holderProto})) code.append(InitUnforgeablePropertiesOnHolder(self.descriptor, self.properties)) code.append(CGGeneric("""\ -JS_SetReservedSlot(prototype.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT, - ObjectValue(unforgeable_holder.get()))""")) +jsapi::JS_SetReservedSlot(prototype.get(), DOM_PROTO_UNFORGEABLE_HOLDER_SLOT, + &ObjectValue(unforgeable_holder.get()))""")) return CGList(code, "\n") @@ -2979,9 +2986,9 @@ class CGGetPerInterfaceObject(CGAbstractMethod): constructor object). """ def __init__(self, descriptor, name, idPrefix="", pub=False): - args = [Argument('*mut JSContext', 'cx'), - Argument('HandleObject', 'global'), - Argument('MutableHandleObject', 'rval')] + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', 'global'), + Argument('jsapi::JS::MutableHandleObject', 'rval')] CGAbstractMethod.__init__(self, descriptor, name, 'void', args, pub=pub, unsafe=True) self.id = idPrefix + "::" + MakeNativeName(self.descriptor.name) @@ -3117,8 +3124,8 @@ class CGDefineDOMInterfaceMethod(CGAbstractMethod): def __init__(self, descriptor): assert descriptor.interface.hasInterfaceObject() args = [ - Argument('*mut JSContext', 'cx'), - Argument('HandleObject', 'global'), + Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', 'global'), ] CGAbstractMethod.__init__(self, descriptor, 'DefineDOMInterface', 'void', args, pub=True, unsafe=True) @@ -3245,7 +3252,7 @@ class CGPerSignatureCall(CGThing): """ # XXXbz For now each entry in the argument list is either an # IDLArgument or a FakeArgument, but longer-term we may want to - # have ways of flagging things like JSContext* or optional_argc in + # have ways of flagging things like jsapi::JSContext* or optional_argc in # there. def __init__(self, returnType, argsPre, arguments, nativeMethodName, static, @@ -3406,7 +3413,7 @@ def getArgc(self): class CGAbstractStaticBindingMethod(CGAbstractMethod): """ - Common class to generate the JSNatives for all our static methods, getters + Common class to generate the jsapi::JSNatives for all our static methods, getters and setters. This will generate the function declaration and unwrap the global object. Subclasses are expected to override the generate_code function to do the rest of the work. This function should return a @@ -3414,15 +3421,16 @@ class CGAbstractStaticBindingMethod(CGAbstractMethod): """ def __init__(self, descriptor, name): args = [ - Argument('*mut JSContext', 'cx'), + Argument('*mut jsapi::JSContext', 'cx'), Argument('libc::c_uint', 'argc'), - Argument('*mut JSVal', 'vp'), + Argument('*mut jsapi::JS::Value', 'vp'), ] CGAbstractMethod.__init__(self, descriptor, name, "bool", args, extern=True) self.exposureSet = descriptor.interface.exposureSet def definition_body(self): - preamble = "let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object());\n" + preamble = ("let args = jsapi::JS::CallArgs::from_vp(vp, argc);\n" + "let global = GlobalScope::from_object(args.callee());\n") if len(self.exposureSet) == 1: preamble += "let global = Root::downcast::(global).unwrap();\n" % list(self.exposureSet)[0] return CGList([CGGeneric(preamble), self.generate_code()]) @@ -3439,9 +3447,9 @@ class CGSpecializedMethod(CGAbstractExternMethod): def __init__(self, descriptor, method): self.method = method name = method.identifier.name - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', '_obj'), + args = [Argument('*mut jsapi::JSContext', 'cx'), Argument('jsapi::JS::HandleObject', '_obj'), Argument('*const %s' % descriptor.concreteType, 'this'), - Argument('*const JSJitMethodCallArgs', 'args')] + Argument('*const jsapi::JSJitMethodCallArgs', 'args')] CGAbstractExternMethod.__init__(self, descriptor, name, 'bool', args) def definition_body(self): @@ -3474,7 +3482,7 @@ def __init__(self, descriptor, method): def generate_code(self): nativeName = CGSpecializedMethod.makeNativeName(self.descriptor, self.method) - setupArgs = CGGeneric("let args = CallArgs::from_vp(vp, argc);\n") + setupArgs = CGGeneric("let args = jsapi::JS::CallArgs::from_vp(vp, argc);\n") call = CGMethodCall(["&global"], nativeName, True, self.descriptor, self.method) return CGList([setupArgs, call]) @@ -3487,10 +3495,10 @@ class CGSpecializedGetter(CGAbstractExternMethod): def __init__(self, descriptor, attr): self.attr = attr name = 'get_' + descriptor.internalNameFor(attr.identifier.name) - args = [Argument('*mut JSContext', 'cx'), - Argument('HandleObject', '_obj'), + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', '_obj'), Argument('*const %s' % descriptor.concreteType, 'this'), - Argument('JSJitGetterCallArgs', 'args')] + Argument('jsapi::JSJitGetterCallArgs', 'args')] CGAbstractExternMethod.__init__(self, descriptor, name, "bool", args) def definition_body(self): @@ -3528,7 +3536,7 @@ def __init__(self, descriptor, attr): def generate_code(self): nativeName = CGSpecializedGetter.makeNativeName(self.descriptor, self.attr) - setupArgs = CGGeneric("let args = CallArgs::from_vp(vp, argc);\n") + setupArgs = CGGeneric("let args = jsapi::JS::CallArgs::from_vp(vp, argc);\n") call = CGGetterCall(["&global"], self.attr.type, nativeName, self.descriptor, self.attr) return CGList([setupArgs, call]) @@ -3542,10 +3550,10 @@ class CGSpecializedSetter(CGAbstractExternMethod): def __init__(self, descriptor, attr): self.attr = attr name = 'set_' + descriptor.internalNameFor(attr.identifier.name) - args = [Argument('*mut JSContext', 'cx'), - Argument('HandleObject', 'obj'), + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', 'obj'), Argument('*const %s' % descriptor.concreteType, 'this'), - Argument('JSJitSetterCallArgs', 'args')] + Argument('jsapi::JSJitSetterCallArgs', 'args')] CGAbstractExternMethod.__init__(self, descriptor, name, "bool", args) def definition_body(self): @@ -3577,7 +3585,7 @@ def generate_code(self): nativeName = CGSpecializedSetter.makeNativeName(self.descriptor, self.attr) checkForArg = CGGeneric( - "let args = CallArgs::from_vp(vp, argc);\n" + "let args = jsapi::JS::CallArgs::from_vp(vp, argc);\n" "if argc == 0 {\n" " throw_type_error(cx, \"Not enough arguments to %s setter.\");\n" " return false;\n" @@ -3597,12 +3605,12 @@ def __init__(self, descriptor, attr): def definition_body(self): attrName = self.attr.identifier.name forwardToAttrName = self.attr.getExtendedAttribute("PutForwards")[0] - # JS_GetProperty and JS_SetProperty can only deal with ASCII + # jsapi::JS_GetProperty and JS_SetProperty can only deal with ASCII assert all(ord(c) < 128 for c in attrName) assert all(ord(c) < 128 for c in forwardToAttrName) return CGGeneric("""\ rooted!(in(cx) let mut v = UndefinedValue()); -if !JS_GetProperty(cx, obj, %s as *const u8 as *const libc::c_char, v.handle_mut()) { +if !jsapi::JS_GetProperty(cx, obj, %s as *const u8 as *const libc::c_char, v.handle_mut()) { return false; } if !v.is_object() { @@ -3610,7 +3618,7 @@ def definition_body(self): return false; } rooted!(in(cx) let target_obj = v.to_object()); -JS_SetProperty(cx, target_obj.handle(), %s as *const u8 as *const libc::c_char, args.get(0)) +jsapi::JS_SetProperty(cx, target_obj.handle(), %s as *const u8 as *const libc::c_char, args.get(0)) """ % (str_to_const_array(attrName), attrName, str_to_const_array(forwardToAttrName))) @@ -3624,11 +3632,11 @@ def __init__(self, descriptor, attr): def definition_body(self): assert self.attr.readonly name = str_to_const_array(self.attr.identifier.name) - # JS_DefineProperty can only deal with ASCII. + # jsapi::JS_DefineProperty can only deal with ASCII. assert all(ord(c) < 128 for c in name) return CGGeneric("""\ -JS_DefineProperty(cx, obj, %s as *const u8 as *const libc::c_char, - args.get(0), JSPROP_ENUMERATE, None, None)""" % name) +jsapi::JS_DefineProperty(cx, obj, %s as *const u8 as *const libc::c_char, + args.get(0), jsapi::JSPROP_ENUMERATE as _, None, None)""" % name) class CGMemberJITInfo(CGThing): @@ -3644,7 +3652,7 @@ def defineJitInfo(self, infoName, opName, opType, infallible, movable, aliasSet, alwaysInSlot, lazilyInSlot, slotIndex, returnTypes, args): """ - aliasSet is a JSJitInfo_AliasSet value, without the "JSJitInfo_AliasSet::" bit. + aliasSet is a jsapi::JSJitInfo_AliasSet value, without the "JSJitInfo_AliasSet::" bit. args is None if we don't want to output argTypes for some reason (e.g. we have overloads or we're not a method) and @@ -3656,23 +3664,33 @@ def defineJitInfo(self, infoName, opName, opType, infallible, movable, def jitInfoInitializer(isTypedMethod): initializer = fill( """ - JSJitInfo { - call: ${opName} as *const os::raw::c_void, - protoID: PrototypeList::ID::${name} as u16, - depth: ${depth}, - _bitfield_1: - JSJitInfo::new_bitfield_1( - JSJitInfo_OpType::${opType} as u8, - JSJitInfo_AliasSet::${aliasSet} as u8, - JSValueType::${returnType} as u8, - ${isInfallible}, - ${isMovable}, - ${isEliminatable}, - ${isAlwaysInSlot}, - ${isLazilyCachedInSlot}, - ${isTypedMethod}, - ${slotIndex} as u16, - ) + jsapi::JSJitInfo { + __bindgen_anon_1: jsapi::JSJitInfo__bindgen_ty_1 { + method: unsafe { + mem::transmute(${opName} as + unsafe extern "C" fn(*mut jsapi::JSContext, + jsapi::JS::HandleObject, + _, + _) -> bool) }, + }, + __bindgen_anon_2: jsapi::JSJitInfo__bindgen_ty_2 { + protoID: PrototypeList::ID::${name} as u16, + }, + __bindgen_anon_3: jsapi::JSJitInfo__bindgen_ty_3 { + depth: ${depth}, + }, + _bitfield_1: unsafe { mem::transmute(jsapi::JSJitInfo::new_bitfield_1( + jsapi::JSJitInfo_OpType::${opType} as _, + jsapi::JSJitInfo_AliasSet::${aliasSet} as _, + jsapi::JSValueType::${returnType} as _, + ${isInfallible} as _, + ${isMovable} as _, + ${isEliminatable} as _, + ${isAlwaysInSlot} as _, + ${isLazilyCachedInSlot} as _, + ${isTypedMethod} as _, + ${slotIndex} as _ + )) } } """, opName=opName, @@ -3695,17 +3713,20 @@ def jitInfoInitializer(isTypedMethod): if args is not None: argTypes = "%s_argTypes" % infoName args = [CGMemberJITInfo.getJSArgType(arg.type) for arg in args] - args.append("JSJitInfo_ArgType::ArgTypeListEnd as i32") + args.append("jsapi::JSJitInfo_ArgType::ArgTypeListEnd as i32") argTypesDecl = ( "const %s: [i32; %d] = [ %s ];\n" % (argTypes, len(args), ", ".join(args))) return fill( """ $*{argTypesDecl} - const ${infoName}: JSTypedMethodJitInfo = JSTypedMethodJitInfo { - base: ${jitInfo}, - argTypes: &${argTypes} as *const _ as *const JSJitInfo_ArgType, - }; + lazy_static! { + pub static ref ${infoName}: jsapi::JSTypedMethodJitInfo = + jsapi::JSTypedMethodJitInfo { + base: ${jitInfo}, + argTypes: &${argTypes} as *const _ as *const jsapi::JSJitInfo_ArgType, + }; + } """, argTypesDecl=argTypesDecl, infoName=infoName, @@ -3713,7 +3734,9 @@ def jitInfoInitializer(isTypedMethod): argTypes=argTypes) return ("\n" - "const %s: JSJitInfo = %s;\n" + "lazy_static! {\n" + " pub static ref %s: jsapi::JSJitInfo = %s;\n" + "}\n" % (infoName, jitInfoInitializer(False))) def define(self): @@ -3886,7 +3909,7 @@ def getJSReturnTypeTag(t): if tag in [IDLType.Tags.int64, IDLType.Tags.uint64, IDLType.Tags.unrestricted_float, IDLType.Tags.float, IDLType.Tags.unrestricted_double, IDLType.Tags.double]: - # These all use JS_NumberValue, which can return int or double. + # These all use jsapi::JS_NumberValue, which can return int or double. # But TI treats "double" as meaning "int or double", so we're # good to return JSVAL_TYPE_DOUBLE here. return "JSVAL_TYPE_DOUBLE" @@ -3918,53 +3941,53 @@ def getJSArgType(t): assert not t.isVoid() if t.nullable(): # Sometimes it might return null, sometimes not - return "JSJitInfo_ArgType::Null as i32 | %s" % CGMemberJITInfo.getJSArgType(t.inner) + return "jsapi::JSJitInfo_ArgType::Null as i32 | %s" % CGMemberJITInfo.getJSArgType(t.inner) if t.isSequence(): - return "JSJitInfo_ArgType::Object as i32" + return "jsapi::JSJitInfo_ArgType::Object as i32" if t.isGeckoInterface(): - return "JSJitInfo_ArgType::Object as i32" + return "jsapi::JSJitInfo_ArgType::Object as i32" if t.isString(): - return "JSJitInfo_ArgType::String as i32" + return "jsapi::JSJitInfo_ArgType::String as i32" if t.isEnum(): - return "JSJitInfo_ArgType::String as i32" + return "jsapi::JSJitInfo_ArgType::String as i32" if t.isCallback(): - return "JSJitInfo_ArgType::Object as i32" + return "jsapi::JSJitInfo_ArgType::Object as i32" if t.isAny(): # The whole point is to return various stuff - return "JSJitInfo_ArgType::Any as i32" + return "jsapi::JSJitInfo_ArgType::Any as i32" if t.isObject(): - return "JSJitInfo_ArgType::Object as i32" + return "jsapi::JSJitInfo_ArgType::Object as i32" if t.isSpiderMonkeyInterface(): - return "JSJitInfo_ArgType::Object as i32" + return "jsapi::JSJitInfo_ArgType::Object as i32" if t.isUnion(): u = t.unroll() - type = "JSJitInfo::Null as i32" if u.hasNullableType else "" + type = "jsapi::JSJitInfo::Null as i32" if u.hasNullableType else "" return reduce(CGMemberJITInfo.getSingleArgType, u.flatMemberTypes, type) if t.isDictionary(): - return "JSJitInfo_ArgType::Object as i32" + return "jsapi::JSJitInfo_ArgType::Object as i32" if t.isDate(): - return "JSJitInfo_ArgType::Object as i32" + return "jsapi::JSJitInfo_ArgType::Object as i32" if not t.isPrimitive(): raise TypeError("No idea what type " + str(t) + " is.") tag = t.tag() if tag == IDLType.Tags.bool: - return "JSJitInfo_ArgType::Boolean as i32" + return "jsapi::JSJitInfo_ArgType::Boolean as i32" if tag in [IDLType.Tags.int8, IDLType.Tags.uint8, IDLType.Tags.int16, IDLType.Tags.uint16, IDLType.Tags.int32]: - return "JSJitInfo_ArgType::Integer as i32" + return "jsapi::JSJitInfo_ArgType::Integer as i32" if tag in [IDLType.Tags.int64, IDLType.Tags.uint64, IDLType.Tags.unrestricted_float, IDLType.Tags.float, IDLType.Tags.unrestricted_double, IDLType.Tags.double]: - # These all use JS_NumberValue, which can return int or double. + # These all use jsapi::JS_NumberValue, which can return int or double. # But TI treats "double" as meaning "int or double", so we're # good to return JSVAL_TYPE_DOUBLE here. - return "JSJitInfo_ArgType::Double as i32" + return "jsapi::JSJitInfo_ArgType::Double as i32" if tag != IDLType.Tags.uint32: raise TypeError("No idea what type " + str(t) + " is.") # uint32 is sometimes int and sometimes double. - return "JSJitInfo_ArgType::Double as i32" + return "jsapi::JSJitInfo_ArgType::Double as i32" @staticmethod def getSingleArgType(existingType, t): @@ -4016,8 +4039,7 @@ def __init__(self, enum): inner = """\ use dom::bindings::conversions::ToJSValConvertible; -use js::jsapi::{JSContext, MutableHandleValue}; -use js::jsval::JSVal; +use js::jsapi; pub const pairs: &'static [(&'static str, super::%s)] = &[ %s, @@ -4030,7 +4052,7 @@ def __init__(self, enum): } impl ToJSValConvertible for super::%s { - unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { + unsafe fn to_jsval(&self, cx: *mut jsapi::JSContext, rval: jsapi::JS::MutableHandleValue) { pairs[*self as usize].0.to_jsval(cx, rval); } } @@ -4100,7 +4122,7 @@ def getUnionTypeTemplateVars(type, descriptorProvider): typeName = builtinNames[type.tag()] elif type.isObject(): name = type.name - typeName = "Heap<*mut JSObject>" + typeName = "Heap<*mut jsapi::JSObject>" else: raise TypeError("Can't handle %s in unions yet" % type) @@ -4149,7 +4171,7 @@ def define(self): } impl ToJSValConvertible for %s { - unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { + unsafe fn to_jsval(&self, cx: *mut jsapi::JSContext, rval: jsapi::JS::MutableHandleValue) { match *self { %s } @@ -4295,8 +4317,8 @@ def getStringOrPrimitiveConversion(memberType): "Err(())" % ", ".join(names))) method = CGWrapper( CGIndenter(CGList(conversions, "\n\n")), - pre="unsafe fn from_jsval(cx: *mut JSContext,\n" - " value: HandleValue,\n" + pre="unsafe fn from_jsval(cx: *mut jsapi::JSContext,\n" + " value: jsapi::JS::HandleValue,\n" " _option: ())\n" " -> Result, ()> {\n" % self.type, post="\n}") @@ -4316,8 +4338,11 @@ def try_method(self, t): return CGWrapper( CGIndenter(jsConversion, 4), # TryConvertToObject is unused, but not generating it while generating others is tricky. - pre="#[allow(dead_code)] unsafe fn TryConvertTo%s(cx: *mut JSContext, value: HandleValue) -> %s {\n" - % (t.name, returnType), + pre=("#[allow(dead_code)]\n" + "unsafe fn TryConvertTo%s(cx: *mut jsapi::JSContext,\n" + " value: jsapi::JS::HandleValue)\n" + " -> %s {\n" + % (t.name, returnType)), post="\n}") def define(self): @@ -4793,7 +4818,7 @@ def __init__(self, descriptor): class CGProxyUnwrap(CGAbstractMethod): def __init__(self, descriptor): - args = [Argument('HandleObject', 'obj')] + args = [Argument('jsapi::JS::HandleObject', 'obj')] CGAbstractMethod.__init__(self, descriptor, "UnwrapProxy", '*const ' + descriptor.concreteType, args, alwaysInline=True, unsafe=True) @@ -4804,15 +4829,16 @@ def definition_body(self): obj = js::UnwrapObject(obj); }*/ //MOZ_ASSERT(IsProxy(obj)); -let box_ = GetProxyPrivate(obj.get()).to_private() as *const %s; +let box_ = GetProxyReservedSlot(obj.get(), 0).to_private() as *const %s; return box_;""" % self.descriptor.concreteType) class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'), - Argument('HandleId', 'id'), - Argument('MutableHandle', 'desc')] + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', 'proxy'), + Argument('jsapi::JS::HandleId', 'id'), + Argument('jsapi::JS::MutableHandle', 'desc')] CGAbstractExternMethod.__init__(self, descriptor, "getOwnPropertyDescriptor", "bool", args) self.descriptor = descriptor @@ -4826,12 +4852,12 @@ def getBody(self): get = "let index = get_array_index_from_id(cx, id);\n" if indexedGetter: - attrs = "JSPROP_ENUMERATE" + attrs = "jsapi::JSPROP_ENUMERATE" if self.descriptor.operations['IndexedSetter'] is None: - attrs += " | JSPROP_READONLY" + attrs += " | jsapi::JSPROP_READONLY" # FIXME(#11868) Should assign to desc.value, desc.get() is a copy. fillDescriptor = ("desc.get().value = result_root.get();\n" - "fill_property_descriptor(desc, proxy.get(), %s);\n" + "fill_property_descriptor(desc, proxy.get(), (%s) as _);\n" "return true;" % attrs) templateValues = { 'jsvalRef': 'result_root.handle_mut()', @@ -4848,16 +4874,16 @@ def getBody(self): if namedGetter: attrs = [] if not self.descriptor.interface.getExtendedAttribute("LegacyUnenumerableNamedProperties"): - attrs.append("JSPROP_ENUMERATE") + attrs.append("jsapi::JSPROP_ENUMERATE") if self.descriptor.operations['NamedSetter'] is None: - attrs.append("JSPROP_READONLY") + attrs.append("jsapi::JSPROP_READONLY") if attrs: attrs = " | ".join(attrs) else: attrs = "0" # FIXME(#11868) Should assign to desc.value, desc.get() is a copy. fillDescriptor = ("desc.get().value = result_root.get();\n" - "fill_property_descriptor(desc, proxy.get(), %s);\n" + "fill_property_descriptor(desc, proxy.get(), (%s) as _);\n" "return true;" % attrs) templateValues = { 'jsvalRef': 'result_root.handle_mut()', @@ -4887,7 +4913,7 @@ def getBody(self): get_expando_object(proxy, expando.handle_mut()); //if (!xpc::WrapperFactory::IsXrayWrapper(proxy) && (expando = GetExpandoObject(proxy))) { if !expando.is_null() { - if !JS_GetPropertyDescriptorById(cx, expando.handle(), id, desc) { + if !jsapi::JS_GetPropertyDescriptorById(cx, expando.handle(), id, desc) { return false; } if !desc.obj.is_null() { @@ -4906,10 +4932,11 @@ def definition_body(self): class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'), - Argument('HandleId', 'id'), - Argument('Handle', 'desc'), - Argument('*mut ObjectOpResult', 'opresult')] + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', 'proxy'), + Argument('jsapi::JS::HandleId', 'id'), + Argument('jsapi::JS::Handle', 'desc'), + Argument('*mut jsapi::JS::ObjectOpResult', 'opresult')] CGAbstractExternMethod.__init__(self, descriptor, "defineProperty", "bool", args) self.descriptor = descriptor @@ -4957,9 +4984,10 @@ def definition_body(self): class CGDOMJSProxyHandler_delete(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'), - Argument('HandleId', 'id'), - Argument('*mut ObjectOpResult', 'res')] + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', 'proxy'), + Argument('jsapi::JS::HandleId', 'id'), + Argument('*mut jsapi::JS::ObjectOpResult', 'res')] CGAbstractExternMethod.__init__(self, descriptor, "delete", "bool", args) self.descriptor = descriptor @@ -4979,9 +5007,9 @@ def definition_body(self): class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), - Argument('HandleObject', 'proxy'), - Argument('*mut AutoIdVector', 'props')] + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', 'proxy'), + Argument('*mut jsapi::JS::AutoIdVector', 'props')] CGAbstractExternMethod.__init__(self, descriptor, "own_property_keys", "bool", args) self.descriptor = descriptor @@ -4996,7 +5024,7 @@ def getBody(self): """ for i in 0..(*unwrapped_proxy).Length() { rooted!(in(cx) let rooted_jsid = int_to_jsid(i as i32)); - AppendToAutoIdVector(props, rooted_jsid.handle().get()); + js::glue::AppendToAutoIdVector(props, rooted_jsid.handle().get()); } """) @@ -5005,11 +5033,11 @@ def getBody(self): """ for name in (*unwrapped_proxy).SupportedPropertyNames() { let cstring = CString::new(name).unwrap(); - let jsstring = JS_AtomizeAndPinString(cx, cstring.as_ptr()); + let jsstring = jsapi::JS_AtomizeAndPinString(cx, cstring.as_ptr()); rooted!(in(cx) let rooted = jsstring); - let jsid = INTERNED_STRING_TO_JSID(cx, rooted.handle().get()); + let jsid = jsapi::INTERNED_STRING_TO_JSID(cx, rooted.handle().get()); rooted!(in(cx) let rooted_jsid = jsid); - AppendToAutoIdVector(props, rooted_jsid.handle().get()); + js::glue::AppendToAutoIdVector(props, rooted_jsid.handle().get()); } """) @@ -5018,7 +5046,11 @@ def getBody(self): rooted!(in(cx) let mut expando = ptr::null_mut()); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { - GetPropertyKeys(cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props); + jsapi::js::GetPropertyKeys( + cx, + expando.handle(), + jsapi::JSITER_OWNONLY | jsapi::JSITER_HIDDEN | jsapi::JSITER_SYMBOLS, + props); } return true; @@ -5034,9 +5066,9 @@ class CGDOMJSProxyHandler_getOwnEnumerablePropertyKeys(CGAbstractExternMethod): def __init__(self, descriptor): assert (descriptor.operations["IndexedGetter"] and descriptor.interface.getExtendedAttribute("LegacyUnenumerableNamedProperties")) - args = [Argument('*mut JSContext', 'cx'), - Argument('HandleObject', 'proxy'), - Argument('*mut AutoIdVector', 'props')] + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', 'proxy'), + Argument('*mut jsapi::JS::AutoIdVector', 'props')] CGAbstractExternMethod.__init__(self, descriptor, "getOwnEnumerablePropertyKeys", "bool", args) self.descriptor = descriptor @@ -5052,7 +5084,7 @@ def getBody(self): """ for i in 0..(*unwrapped_proxy).Length() { rooted!(in(cx) let rooted_jsid = int_to_jsid(i as i32)); - AppendToAutoIdVector(props, rooted_jsid.handle().get()); + js::glue::AppendToAutoIdVector(props, rooted_jsid.handle().get()); } """) @@ -5061,7 +5093,11 @@ def getBody(self): rooted!(in(cx) let mut expando = ptr::null_mut()); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { - GetPropertyKeys(cx, expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props); + jsapi::js::GetPropertyKeys( + cx, + expando.handle(), + jsapi::JSITER_OWNONLY | jsapi::JSITER_HIDDEN | jsapi::JSITER_SYMBOLS, + props); } return true; @@ -5075,8 +5111,10 @@ def definition_body(self): class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'), - Argument('HandleId', 'id'), Argument('*mut bool', 'bp')] + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', 'proxy'), + Argument('jsapi::JS::HandleId', 'id'), + Argument('*mut bool', 'bp')] CGAbstractExternMethod.__init__(self, descriptor, "hasOwn", "bool", args) self.descriptor = descriptor @@ -5117,7 +5155,7 @@ def getBody(self): rooted!(in(cx) let mut expando = ptr::null_mut()); get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { - let ok = JS_HasPropertyById(cx, expando.handle(), id, bp); + let ok = jsapi::JS_HasPropertyById(cx, expando.handle(), id, bp); if !ok || *bp { return ok; } @@ -5132,9 +5170,11 @@ def definition_body(self): class CGDOMJSProxyHandler_get(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'), - Argument('HandleValue', 'receiver'), Argument('HandleId', 'id'), - Argument('MutableHandleValue', 'vp')] + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('jsapi::JS::HandleObject', 'proxy'), + Argument('jsapi::JS::HandleValue', 'receiver'), + Argument('jsapi::JS::HandleId', 'id'), + Argument('jsapi::JS::MutableHandleValue', 'vp')] CGAbstractExternMethod.__init__(self, descriptor, "get", "bool", args) self.descriptor = descriptor @@ -5144,12 +5184,12 @@ def getBody(self): get_expando_object(proxy, expando.handle_mut()); if !expando.is_null() { let mut hasProp = false; - if !JS_HasPropertyById(cx, expando.handle(), id, &mut hasProp) { + if !jsapi::JS_HasPropertyById(cx, expando.handle(), id, &mut hasProp) { return false; } if hasProp { - return JS_ForwardGetPropertyTo(cx, expando.handle(), id, receiver, vp); + return jsapi::JS_ForwardGetPropertyTo(cx, expando.handle(), id, receiver, vp); } }""" @@ -5206,7 +5246,7 @@ def definition_body(self): class CGDOMJSProxyHandler_className(CGAbstractExternMethod): def __init__(self, descriptor): - args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', '_proxy')] + args = [Argument('*mut jsapi::JSContext', 'cx'), Argument('jsapi::JS::HandleObject', '_proxy')] CGAbstractExternMethod.__init__(self, descriptor, "className", "*const i8", args, doesNotPanic=True) self.descriptor = descriptor @@ -5249,7 +5289,7 @@ def finalizeHook(descriptor, hookName, context): """ elif descriptor.weakReferenceable: release += """\ -let weak_box_ptr = JS_GetReservedSlot(obj, DOM_WEAK_SLOT).to_private() as *mut WeakBox<%s>; +let weak_box_ptr = jsapi::JS_GetReservedSlot(obj, DOM_WEAK_SLOT).to_private() as *mut WeakBox<%s>; if !weak_box_ptr.is_null() { let count = { let weak_box = &*weak_box_ptr; @@ -5280,7 +5320,7 @@ class CGClassTraceHook(CGAbstractClassHook): A hook to trace through our native object; used for GC and CC """ def __init__(self, descriptor): - args = [Argument('*mut JSTracer', 'trc'), Argument('*mut JSObject', 'obj')] + args = [Argument('*mut jsapi::JSTracer', 'trc'), Argument('*mut jsapi::JSObject', 'obj')] CGAbstractClassHook.__init__(self, descriptor, TRACE_HOOK_NAME, 'void', args, doesNotPanic=True) self.traceGlobal = descriptor.isGlobal() @@ -5298,7 +5338,9 @@ class CGClassConstructHook(CGAbstractExternMethod): JS-visible constructor for our objects """ def __init__(self, descriptor, constructor=None): - args = [Argument('*mut JSContext', 'cx'), Argument('u32', 'argc'), Argument('*mut JSVal', 'vp')] + args = [Argument('*mut jsapi::JSContext', 'cx'), + Argument('u32', 'argc'), + Argument('*mut jsapi::JS::Value', 'vp')] name = CONSTRUCT_HOOK_NAME if constructor: name += "_" + constructor.identifier.name @@ -5310,10 +5352,15 @@ def __init__(self, descriptor, constructor=None): self.exposureSet = descriptor.interface.exposureSet def definition_body(self): - preamble = """let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object());\n""" + preamble = """\ +let args = jsapi::JS::CallArgs::from_vp(vp, argc); +let global = GlobalScope::from_object(args.callee()); +""" if len(self.exposureSet) == 1: - preamble += "let global = Root::downcast::(global).unwrap();\n" % list(self.exposureSet)[0] - preamble += """let args = CallArgs::from_vp(vp, argc);\n""" + preamble += "let global = Root::downcast::(global).unwrap();\n" % ( + list(self.exposureSet)[0] + ) + preamble += """let args = jsapi::JS::CallArgs::from_vp(vp, argc);\n""" preamble = CGGeneric(preamble) if self.constructor.isHTMLConstructor(): signatures = self.constructor.signatures() @@ -5326,7 +5373,9 @@ def definition_body(self): // so we can do the spec's object-identity checks. rooted!(in(cx) let new_target = UnwrapObject(args.new_target().to_object(), 1)); if new_target.is_null() { - throw_dom_exception(cx, global.upcast::(), Error::Type("new.target is null".to_owned())); + throw_dom_exception(cx, + global.upcast::(), + Error::Type("new.target is null".to_owned())); return false; } @@ -5340,8 +5389,12 @@ def definition_body(self): rooted!(in(cx) let mut prototype = ptr::null_mut()); { rooted!(in(cx) let mut proto_val = UndefinedValue()); - let _ac = JSAutoCompartment::new(cx, new_target.get()); - if !JS_GetProperty(cx, new_target.handle(), b"prototype\\0".as_ptr() as *const _, proto_val.handle_mut()) { + let _ac = js::ac::AutoCompartment::with_obj(cx, new_target.get()); + if !jsapi::JS_GetProperty( + cx, + new_target.handle(), + b"prototype\\0".as_ptr() as *const _, + proto_val.handle_mut()) { return false; } @@ -5355,7 +5408,7 @@ def definition_body(self): // whose target is not same-compartment with the proxy, or bound functions, etc). // https://bugzilla.mozilla.org/show_bug.cgi?id=1317658 - rooted!(in(cx) let global_object = CurrentGlobalOrNull(cx)); + rooted!(in(cx) let global_object = jsapi::JS::CurrentGlobalOrNull(cx)); GetProtoObject(cx, global_object.handle(), prototype.handle_mut()); } else { // Step 6 @@ -5364,7 +5417,7 @@ def definition_body(self): } // Wrap prototype in this context since it is from the newTarget compartment -if !JS_WrapObject(cx, prototype.handle_mut()) { +if !jsapi::JS_WrapObject(cx, prototype.handle_mut()) { return false; } @@ -5378,11 +5431,11 @@ def definition_body(self): }; rooted!(in(cx) let mut element = result.reflector().get_jsobject().get()); -if !JS_WrapObject(cx, element.handle_mut()) { +if !jsapi::JS_WrapObject(cx, element.handle_mut()) { return false; } -JS_SetPrototype(cx, element.handle(), prototype.handle()); +jsapi::JS_SetPrototype(cx, element.handle(), prototype.handle()); (result).to_jsval(cx, args.rval()); return true; @@ -5400,7 +5453,7 @@ class CGClassFinalizeHook(CGAbstractClassHook): A hook for finalize, used to release our native object. """ def __init__(self, descriptor): - args = [Argument('*mut JSFreeOp', '_fop'), Argument('*mut JSObject', 'obj')] + args = [Argument('*mut jsapi::JSFreeOp', '_fop'), Argument('*mut jsapi::JSObject', 'obj')] CGAbstractClassHook.__init__(self, descriptor, FINALIZE_HOOK_NAME, 'void', args) @@ -5423,7 +5476,7 @@ def __init__(self, descriptor): def attribute_arguments(needCx, argument=None): if needCx: - yield "cx", "*mut JSContext" + yield "cx", "*mut jsapi::JSContext" if argument: yield "value", argument_type(descriptor, argument) @@ -5487,7 +5540,7 @@ def fmt(arguments): def contains_unsafe_arg(arguments): if not arguments or len(arguments) == 0: return False - return reduce((lambda x, y: x or y[1] == '*mut JSContext'), arguments, False) + return reduce((lambda x, y: x or y[1] == '*mut jsapi::JSContext'), arguments, False) methods = [] for name, arguments, rettype in members(): @@ -5532,96 +5585,13 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries return CGImports(cgthings, descriptors, callbacks, dictionaries, enums, typedefs, [ 'core::nonzero::NonZero', 'js', - 'js::JSCLASS_GLOBAL_SLOT_COUNT', - 'js::JSCLASS_IS_DOMJSCLASS', - 'js::JSCLASS_IS_GLOBAL', - 'js::JSCLASS_RESERVED_SLOTS_MASK', - 'js::JS_CALLEE', 'js::error::throw_type_error', - 'js::jsapi::AutoIdVector', - 'js::jsapi::Call', - 'js::jsapi::CallArgs', - 'js::jsapi::CurrentGlobalOrNull', - 'js::jsapi::FreeOp', - 'js::jsapi::GetPropertyKeys', - 'js::jsapi::GetWellKnownSymbol', - 'js::jsapi::Handle', - 'js::jsapi::HandleId', - 'js::jsapi::HandleObject', - 'js::jsapi::HandleValue', - 'js::jsapi::HandleValueArray', - 'js::jsapi::Heap', - 'js::jsapi::INTERNED_STRING_TO_JSID', - 'js::jsapi::IsCallable', - 'js::jsapi::JSAutoCompartment', - 'js::jsapi::JSCLASS_RESERVED_SLOTS_SHIFT', - 'js::jsapi::JSClass', - 'js::jsapi::JSContext', - 'js::jsapi::JSFreeOp', - 'js::jsapi::JSFunctionSpec', - 'js::jsapi::JSITER_HIDDEN', - 'js::jsapi::JSITER_OWNONLY', - 'js::jsapi::JSITER_SYMBOLS', - 'js::jsapi::JSJitGetterCallArgs', - 'js::jsapi::JSJitInfo', - 'js::jsapi::JSJitInfo_AliasSet', - 'js::jsapi::JSJitInfo_ArgType', - 'js::jsapi::JSJitInfo_OpType', - 'js::jsapi::JSJitMethodCallArgs', - 'js::jsapi::JSJitSetterCallArgs', - 'js::jsapi::JSNative', - 'js::jsapi::JSNativeWrapper', - 'js::jsapi::JSObject', - 'js::jsapi::JSPROP_ENUMERATE', - 'js::jsapi::JSPROP_PERMANENT', - 'js::jsapi::JSPROP_READONLY', - 'js::jsapi::JSPROP_SHARED', - 'js::jsapi::JSPropertySpec', - 'js::jsapi::JSString', - 'js::jsapi::JSTracer', - 'js::jsapi::JSType', - 'js::jsapi::JSTypedMethodJitInfo', - 'js::jsapi::JSValueType', - 'js::jsapi::JS_AtomizeAndPinString', - 'js::jsapi::JS_CallFunctionValue', - 'js::jsapi::JS_CopyPropertiesFrom', - 'js::jsapi::JS_DefineProperty', - 'js::jsapi::JS_DefinePropertyById2', - 'js::jsapi::JS_ForwardGetPropertyTo', - 'js::jsapi::JS_GetErrorPrototype', - 'js::jsapi::JS_GetFunctionPrototype', - 'js::jsapi::JS_GetGlobalForObject', - 'js::jsapi::JS_GetIteratorPrototype', - 'js::jsapi::JS_GetObjectPrototype', - 'js::jsapi::JS_GetProperty', - 'js::jsapi::JS_GetPropertyById', - 'js::jsapi::JS_GetPropertyDescriptorById', - 'js::jsapi::JS_GetReservedSlot', - 'js::jsapi::JS_HasProperty', - 'js::jsapi::JS_HasPropertyById', - 'js::jsapi::JS_InitializePropertiesFromCompatibleNativeObject', - 'js::jsapi::JS_NewObject', - 'js::jsapi::JS_NewObjectWithGivenProto', - 'js::jsapi::JS_NewObjectWithoutMetadata', - 'js::jsapi::JS_ObjectIsDate', - 'js::jsapi::JS_SetImmutablePrototype', - 'js::jsapi::JS_SetProperty', - 'js::jsapi::JS_SetPrototype', - 'js::jsapi::JS_SetReservedSlot', - 'js::jsapi::JS_SplicePrototype', - 'js::jsapi::JS_WrapValue', - 'js::jsapi::JS_WrapObject', - 'js::jsapi::MutableHandle', - 'js::jsapi::MutableHandleObject', - 'js::jsapi::MutableHandleValue', - 'js::jsapi::ObjectOpResult', - 'js::jsapi::PropertyDescriptor', - 'js::jsapi::RootedId', - 'js::jsapi::RootedObject', - 'js::jsapi::RootedString', - 'js::jsapi::SymbolCode', - 'js::jsapi::jsid', - 'js::jsval::JSVal', + 'js::heap::Heap', + 'js::jsapi', + 'js::jsapi::JSCLASS_GLOBAL_SLOT_COUNT', + 'js::jsapi::JSCLASS_IS_DOMJSCLASS', + 'js::jsapi::JSCLASS_IS_GLOBAL', + 'js::jsapi::JSCLASS_RESERVED_SLOTS_MASK', 'js::jsval::NullValue', 'js::jsval::ObjectValue', 'js::jsval::ObjectOrNullValue', @@ -5632,7 +5602,8 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::glue::CallJitMethodOp', 'js::glue::CallJitSetterOp', 'js::glue::CreateProxyHandler', - 'js::glue::GetProxyPrivate', + 'js::glue::GetProxyReservedSlot', + 'js::glue::SetProxyReservedSlot', 'js::glue::NewProxyObject', 'js::glue::ProxyTraps', 'js::glue::RUST_JSID_IS_STRING', @@ -5694,6 +5665,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::utils::get_proto_or_iface_array', 'dom::bindings::utils::has_property_on_prototype', 'dom::bindings::utils::is_platform_object', + 'dom::bindings::utils::leak_as_static', 'dom::bindings::utils::resolve_global', 'dom::bindings::utils::set_dictionary_property', 'dom::bindings::utils::trace_global', @@ -5926,7 +5898,8 @@ def reexportedName(name): if reexports: reexports = ', '.join(map(lambda name: reexportedName(name), reexports)) - cgThings = CGList([CGGeneric('pub use self::%s::{%s};' % (toBindingNamespace(descriptor.name), reexports)), + cgThings = CGList([CGGeneric('pub use self::%s::{%s};' % (toBindingNamespace(descriptor.name), + reexports)), cgThings], '\n') self.cgRoot = cgThings @@ -6057,13 +6030,13 @@ def memberInsert(memberInfo): return string.Template( "impl ${selfName} {\n" - " pub unsafe fn empty(cx: *mut JSContext) -> ${selfName} {\n" - " match ${selfName}::new(cx, HandleValue::null()) {\n" + " pub unsafe fn empty(cx: *mut jsapi::JSContext) -> ${selfName} {\n" + " match ${selfName}::new(cx, jsapi::JS::HandleValue::null()) {\n" " Ok(ConversionResult::Success(v)) => v,\n" " _ => unreachable!(),\n" " }\n" " }\n" - " pub unsafe fn new(cx: *mut JSContext, val: HandleValue) \n" + " pub unsafe fn new(cx: *mut jsapi::JSContext, val: jsapi::JS::HandleValue) \n" " -> Result, ()> {\n" " let object = if val.get().is_null_or_undefined() {\n" " ptr::null_mut()\n" @@ -6083,15 +6056,15 @@ def memberInsert(memberInfo): "\n" "impl FromJSValConvertible for ${selfName} {\n" " type Config = ();\n" - " unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, _option: ())\n" + " unsafe fn from_jsval(cx: *mut jsapi::JSContext, value: jsapi::JS::HandleValue, _option: ())\n" " -> Result, ()> {\n" " ${selfName}::new(cx, value)\n" " }\n" "}\n" "\n" "impl ToJSValConvertible for ${selfName} {\n" - " unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {\n" - " rooted!(in(cx) let obj = JS_NewObject(cx, ptr::null()));\n" + " unsafe fn to_jsval(&self, cx: *mut jsapi::JSContext, rval: jsapi::JS::MutableHandleValue) {\n" + " rooted!(in(cx) let obj = jsapi::JS_NewObject(cx, ptr::null()));\n" "${insertMembers}" " rval.set(ObjectOrNullValue(obj.get()))\n" " }\n" @@ -6349,7 +6322,7 @@ def argument_type(descriptorProvider, ty, optional=False, defaultValue=None, var def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, trailing=None): if needCx(returnType, arguments, passJSBits): - yield "cx", "*mut JSContext" + yield "cx", "*mut jsapi::JSContext" for argument in arguments: ty = argument_type(descriptorProvider, argument.type, argument.optional, @@ -6372,7 +6345,7 @@ def __init__(self, descriptorProvider, member, name, signature, extendedAttrs, breakAfter=True, passJSBitsAsNeeded=True, visibility="public"): """ If passJSBitsAsNeeded is false, we don't automatically pass in a - JSContext* or a JSObject* based on the return and argument types. + jsapi::JSContext* or a jsapi::JSObject* based on the return and argument types. """ self.descriptorProvider = descriptorProvider self.member = member @@ -6428,7 +6401,7 @@ def __init__(self, idlObject, descriptorProvider, baseName, methods, def getConstructors(self): return [ClassConstructor( - [Argument("*mut JSContext", "aCx"), Argument("*mut JSObject", "aCallback")], + [Argument("*mut jsapi::JSContext", "aCx"), Argument("*mut jsapi::JSObject", "aCallback")], bodyInHeader=True, visibility="pub", explicit=False, @@ -6439,10 +6412,10 @@ def getConstructors(self): def getMethodImpls(self, method): assert method.needThisHandling args = list(method.args) - # Strip out the JSContext*/JSObject* args + # Strip out the jsapi::JSContext*/jsapi::JSObject* args # that got added. - assert args[0].name == "cx" and args[0].argType == "*mut JSContext" - assert args[1].name == "aThisObj" and args[1].argType == "HandleObject" + assert args[0].name == "cx" and args[0].argType == "*mut jsapi::JSContext" + assert args[1].name == "aThisObj" and args[1].argType == "jsapi::JS::HandleObject" args = args[2:] # Record the names of all the arguments, so we can use them when we call # the private method. @@ -6524,7 +6497,7 @@ class CGCallbackFunctionImpl(CGGeneric): def __init__(self, callback): impl = string.Template("""\ impl CallbackContainer for ${type} { - unsafe fn new(cx: *mut JSContext, callback: *mut JSObject) -> Rc<${type}> { + unsafe fn new(cx: *mut jsapi::JSContext, callback: *mut jsapi::JSObject) -> Rc<${type}> { ${type}::new(cx, callback) } @@ -6534,7 +6507,7 @@ def __init__(self, callback): } impl ToJSValConvertible for ${type} { - unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { + unsafe fn to_jsval(&self, cx: *mut jsapi::JSContext, rval: jsapi::JS::MutableHandleValue) { self.callback().to_jsval(cx, rval); } }\ @@ -6728,9 +6701,9 @@ def getArgs(self, returnType, argList): "ReportExceptions")) return args # We want to allow the caller to pass in a "this" object, as - # well as a JSContext. - return [Argument("*mut JSContext", "cx"), - Argument("HandleObject", "aThisObj")] + args + # well as a jsapi::JSContext. + return [Argument("*mut jsapi::JSContext", "cx"), + Argument("jsapi::JS::HandleObject", "aThisObj")] + args def getCallSetup(self): if self.needThisHandling: @@ -6738,7 +6711,7 @@ def getCallSetup(self): return "" return ( "CallSetup s(CallbackPreserveColor(), aRv, aExceptionHandling);\n" - "JSContext* cx = s.get_context();\n" + "jsapi::JSContext* cx = s.get_context();\n" "if (!cx) {\n" " return Err(JSFailed);\n" "}\n") @@ -6779,7 +6752,7 @@ def getCall(self): "callGuard": self.getCallGuard(), } if self.argCount > 0: - replacements["argv"] = "argv.as_ptr() as *const JSVal" + replacements["argv"] = "argv.as_ptr() as *const jsapi::JS::Value" replacements["argc"] = "argc" else: replacements["argv"] = "ptr::null_mut()" @@ -6787,9 +6760,9 @@ def getCall(self): return string.Template( "${getCallable}" "rooted!(in(cx) let rootedThis = ${thisObj});\n" - "let ok = ${callGuard}JS_CallFunctionValue(\n" + "let ok = ${callGuard}jsapi::JS_CallFunctionValue(\n" " cx, rootedThis.handle(), callable.handle(),\n" - " &HandleValueArray {\n" + " &jsapi::JS::HandleValueArray {\n" " length_: ${argc} as ::libc::size_t,\n" " elements_: ${argv}\n" " }, rval.handle_mut());\n" @@ -6813,7 +6786,7 @@ def getCallableDecl(self): def getCallGuard(self): if self.callback._treatNonObjectAsNull: - return "!IsCallable(self.callback()) || " + return "!jsapi::JS::IsCallable(self.callback()) || " return "" @@ -6844,7 +6817,7 @@ def getCallableDecl(self): if not self.singleOperation: return 'rooted!(in(cx) let callable =\n' + getCallableFromProp + ');\n' return ( - 'let isCallable = IsCallable(self.callback());\n' + 'let isCallable = jsapi::JS::IsCallable(self.callback());\n' 'rooted!(in(cx) let callable =\n' + CGIndenter( CGIfElseWrapper('isCallable', @@ -6879,14 +6852,14 @@ def __init__(self, attr, descriptor): needThisHandling=False) def getRvalDecl(self): - return "JS::Rooted rval(cx, JS::UndefinedValue());\n" + return "jsapi::JS::Rooted rval(cx, JS::UndefinedValue());\n" def getCall(self): replacements = { "attrName": self.attrName } return string.Template( - 'if (!JS_GetProperty(cx, mCallback, "${attrName}", &rval)) {\n' + 'if (!jsapi::JS_GetProperty(cx, mCallback, "${attrName}", &rval)) {\n' ' return Err(JSFailed);\n' '}\n').substitute(replacements) @@ -6913,7 +6886,7 @@ def getCall(self): } return string.Template( 'MOZ_ASSERT(argv.length() == 1);\n' - 'if (!JS_SetProperty(cx, mCallback, "${attrName}", ${argv})) {\n' + 'if (!jsapi::JS_SetProperty(cx, mCallback, "${attrName}", ${argv})) {\n' ' return Err(JSFailed);\n' '}\n').substitute(replacements) @@ -6932,7 +6905,7 @@ def __init__(self, descriptor, iterable, methodName): if methodName == "forEach": CGGeneric.__init__(self, fill( """ - if !IsCallable(arg0) { + if !jsapi::JS::IsCallable(arg0) { throw_type_error(cx, "Argument 1 of ${ifaceName}.forEach is not callable."); return false; } @@ -6946,8 +6919,8 @@ def __init__(self, descriptor, iterable, methodName): (*this).get_key_at_index(i).to_jsval(cx, call_arg2.handle_mut()); call_args[0] = call_arg1.handle().get(); call_args[1] = call_arg2.handle().get(); - let call_args = HandleValueArray { length_: 3, elements_: call_args.as_ptr() }; - if !Call(cx, arg1, arg0.handle(), &call_args, + let call_args = jsapi::JS::HandleValueArray { length_: 3, elements_: call_args.as_ptr() }; + if !jsapi::JS::Call(cx, arg1, arg0.handle(), &call_args, ignoredReturnVal.handle_mut()) { return false; } @@ -6995,7 +6968,7 @@ class GlobalGenRoots(): def InterfaceObjectMap(config): mods = [ "dom::bindings::codegen", - "js::jsapi::{HandleObject, JSContext}", + "js::jsapi", "phf", ] imports = CGList([CGGeneric("use %s;" % mod) for mod in mods], "\n") @@ -7052,9 +7025,9 @@ def PrototypeList(config): CGGeneric(AUTOGENERATED_WARNING_COMMENT), CGGeneric("pub const PROTO_OR_IFACE_LENGTH: usize = %d;\n" % (len(protos) + len(constructors))), CGGeneric("pub const MAX_PROTO_CHAIN_LENGTH: usize = %d;\n\n" % config.maxProtoChainLength), - CGNonNamespacedEnum('ID', protos, 0, deriving="PartialEq, Copy, Clone", repr="u16"), + CGNonNamespacedEnum('ID', protos, 0, deriving="PartialEq, Copy, Clone, Debug", repr="u16"), CGNonNamespacedEnum('Constructor', constructors, len(protos), - deriving="PartialEq, Copy, Clone", repr="u16"), + deriving="PartialEq, Copy, Clone, Debug", repr="u16"), CGWrapper(CGIndenter(CGList([CGGeneric('"' + name + '"') for name in protos], ",\n"), indentLevel=4), @@ -7064,7 +7037,7 @@ def PrototypeList(config): " debug_assert!(proto_id < ID::Last as u16);\n" " INTERFACES[proto_id as usize]\n" "}\n\n"), - CGNonNamespacedEnum('Proxies', proxies, 0, deriving="PartialEq, Copy, Clone"), + CGNonNamespacedEnum('Proxies', proxies, 0, deriving="PartialEq, Copy, Clone, Debug"), ]) @staticmethod @@ -7116,7 +7089,7 @@ def InheritTypes(config): CGGeneric("use dom::bindings::js::{JS, LayoutJS, Root};\n"), CGGeneric("use dom::bindings::trace::JSTraceable;\n"), CGGeneric("use dom::bindings::reflector::DomObject;\n"), - CGGeneric("use js::jsapi::JSTracer;\n\n"), + CGGeneric("use js::jsapi;\n\n"), CGGeneric("use std::mem;\n\n")] allprotos = [] topTypes = [] @@ -7161,6 +7134,15 @@ def InheritTypes(config): pre="#[derive(Copy)]\npub union TopTypeId {\n", post="\n}\n\n")) + typeIdCode.append(CGGeneric("""\ +impl ::std::fmt::Debug for TopTypeId { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + write!(f, \"TopTypeId\") + } +} + +""")) + typeIdCode.append(CGGeneric("""\ impl Clone for TopTypeId { fn clone(&self) -> Self { *self } diff --git a/components/script/dom/bindings/codegen/parser/WebIDL.py b/components/script/dom/bindings/codegen/parser/WebIDL.py index 820dc108fbfe..f6bfb551b95c 100644 --- a/components/script/dom/bindings/codegen/parser/WebIDL.py +++ b/components/script/dom/bindings/codegen/parser/WebIDL.py @@ -2886,7 +2886,7 @@ def _getDependentObjects(self): # On the other hand, if our type is a dictionary, we should # depend on it, because the member types of a dictionary # affect whether a method taking the dictionary as an argument - # takes a JSContext* argument or not. + # takes a jsapi::JSContext* argument or not. if self.isDictionary(): return set([self.inner]) return set() diff --git a/components/script/dom/bindings/constant.rs b/components/script/dom/bindings/constant.rs index 42f10055080f..39f4e85bb82f 100644 --- a/components/script/dom/bindings/constant.rs +++ b/components/script/dom/bindings/constant.rs @@ -4,9 +4,8 @@ //! WebIDL constants. -use js::jsapi::{HandleObject, JSContext, JSPROP_ENUMERATE, JSPROP_PERMANENT}; -use js::jsapi::{JSPROP_READONLY, JS_DefineProperty}; -use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UInt32Value}; +use js::jsapi; +use js::jsval::{BooleanValue, DoubleValue, Int32Value, NullValue, UInt32Value}; use libc; /// Representation of an IDL constant. @@ -35,8 +34,8 @@ pub enum ConstantVal { } impl ConstantSpec { - /// Returns a `JSVal` that represents the value of this `ConstantSpec`. - pub fn get_value(&self) -> JSVal { + /// Returns a `jsapi::JS::Value` that represents the value of this `ConstantSpec`. + pub fn get_value(&self) -> jsapi::JS::Value { match self.value { ConstantVal::NullVal => NullValue(), ConstantVal::IntVal(i) => Int32Value(i), @@ -50,17 +49,19 @@ impl ConstantSpec { /// Defines constants on `obj`. /// Fails on JSAPI failure. pub unsafe fn define_constants( - cx: *mut JSContext, - obj: HandleObject, + cx: *mut jsapi::JSContext, + obj: jsapi::JS::HandleObject, constants: &[ConstantSpec]) { for spec in constants { rooted!(in(cx) let value = spec.get_value()); - assert!(JS_DefineProperty(cx, - obj, - spec.name.as_ptr() as *const libc::c_char, - value.handle(), - JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT, - None, - None)); + assert!(jsapi::JS_DefineProperty(cx, + obj, + spec.name.as_ptr() as *const libc::c_char, + value.handle(), + (jsapi::JSPROP_ENUMERATE | + jsapi::JSPROP_READONLY | + jsapi::JSPROP_PERMANENT) as _, + None, + None)); } } diff --git a/components/script/dom/bindings/conversions.rs b/components/script/dom/bindings/conversions.rs index 9afae9f68046..4a0a7659ae8c 100644 --- a/components/script/dom/bindings/conversions.rs +++ b/components/script/dom/bindings/conversions.rs @@ -2,35 +2,35 @@ * 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/. */ -//! Conversions of Rust values to and from `JSVal`. +//! Conversions of Rust values to and from `jsapi::JS::Value`. //! -//! | IDL type | Argument type | Return type | -//! |-------------------------|-----------------|----------------| -//! | any | `JSVal` | -//! | boolean | `bool` | -//! | byte | `i8` | -//! | octet | `u8` | -//! | short | `i16` | -//! | unsigned short | `u16` | -//! | long | `i32` | -//! | unsigned long | `u32` | -//! | long long | `i64` | -//! | unsigned long long | `u64` | -//! | unrestricted float | `f32` | -//! | float | `Finite` | -//! | unrestricted double | `f64` | -//! | double | `Finite` | -//! | DOMString | `DOMString` | -//! | USVString | `USVString` | -//! | ByteString | `ByteString` | -//! | object | `*mut JSObject` | -//! | interface types | `&T` | `Root` | -//! | dictionary types | `&T` | *unsupported* | -//! | enumeration types | `T` | -//! | callback function types | `Rc` | -//! | nullable types | `Option` | -//! | sequences | `Vec` | -//! | union types | `T` | +//! | IDL type | Argument type | Return type | +//! |-------------------------|------------------------|----------------| +//! | any | `jsapi::JS::Value` | +//! | boolean | `bool` | +//! | byte | `i8` | +//! | octet | `u8` | +//! | short | `i16` | +//! | unsigned short | `u16` | +//! | long | `i32` | +//! | unsigned long | `u32` | +//! | long long | `i64` | +//! | unsigned long long | `u64` | +//! | unrestricted float | `f32` | +//! | float | `Finite` | +//! | unrestricted double | `f64` | +//! | double | `Finite` | +//! | DOMString | `DOMString` | +//! | USVString | `USVString` | +//! | ByteString | `ByteString` | +//! | object | `*mut jsapi::JSObject` | +//! | interface types | `&T` | `Root` | +//! | dictionary types | `&T` | *unsupported* | +//! | enumeration types | `T` | +//! | callback function types | `Rc` | +//! | nullable types | `Option` | +//! | sequences | `Vec` | +//! | union types | `T` | use dom::bindings::error::{Error, Fallible}; use dom::bindings::inheritance::Castable; @@ -40,18 +40,14 @@ use dom::bindings::reflector::{DomObject, Reflector}; use dom::bindings::str::{ByteString, DOMString, USVString}; use dom::bindings::trace::{JSTraceable, RootedTraceableBox}; use dom::bindings::utils::DOMClass; -use js; pub use js::conversions::{FromJSValConvertible, ToJSValConvertible, ConversionResult}; pub use js::conversions::ConversionBehavior; use js::conversions::latin1_to_string; use js::error::throw_type_error; -use js::glue::{GetProxyPrivate, IsWrapper}; +use js::glue::{GetProxyReservedSlot, IsWrapper}; use js::glue::{RUST_JSID_IS_INT, RUST_JSID_TO_INT}; use js::glue::{RUST_JSID_IS_STRING, RUST_JSID_TO_STRING, UnwrapObject}; -use js::jsapi::{HandleId, HandleObject, HandleValue, JSContext, JSObject, JSString}; -use js::jsapi::{JS_GetLatin1StringCharsAndLength, JS_GetProperty, JS_GetReservedSlot}; -use js::jsapi::{JS_GetTwoByteStringCharsAndLength, JS_IsArrayObject, JS_IsExceptionPending}; -use js::jsapi::{JS_NewStringCopyN, JS_StringHasLatin1Chars, MutableHandleValue}; +use js::jsapi; use js::jsval::{ObjectValue, StringValue, UndefinedValue}; use js::rust::{ToString, get_object_class, is_dom_class, is_dom_object, maybe_wrap_value}; use libc; @@ -59,7 +55,7 @@ use num_traits::Float; use servo_config::opts; use std::{char, ffi, ptr, slice}; -/// A trait to check whether a given `JSObject` implements an IDL interface. +/// A trait to check whether a given `jsapi::JSObject` implements an IDL interface. pub trait IDLInterface { /// Returns whether the given DOM class derives that interface. fn derives(&'static DOMClass) -> bool; @@ -71,7 +67,7 @@ pub trait DerivedFrom: Castable {} impl ToJSValConvertible for Finite { #[inline] - unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { + unsafe fn to_jsval(&self, cx: *mut jsapi::JSContext, rval: jsapi::JS::MutableHandleValue) { let value = **self; value.to_jsval(cx, rval); } @@ -80,8 +76,8 @@ impl ToJSValConvertible for Finite { impl> FromJSValConvertible for Finite { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, - value: HandleValue, + unsafe fn from_jsval(cx: *mut jsapi::JSContext, + value: jsapi::JS::HandleValue, option: ()) -> Result>, ()> { let result = match FromJSValConvertible::from_jsval(cx, value, option) { @@ -105,8 +101,8 @@ impl> FromJSValConvertible for Finite impl FromJSValConvertible for Root { type Config = (); - unsafe fn from_jsval(_cx: *mut JSContext, - value: HandleValue, + unsafe fn from_jsval(_cx: *mut jsapi::JSContext, + value: jsapi::JS::HandleValue, _config: Self::Config) -> Result>, ()> { Ok(match root_from_handlevalue(value) { @@ -119,8 +115,8 @@ impl FromJSValConvertible for Root { impl FromJSValConvertible for RootedTraceableBox { type Config = T::Config; - unsafe fn from_jsval(cx: *mut JSContext, - value: HandleValue, + unsafe fn from_jsval(cx: *mut jsapi::JSContext, + value: jsapi::JS::HandleValue, config: Self::Config) -> Result, ()> { T::from_jsval(cx, value, config).map(|result| { @@ -139,7 +135,7 @@ impl FromJSValConvertible for RootedTrac /// # Panics /// /// Panics if `id` is not string-valued. -pub fn string_jsid_to_string(cx: *mut JSContext, id: HandleId) -> DOMString { +pub fn string_jsid_to_string(cx: *mut jsapi::JSContext, id: jsapi::JS::HandleId) -> DOMString { unsafe { assert!(RUST_JSID_IS_STRING(id)); jsstring_to_str(cx, RUST_JSID_TO_STRING(id)) @@ -150,7 +146,7 @@ pub fn string_jsid_to_string(cx: *mut JSContext, id: HandleId) -> DOMString { /// integer. /// /// Handling of invalid UTF-16 in strings depends on the relevant option. -pub unsafe fn jsid_to_string(cx: *mut JSContext, id: HandleId) -> Option { +pub unsafe fn jsid_to_string(cx: *mut jsapi::JSContext, id: jsapi::JS::HandleId) -> Option { if RUST_JSID_IS_STRING(id) { return Some(jsstring_to_str(cx, RUST_JSID_TO_STRING(id))); } @@ -164,12 +160,12 @@ pub unsafe fn jsid_to_string(cx: *mut JSContext, id: HandleId) -> Option Result, ()> { if null_behavior == StringificationBehavior::Empty && @@ -207,15 +203,15 @@ impl FromJSValConvertible for DOMString { } } -/// Convert the given `JSString` to a `DOMString`. Fails if the string does not -/// contain valid UTF-16. -pub unsafe fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString { - let latin1 = JS_StringHasLatin1Chars(s); +/// Convert the given `jsapi::JSString` to a `DOMString`. Fails if the string +/// does not contain valid UTF-16. +pub unsafe fn jsstring_to_str(cx: *mut jsapi::JSContext, s: *mut jsapi::JSString) -> DOMString { + let latin1 = jsapi::JS_StringHasLatin1Chars(s); DOMString::from_string(if latin1 { latin1_to_string(cx, s) } else { let mut length = 0; - let chars = JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), s, &mut length); + let chars = jsapi::JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), s, &mut length); assert!(!chars.is_null()); let potentially_ill_formed_utf16 = slice::from_raw_parts(chars, length as usize); let mut s = String::with_capacity(length as usize); @@ -248,21 +244,21 @@ pub unsafe fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString // http://heycam.github.io/webidl/#es-USVString impl FromJSValConvertible for USVString { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, _: ()) + unsafe fn from_jsval(cx: *mut jsapi::JSContext, value: jsapi::JS::HandleValue, _: ()) -> Result, ()> { let jsstr = ToString(cx, value); if jsstr.is_null() { debug!("ToString failed"); return Err(()); } - let latin1 = JS_StringHasLatin1Chars(jsstr); + let latin1 = jsapi::JS_StringHasLatin1Chars(jsstr); if latin1 { // FIXME(ajeffrey): Convert directly from DOMString to USVString return Ok(ConversionResult::Success( USVString(String::from(jsstring_to_str(cx, jsstr))))); } let mut length = 0; - let chars = JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), jsstr, &mut length); + let chars = jsapi::JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), jsstr, &mut length); assert!(!chars.is_null()); let char_vec = slice::from_raw_parts(chars as *const u16, length as usize); Ok(ConversionResult::Success(USVString(String::from_utf16_lossy(char_vec)))) @@ -271,12 +267,12 @@ impl FromJSValConvertible for USVString { // http://heycam.github.io/webidl/#es-ByteString impl ToJSValConvertible for ByteString { - unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { - let jsstr = JS_NewStringCopyN(cx, + unsafe fn to_jsval(&self, cx: *mut jsapi::JSContext, rval: jsapi::JS::MutableHandleValue) { + let jsstr = jsapi::JS_NewStringCopyN(cx, self.as_ptr() as *const libc::c_char, self.len() as libc::size_t); if jsstr.is_null() { - panic!("JS_NewStringCopyN failed"); + panic!("jsapi::JS_NewStringCopyN failed"); } rval.set(StringValue(&*jsstr)); } @@ -285,8 +281,8 @@ impl ToJSValConvertible for ByteString { // http://heycam.github.io/webidl/#es-ByteString impl FromJSValConvertible for ByteString { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, - value: HandleValue, + unsafe fn from_jsval(cx: *mut jsapi::JSContext, + value: jsapi::JS::HandleValue, _option: ()) -> Result, ()> { let string = ToString(cx, value); @@ -295,10 +291,10 @@ impl FromJSValConvertible for ByteString { return Err(()); } - let latin1 = JS_StringHasLatin1Chars(string); + let latin1 = jsapi::JS_StringHasLatin1Chars(string); if latin1 { let mut length = 0; - let chars = JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length); + let chars = jsapi::JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length); assert!(!chars.is_null()); let char_slice = slice::from_raw_parts(chars as *mut u8, length as usize); @@ -306,7 +302,7 @@ impl FromJSValConvertible for ByteString { } let mut length = 0; - let chars = JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), string, &mut length); + let chars = jsapi::JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), string, &mut length); let char_vec = slice::from_raw_parts(chars, length as usize); if char_vec.iter().any(|&c| c > 0xFF) { @@ -321,7 +317,7 @@ impl FromJSValConvertible for ByteString { impl ToJSValConvertible for Reflector { - unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { + unsafe fn to_jsval(&self, cx: *mut jsapi::JSContext, rval: jsapi::JS::MutableHandleValue) { let obj = self.get_jsobject().get(); assert!(!obj.is_null()); rval.set(ObjectValue(obj)); @@ -330,11 +326,11 @@ impl ToJSValConvertible for Reflector { } /// Returns whether `obj` is a DOM object implemented as a proxy. -pub fn is_dom_proxy(obj: *mut JSObject) -> bool { +pub fn is_dom_proxy(obj: *mut jsapi::JSObject) -> bool { use js::glue::IsProxyHandlerFamily; unsafe { let clasp = get_object_class(obj); - ((*clasp).flags & js::JSCLASS_IS_PROXY) != 0 && IsProxyHandlerFamily(obj) != 0 + ((*clasp).flags & jsapi::JSCLASS_IS_PROXY) != 0 && IsProxyHandlerFamily(obj) != 0 } } @@ -345,12 +341,12 @@ pub fn is_dom_proxy(obj: *mut JSObject) -> bool { pub const DOM_OBJECT_SLOT: u32 = 0; /// Get the private pointer of a DOM object from a given reflector. -pub unsafe fn private_from_object(obj: *mut JSObject) -> *const libc::c_void { +pub unsafe fn private_from_object(obj: *mut jsapi::JSObject) -> *const libc::c_void { let value = if is_dom_object(obj) { - JS_GetReservedSlot(obj, DOM_OBJECT_SLOT) + jsapi::JS_GetReservedSlot(obj, DOM_OBJECT_SLOT) } else { debug_assert!(is_dom_proxy(obj)); - GetProxyPrivate(obj) + GetProxyReservedSlot(obj, 0) }; if value.is_undefined() { ptr::null() @@ -360,7 +356,7 @@ pub unsafe fn private_from_object(obj: *mut JSObject) -> *const libc::c_void { } /// Get the `DOMClass` from `obj`, or `Err(())` if `obj` is not a DOM object. -pub unsafe fn get_dom_class(obj: *mut JSObject) -> Result<&'static DOMClass, ()> { +pub unsafe fn get_dom_class(obj: *mut jsapi::JSObject) -> Result<&'static DOMClass, ()> { use dom::bindings::utils::DOMJSClass; use js::glue::GetProxyHandlerExtra; @@ -386,7 +382,7 @@ pub unsafe fn get_dom_class(obj: *mut JSObject) -> Result<&'static DOMClass, ()> /// not an object for a DOM object of the given type (as defined by the /// proto_id and proto_depth). #[inline] -pub unsafe fn private_from_proto_check(mut obj: *mut JSObject, +pub unsafe fn private_from_proto_check(mut obj: *mut jsapi::JSObject, proto_check: F) -> Result<*const libc::c_void, ()> where F: Fn(&'static DOMClass) -> bool @@ -418,8 +414,8 @@ pub unsafe fn private_from_proto_check(mut obj: *mut JSObject, } } -/// Get a `*const T` for a DOM object accessible from a `JSObject`. -pub fn native_from_object(obj: *mut JSObject) -> Result<*const T, ()> +/// Get a `*const T` for a DOM object accessible from a `jsapi::JSObject`. +pub fn native_from_object(obj: *mut jsapi::JSObject) -> Result<*const T, ()> where T: DomObject + IDLInterface { unsafe { @@ -433,7 +429,7 @@ pub fn native_from_object(obj: *mut JSObject) -> Result<*const T, ()> /// Returns Err(()) if `obj` is an opaque security wrapper or if the object is /// not a reflector for a DOM object of the given type (as defined by the /// proto_id and proto_depth). -pub fn root_from_object(obj: *mut JSObject) -> Result, ()> +pub fn root_from_object(obj: *mut jsapi::JSObject) -> Result, ()> where T: DomObject + IDLInterface { native_from_object(obj).map(|ptr| unsafe { Root::from_ref(&*ptr) }) @@ -441,7 +437,7 @@ pub fn root_from_object(obj: *mut JSObject) -> Result, ()> /// Get a `*const T` for a DOM object accessible from a `HandleValue`. /// Caller is responsible for throwing a JS exception if needed in case of error. -pub fn native_from_handlevalue(v: HandleValue) -> Result<*const T, ()> +pub fn native_from_handlevalue(v: jsapi::JS::HandleValue) -> Result<*const T, ()> where T: DomObject + IDLInterface { if !v.get().is_object() { @@ -452,7 +448,7 @@ pub fn native_from_handlevalue(v: HandleValue) -> Result<*const T, ()> /// Get a `Root` for a DOM object accessible from a `HandleValue`. /// Caller is responsible for throwing a JS exception if needed in case of error. -pub fn root_from_handlevalue(v: HandleValue) -> Result, ()> +pub fn root_from_handlevalue(v: jsapi::JS::HandleValue) -> Result, ()> where T: DomObject + IDLInterface { if !v.get().is_object() { @@ -462,14 +458,14 @@ pub fn root_from_handlevalue(v: HandleValue) -> Result, ()> } /// Get a `Root` for a DOM object accessible from a `HandleObject`. -pub fn root_from_handleobject(obj: HandleObject) -> Result, ()> +pub fn root_from_handleobject(obj: jsapi::JS::HandleObject) -> Result, ()> where T: DomObject + IDLInterface { root_from_object(obj.get()) } impl ToJSValConvertible for Root { - unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { + unsafe fn to_jsval(&self, cx: *mut jsapi::JSContext, rval: jsapi::JS::MutableHandleValue) { self.reflector().to_jsval(cx, rval); } } @@ -477,17 +473,17 @@ impl ToJSValConvertible for Root { /// Returns whether `value` is an array-like object. /// Note: Currently only Arrays are supported. /// TODO: Expand this to support sequences and other array-like objects -pub unsafe fn is_array_like(cx: *mut JSContext, value: HandleValue) -> bool { +pub unsafe fn is_array_like(cx: *mut jsapi::JSContext, value: jsapi::JS::HandleValue) -> bool { let mut result = false; - assert!(JS_IsArrayObject(cx, value, &mut result)); + assert!(jsapi::JS_IsArrayObject(cx, value, &mut result)); result } /// Get a property from a JS object. -pub unsafe fn get_property_jsval(cx: *mut JSContext, - object: HandleObject, +pub unsafe fn get_property_jsval(cx: *mut jsapi::JSContext, + object: jsapi::JS::HandleObject, name: &str, - rval: MutableHandleValue) + rval: jsapi::JS::MutableHandleValue) -> Fallible<()> { rval.set(UndefinedValue()); @@ -495,16 +491,16 @@ pub unsafe fn get_property_jsval(cx: *mut JSContext, Ok(cname) => cname, Err(_) => return Ok(()), }; - JS_GetProperty(cx, object, cname.as_ptr(), rval); - if JS_IsExceptionPending(cx) { + jsapi::JS_GetProperty(cx, object, cname.as_ptr(), rval); + if jsapi::JS_IsExceptionPending(cx) { return Err(Error::JSFailed); } Ok(()) } /// Get a property from a JS object, and convert it to a Rust value. -pub unsafe fn get_property(cx: *mut JSContext, - object: HandleObject, +pub unsafe fn get_property(cx: *mut jsapi::JSContext, + object: jsapi::JS::HandleObject, name: &str, option: T::Config) -> Fallible> where diff --git a/components/script/dom/bindings/error.rs b/components/script/dom/bindings/error.rs index 2cbbe2da647d..541aa5ea15d8 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -12,14 +12,7 @@ use dom::bindings::str::USVString; use dom::domexception::{DOMErrorName, DOMException}; use dom::globalscope::GlobalScope; use js::error::{throw_range_error, throw_type_error}; -use js::jsapi::HandleObject; -use js::jsapi::JSContext; -use js::jsapi::JS_ClearPendingException; -use js::jsapi::JS_ErrorFromException; -use js::jsapi::JS_GetPendingException; -use js::jsapi::JS_IsExceptionPending; -use js::jsapi::JS_SetPendingException; -use js::jsapi::MutableHandleValue; +use js::jsapi; use js::jsval::UndefinedValue; use libc::c_uint; use std::slice::from_raw_parts; @@ -87,7 +80,7 @@ pub type Fallible = Result; pub type ErrorResult = Fallible<()>; /// Set a pending exception for the given `result` on `cx`. -pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) { +pub unsafe fn throw_dom_exception(cx: *mut jsapi::JSContext, global: &GlobalScope, result: Error) { let code = match result { Error::IndexSize => DOMErrorName::IndexSizeError, Error::NotFound => DOMErrorName::NotFoundError, @@ -111,26 +104,26 @@ pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, resu Error::TypeMismatch => DOMErrorName::TypeMismatchError, Error::InvalidModification => DOMErrorName::InvalidModificationError, Error::Type(message) => { - assert!(!JS_IsExceptionPending(cx)); + assert!(!jsapi::JS_IsExceptionPending(cx)); throw_type_error(cx, &message); return; }, Error::Range(message) => { - assert!(!JS_IsExceptionPending(cx)); + assert!(!jsapi::JS_IsExceptionPending(cx)); throw_range_error(cx, &message); return; }, Error::JSFailed => { - assert!(JS_IsExceptionPending(cx)); + assert!(jsapi::JS_IsExceptionPending(cx)); return; } }; - assert!(!JS_IsExceptionPending(cx)); + assert!(!jsapi::JS_IsExceptionPending(cx)); let exception = DOMException::new(global, code); rooted!(in(cx) let mut thrown = UndefinedValue()); exception.to_jsval(cx, thrown.handle_mut()); - JS_SetPendingException(cx, thrown.handle()); + jsapi::JS_SetPendingException(cx, thrown.handle()); } /// A struct encapsulating information about a runtime script error. @@ -146,43 +139,37 @@ pub struct ErrorInfo { } impl ErrorInfo { - unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) + unsafe fn from_native_error(cx: *mut jsapi::JSContext, object: jsapi::JS::HandleObject) -> Option { - let report = JS_ErrorFromException(cx, object); + let report = jsapi::JS_ErrorFromException(cx, object); if report.is_null() { return None; } - let filename = { - let filename = (*report).filename as *const u8; - if !filename.is_null() { - let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap(); - let filename = from_raw_parts(filename, length as usize); - String::from_utf8_lossy(filename).into_owned() - } else { - "none".to_string() - } - }; - - let lineno = (*report).lineno; - let column = (*report).column; + // TODO(fitzgen): Errors now have zero or more "notes", each of which + // may have a filename, line, and column. However, these notes are + // behind `UniquePtr`s that are too complicated for bindgen to + // understand at the moment. + let filename = "none".to_string(); + let lineno = 0; + let column = 0; let message = { - let message = (*report).ucmessage; + let message = (*report)._base.message_.data_; let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap(); - let message = from_raw_parts(message, length as usize); - String::from_utf16_lossy(message) + let message = from_raw_parts(message as *const u8, length as usize); + String::from_utf8_lossy(message) }; Some(ErrorInfo { filename: filename, - message: message, + message: message.to_string(), lineno: lineno, column: column, }) } - fn from_dom_exception(object: HandleObject) -> Option { + fn from_dom_exception(object: jsapi::JS::HandleObject) -> Option { let exception = match root_from_object::(object.get()) { Ok(exception) => exception, Err(_) => return None, @@ -201,17 +188,17 @@ impl ErrorInfo { /// /// The `dispatch_event` argument is temporary and non-standard; passing false /// prevents dispatching the `error` event. -pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) { - if !JS_IsExceptionPending(cx) { return; } +pub unsafe fn report_pending_exception(cx: *mut jsapi::JSContext, dispatch_event: bool) { + if !jsapi::JS_IsExceptionPending(cx) { return; } rooted!(in(cx) let mut value = UndefinedValue()); - if !JS_GetPendingException(cx, value.handle_mut()) { - JS_ClearPendingException(cx); - error!("Uncaught exception: JS_GetPendingException failed"); + if !jsapi::JS_GetPendingException(cx, value.handle_mut()) { + jsapi::JS_ClearPendingException(cx); + error!("Uncaught exception: jsapi::JS_GetPendingException failed"); return; } - JS_ClearPendingException(cx); + jsapi::JS_ClearPendingException(cx); let error_info = if value.is_object() { rooted!(in(cx) let object = value.to_object()); ErrorInfo::from_native_error(cx, object.handle()) @@ -252,18 +239,18 @@ pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) } } -/// Throw an exception to signal that a `JSVal` can not be converted to any of +/// Throw an exception to signal that a `jsapi::JS::Value` can not be converted to any of /// the types in an IDL union type. -pub unsafe fn throw_not_in_union(cx: *mut JSContext, names: &'static str) { - assert!(!JS_IsExceptionPending(cx)); +pub unsafe fn throw_not_in_union(cx: *mut jsapi::JSContext, names: &'static str) { + assert!(!jsapi::JS_IsExceptionPending(cx)); let error = format!("argument could not be converted to any of: {}", names); throw_type_error(cx, &error); } -/// Throw an exception to signal that a `JSObject` can not be converted to a +/// Throw an exception to signal that a `jsapi::JSObject` can not be converted to a /// given DOM type. -pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) { - debug_assert!(!JS_IsExceptionPending(cx)); +pub unsafe fn throw_invalid_this(cx: *mut jsapi::JSContext, proto_id: u16) { + debug_assert!(!jsapi::JS_IsExceptionPending(cx)); let error = format!("\"this\" object does not implement interface {}.", proto_id_to_name(proto_id)); throw_type_error(cx, &error); @@ -271,11 +258,11 @@ pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) { impl Error { /// Convert this error value to a JS value, consuming it in the process. - pub unsafe fn to_jsval(self, cx: *mut JSContext, global: &GlobalScope, rval: MutableHandleValue) { - assert!(!JS_IsExceptionPending(cx)); + pub unsafe fn to_jsval(self, cx: *mut jsapi::JSContext, global: &GlobalScope, rval: jsapi::JS::MutableHandleValue) { + assert!(!jsapi::JS_IsExceptionPending(cx)); throw_dom_exception(cx, global, self); - assert!(JS_IsExceptionPending(cx)); - assert!(JS_GetPendingException(cx, rval)); - JS_ClearPendingException(cx); + assert!(jsapi::JS_IsExceptionPending(cx)); + assert!(jsapi::JS_GetPendingException(cx, rval)); + jsapi::JS_ClearPendingException(cx); } } diff --git a/components/script/dom/bindings/guard.rs b/components/script/dom/bindings/guard.rs index 25a52fbe84c1..ec4f0939666e 100644 --- a/components/script/dom/bindings/guard.rs +++ b/components/script/dom/bindings/guard.rs @@ -4,7 +4,7 @@ //! Machinery to conditionally expose things. -use js::jsapi::{HandleObject, JSContext}; +use js::jsapi; use servo_config::prefs::PREFS; /// A container with a condition. @@ -25,7 +25,7 @@ impl Guard { /// Expose the value if the condition is satisfied. /// /// The passed handle is the object on which the value may be exposed. - pub unsafe fn expose(&self, cx: *mut JSContext, obj: HandleObject) -> Option { + pub unsafe fn expose(&self, cx: *mut jsapi::JSContext, obj: jsapi::JS::HandleObject) -> Option { if self.condition.is_satisfied(cx, obj) { Some(self.value) } else { @@ -37,7 +37,7 @@ impl Guard { /// A condition to expose things. pub enum Condition { /// The condition is satisfied if the function returns true. - Func(unsafe fn(*mut JSContext, HandleObject) -> bool), + Func(unsafe fn(*mut jsapi::JSContext, jsapi::JS::HandleObject) -> bool), /// The condition is satisfied if the preference is set. Pref(&'static str), /// The condition is always satisfied. @@ -45,7 +45,7 @@ pub enum Condition { } impl Condition { - unsafe fn is_satisfied(&self, cx: *mut JSContext, obj: HandleObject) -> bool { + unsafe fn is_satisfied(&self, cx: *mut jsapi::JSContext, obj: jsapi::JS::HandleObject) -> bool { match *self { Condition::Pref(name) => PREFS.get(name).as_boolean().unwrap_or(false), Condition::Func(f) => f(cx, obj), diff --git a/components/script/dom/bindings/interface.rs b/components/script/dom/bindings/interface.rs index c242bd7f0650..05aa41a2b360 100644 --- a/components/script/dom/bindings/interface.rs +++ b/components/script/dom/bindings/interface.rs @@ -86,22 +86,11 @@ use dom::htmlelement::HTMLElement; use dom::window::Window; use html5ever::LocalName; use html5ever::interface::QualName; +use js; use js::error::throw_type_error; use js::glue::{RUST_SYMBOL_TO_JSID, UncheckedUnwrapObject, UnwrapObject}; -use js::jsapi::{CallArgs, Class, ClassOps, CompartmentOptions, CurrentGlobalOrNull}; -use js::jsapi::{GetGlobalForObjectCrossCompartment, GetWellKnownSymbol, HandleObject, HandleValue}; -use js::jsapi::{JSAutoCompartment, JSClass, JSContext, JSFUN_CONSTRUCTOR, JSFunctionSpec, JSObject}; -use js::jsapi::{JSPROP_PERMANENT, JSPROP_READONLY, JSPROP_RESOLVING}; -use js::jsapi::{JSPropertySpec, JSString, JSTracer, JSVersion, JS_AtomizeAndPinString}; -use js::jsapi::{JS_DefineProperty, JS_DefineProperty1, JS_DefineProperty2}; -use js::jsapi::{JS_DefineProperty4, JS_DefinePropertyById3, JS_FireOnNewGlobalObject}; -use js::jsapi::{JS_GetFunctionObject, JS_GetPrototype}; -use js::jsapi::{JS_LinkConstructorAndPrototype, JS_NewFunction, JS_NewGlobalObject}; -use js::jsapi::{JS_NewObject, JS_NewObjectWithUniqueType, JS_NewPlainObject}; -use js::jsapi::{JS_NewStringCopyN, JS_SetReservedSlot, MutableHandleObject}; -use js::jsapi::{MutableHandleValue, ObjectOps, OnNewGlobalHookOption, SymbolCode}; -use js::jsapi::{TrueHandleValue, Value}; -use js::jsval::{JSVal, PrivateValue}; +use js::jsapi; +use js::jsval::PrivateValue; use js::rust::{define_methods, define_properties, get_object_class}; use libc; use script_thread::ScriptThread; @@ -111,7 +100,7 @@ use std::ptr; #[derive(Clone, Copy)] pub struct NonCallbackInterfaceObjectClass { /// The SpiderMonkey Class structure. - pub class: Class, + pub class: jsapi::js::Class, /// The prototype id of that interface, used in the hasInstance hook. pub proto_id: PrototypeList::ID, /// The prototype depth of that interface, used in the hasInstance hook. @@ -130,7 +119,7 @@ impl NonCallbackInterfaceObjectClass { proto_depth: u16) -> NonCallbackInterfaceObjectClass { NonCallbackInterfaceObjectClass { - class: Class { + class: jsapi::js::Class { name: b"Function\0" as *const _ as *const libc::c_char, flags: 0, cOps: &constructor_behavior.0, @@ -145,24 +134,24 @@ impl NonCallbackInterfaceObjectClass { } /// cast own reference to `JSClass` reference - pub fn as_jsclass(&self) -> &JSClass { + pub fn as_jsclass(&self) -> &jsapi::JSClass { unsafe { - &*(self as *const _ as *const JSClass) + &*(self as *const _ as *const jsapi::JSClass) } } } /// A constructor class hook. pub type ConstructorClassHook = - unsafe extern "C" fn(cx: *mut JSContext, argc: u32, vp: *mut Value) -> bool; + unsafe extern "C" fn(cx: *mut jsapi::JSContext, argc: u32, vp: *mut jsapi::JS::Value) -> bool; /// The constructor behavior of a non-callback interface object. -pub struct InterfaceConstructorBehavior(ClassOps); +pub struct InterfaceConstructorBehavior(jsapi::js::ClassOps); impl InterfaceConstructorBehavior { /// An interface constructor that unconditionally throws a type error. pub const fn throw() -> Self { - InterfaceConstructorBehavior(ClassOps { + InterfaceConstructorBehavior(jsapi::js::ClassOps { addProperty: None, delProperty: None, getProperty: None, @@ -180,7 +169,7 @@ impl InterfaceConstructorBehavior { /// An interface constructor that calls a native Rust function. pub const fn call(hook: ConstructorClassHook) -> Self { - InterfaceConstructorBehavior(ClassOps { + InterfaceConstructorBehavior(jsapi::js::ClassOps { addProperty: None, delProperty: None, getProperty: None, @@ -199,45 +188,51 @@ impl InterfaceConstructorBehavior { /// A trace hook. pub type TraceHook = - unsafe extern "C" fn(trc: *mut JSTracer, obj: *mut JSObject); + unsafe extern "C" fn(trc: *mut jsapi::JSTracer, obj: *mut jsapi::JSObject); /// Create a global object with the given class. pub unsafe fn create_global_object( - cx: *mut JSContext, - class: &'static JSClass, + cx: *mut jsapi::JSContext, + class: &'static jsapi::JSClass, private: *const libc::c_void, trace: TraceHook, - rval: MutableHandleObject) { + rval: jsapi::JS::MutableHandleObject) { assert!(rval.is_null()); - let mut options = CompartmentOptions::default(); - options.behaviors_.version_ = JSVersion::JSVERSION_ECMA_5; + let mut options = jsapi::JS::CompartmentOptions::default(); + options.behaviors_.version_ = jsapi::JSVersion::JSVERSION_ECMA_5; options.creationOptions_.traceGlobal_ = Some(trace); options.creationOptions_.sharedMemoryAndAtomics_ = true; - rval.set(JS_NewGlobalObject(cx, + rval.set(jsapi::JS_NewGlobalObject(cx, class, ptr::null_mut(), - OnNewGlobalHookOption::DontFireOnNewGlobalHook, + jsapi::JS::OnNewGlobalHookOption::DontFireOnNewGlobalHook, &options)); assert!(!rval.is_null()); // Initialize the reserved slots before doing anything that can GC, to // avoid getting trace hooks called on a partially initialized object. - JS_SetReservedSlot(rval.get(), DOM_OBJECT_SLOT, PrivateValue(private)); + let private = PrivateValue(private); + jsapi::JS_SetReservedSlot(rval.get(), DOM_OBJECT_SLOT, &private); let proto_array: Box = - box [0 as *mut JSObject; PrototypeList::PROTO_OR_IFACE_LENGTH]; - JS_SetReservedSlot(rval.get(), - DOM_PROTOTYPE_SLOT, - PrivateValue(Box::into_raw(proto_array) as *const libc::c_void)); + box [0 as *mut jsapi::JSObject; PrototypeList::PROTO_OR_IFACE_LENGTH]; - let _ac = JSAutoCompartment::new(cx, rval.get()); - JS_FireOnNewGlobalObject(cx, rval.handle()); + let proto_array = PrivateValue(Box::into_raw(proto_array) as *const libc::c_void); + jsapi::JS_SetReservedSlot(rval.get(), + DOM_PROTOTYPE_SLOT, + &proto_array); + + let _ac = js::ac::AutoCompartment::with_obj(cx, rval.get()); + jsapi::JS_FireOnNewGlobalObject(cx, rval.handle()); } // https://html.spec.whatwg.org/multipage/#htmlconstructor -pub unsafe fn html_constructor(window: &Window, call_args: &CallArgs) -> Fallible> - where T: DerivedFrom { +pub unsafe fn html_constructor(window: &Window, + call_args: &jsapi::JS::CallArgs) + -> Fallible> + where T: DerivedFrom +{ let document = window.Document(); // Step 1 @@ -258,9 +253,9 @@ pub unsafe fn html_constructor(window: &Window, call_args: &CallArgs) -> Fall } { - let _ac = JSAutoCompartment::new(window.get_cx(), callee.get()); + let _ac = js::ac::AutoCompartment::with_obj(window.get_cx(), callee.get()); rooted!(in(window.get_cx()) let mut constructor = ptr::null_mut()); - rooted!(in(window.get_cx()) let global_object = CurrentGlobalOrNull(window.get_cx())); + rooted!(in(window.get_cx()) let global_object = jsapi::JS::CurrentGlobalOrNull(window.get_cx())); if definition.is_autonomous() { // Step 4 @@ -332,13 +327,13 @@ pub fn pop_current_element_queue() { /// Create and define the interface object of a callback interface. pub unsafe fn create_callback_interface_object( - cx: *mut JSContext, - global: HandleObject, + cx: *mut jsapi::JSContext, + global: jsapi::JS::HandleObject, constants: &[Guard<&[ConstantSpec]>], name: &[u8], - rval: MutableHandleObject) { + rval: jsapi::JS::MutableHandleObject) { assert!(!constants.is_empty()); - rval.set(JS_NewObject(cx, ptr::null())); + rval.set(jsapi::JS_NewObject(cx, ptr::null())); assert!(!rval.ptr.is_null()); define_guarded_constants(cx, rval.handle(), constants); define_name(cx, rval.handle(), name); @@ -347,43 +342,43 @@ pub unsafe fn create_callback_interface_object( /// Create the interface prototype object of a non-callback interface. pub unsafe fn create_interface_prototype_object( - cx: *mut JSContext, - proto: HandleObject, - class: &'static JSClass, - regular_methods: &[Guard<&'static [JSFunctionSpec]>], - regular_properties: &[Guard<&'static [JSPropertySpec]>], + cx: *mut jsapi::JSContext, + proto: jsapi::JS::HandleObject, + class: &'static jsapi::JSClass, + regular_methods: &[Guard<&'static [jsapi::JSFunctionSpec]>], + regular_properties: &[Guard<&'static [jsapi::JSPropertySpec]>], constants: &[Guard<&[ConstantSpec]>], unscopable_names: &[&[u8]], - rval: MutableHandleObject) { + rval: jsapi::JS::MutableHandleObject) { create_object(cx, proto, class, regular_methods, regular_properties, constants, rval); if !unscopable_names.is_empty() { rooted!(in(cx) let mut unscopable_obj = ptr::null_mut()); create_unscopable_object(cx, unscopable_names, unscopable_obj.handle_mut()); - let unscopable_symbol = GetWellKnownSymbol(cx, SymbolCode::unscopables); + let unscopable_symbol = jsapi::JS::GetWellKnownSymbol(cx, jsapi::JS::SymbolCode::unscopables); assert!(!unscopable_symbol.is_null()); rooted!(in(cx) let unscopable_id = RUST_SYMBOL_TO_JSID(unscopable_symbol)); - assert!(JS_DefinePropertyById3( + assert!(jsapi::JS_DefinePropertyById3( cx, rval.handle(), unscopable_id.handle(), unscopable_obj.handle(), - JSPROP_READONLY, None, None)) + jsapi::JSPROP_READONLY as _, None, None)) } } /// Create and define the interface object of a non-callback interface. pub unsafe fn create_noncallback_interface_object( - cx: *mut JSContext, - global: HandleObject, - proto: HandleObject, + cx: *mut jsapi::JSContext, + global: jsapi::JS::HandleObject, + proto: jsapi::JS::HandleObject, class: &'static NonCallbackInterfaceObjectClass, - static_methods: &[Guard<&'static [JSFunctionSpec]>], - static_properties: &[Guard<&'static [JSPropertySpec]>], + static_methods: &[Guard<&'static [jsapi::JSFunctionSpec]>], + static_properties: &[Guard<&'static [jsapi::JSPropertySpec]>], constants: &[Guard<&[ConstantSpec]>], - interface_prototype_object: HandleObject, + interface_prototype_object: jsapi::JS::HandleObject, name: &[u8], length: u32, - rval: MutableHandleObject) { + rval: jsapi::JS::MutableHandleObject) { create_object(cx, proto, class.as_jsclass(), @@ -391,7 +386,7 @@ pub unsafe fn create_noncallback_interface_object( static_properties, constants, rval); - assert!(JS_LinkConstructorAndPrototype(cx, rval.handle(), interface_prototype_object)); + assert!(jsapi::JS_LinkConstructorAndPrototype(cx, rval.handle(), interface_prototype_object)); define_name(cx, rval.handle(), name); define_length(cx, rval.handle(), length); define_on_global_object(cx, global, name, rval.handle()); @@ -399,29 +394,29 @@ pub unsafe fn create_noncallback_interface_object( /// Create and define the named constructors of a non-callback interface. pub unsafe fn create_named_constructors( - cx: *mut JSContext, - global: HandleObject, + cx: *mut jsapi::JSContext, + global: jsapi::JS::HandleObject, named_constructors: &[(ConstructorClassHook, &[u8], u32)], - interface_prototype_object: HandleObject) { + interface_prototype_object: jsapi::JS::HandleObject) { rooted!(in(cx) let mut constructor = ptr::null_mut()); for &(native, name, arity) in named_constructors { assert!(*name.last().unwrap() == b'\0'); - let fun = JS_NewFunction(cx, + let fun = jsapi::JS_NewFunction(cx, Some(native), arity, - JSFUN_CONSTRUCTOR, + jsapi::JSFUN_CONSTRUCTOR, name.as_ptr() as *const libc::c_char); assert!(!fun.is_null()); - constructor.set(JS_GetFunctionObject(fun)); + constructor.set(jsapi::JS_GetFunctionObject(fun)); assert!(!constructor.is_null()); - assert!(JS_DefineProperty1(cx, + assert!(jsapi::JS_DefineProperty1(cx, constructor.handle(), b"prototype\0".as_ptr() as *const libc::c_char, interface_prototype_object, - JSPROP_PERMANENT | JSPROP_READONLY, + (jsapi::JSPROP_PERMANENT | jsapi::JSPROP_READONLY) as _, None, None)); @@ -431,14 +426,14 @@ pub unsafe fn create_named_constructors( /// Create a new object with a unique type. pub unsafe fn create_object( - cx: *mut JSContext, - proto: HandleObject, - class: &'static JSClass, - methods: &[Guard<&'static [JSFunctionSpec]>], - properties: &[Guard<&'static [JSPropertySpec]>], + cx: *mut jsapi::JSContext, + proto: jsapi::JS::HandleObject, + class: &'static jsapi::JSClass, + methods: &[Guard<&'static [jsapi::JSFunctionSpec]>], + properties: &[Guard<&'static [jsapi::JSPropertySpec]>], constants: &[Guard<&[ConstantSpec]>], - rval: MutableHandleObject) { - rval.set(JS_NewObjectWithUniqueType(cx, class, proto)); + rval: jsapi::JS::MutableHandleObject) { + rval.set(jsapi::JS_NewObjectWithUniqueType(cx, class, proto)); assert!(!rval.ptr.is_null()); define_guarded_methods(cx, rval.handle(), methods); define_guarded_properties(cx, rval.handle(), properties); @@ -447,8 +442,8 @@ pub unsafe fn create_object( /// Conditionally define constants on an object. pub unsafe fn define_guarded_constants( - cx: *mut JSContext, - obj: HandleObject, + cx: *mut jsapi::JSContext, + obj: jsapi::JS::HandleObject, constants: &[Guard<&[ConstantSpec]>]) { for guard in constants { if let Some(specs) = guard.expose(cx, obj) { @@ -459,9 +454,9 @@ pub unsafe fn define_guarded_constants( /// Conditionally define methods on an object. pub unsafe fn define_guarded_methods( - cx: *mut JSContext, - obj: HandleObject, - methods: &[Guard<&'static [JSFunctionSpec]>]) { + cx: *mut jsapi::JSContext, + obj: jsapi::JS::HandleObject, + methods: &[Guard<&'static [jsapi::JSFunctionSpec]>]) { for guard in methods { if let Some(specs) = guard.expose(cx, obj) { define_methods(cx, obj, specs).unwrap(); @@ -471,9 +466,9 @@ pub unsafe fn define_guarded_methods( /// Conditionally define properties on an object. pub unsafe fn define_guarded_properties( - cx: *mut JSContext, - obj: HandleObject, - properties: &[Guard<&'static [JSPropertySpec]>]) { + cx: *mut jsapi::JSContext, + obj: jsapi::JS::HandleObject, + properties: &[Guard<&'static [jsapi::JSPropertySpec]>]) { for guard in properties { if let Some(specs) = guard.expose(cx, obj) { define_properties(cx, obj, specs).unwrap(); @@ -483,7 +478,7 @@ pub unsafe fn define_guarded_properties( /// Returns whether an interface with exposure set given by `globals` should /// be exposed in the global object `obj`. -pub unsafe fn is_exposed_in(object: HandleObject, globals: Globals) -> bool { +pub unsafe fn is_exposed_in(object: jsapi::JS::HandleObject, globals: Globals) -> bool { let unwrapped = UncheckedUnwrapObject(object.get(), /* stopAtWindowProxy = */ 0); let dom_class = get_dom_class(unwrapped).unwrap(); globals.contains(dom_class.global) @@ -492,20 +487,20 @@ pub unsafe fn is_exposed_in(object: HandleObject, globals: Globals) -> bool { /// Define a property with a given name on the global object. Should be called /// through the resolve hook. pub unsafe fn define_on_global_object( - cx: *mut JSContext, - global: HandleObject, + cx: *mut jsapi::JSContext, + global: jsapi::JS::HandleObject, name: &[u8], - obj: HandleObject) { + obj: jsapi::JS::HandleObject) { assert!(*name.last().unwrap() == b'\0'); - assert!(JS_DefineProperty1(cx, + assert!(jsapi::JS_DefineProperty1(cx, global, name.as_ptr() as *const libc::c_char, obj, - JSPROP_RESOLVING, + jsapi::JSPROP_RESOLVING, None, None)); } -const OBJECT_OPS: ObjectOps = ObjectOps { +const OBJECT_OPS: jsapi::js::ObjectOps = jsapi::js::ObjectOps { lookupProperty: None, defineProperty: None, hasProperty: None, @@ -520,23 +515,23 @@ const OBJECT_OPS: ObjectOps = ObjectOps { funToString: Some(fun_to_string_hook), }; -unsafe extern "C" fn fun_to_string_hook(cx: *mut JSContext, - obj: HandleObject, +unsafe extern "C" fn fun_to_string_hook(cx: *mut jsapi::JSContext, + obj: jsapi::JS::HandleObject, _indent: u32) - -> *mut JSString { + -> *mut jsapi::JSString { let js_class = get_object_class(obj.get()); assert!(!js_class.is_null()); let repr = (*(js_class as *const NonCallbackInterfaceObjectClass)).representation; assert!(!repr.is_empty()); - let ret = JS_NewStringCopyN(cx, repr.as_ptr() as *const libc::c_char, repr.len()); + let ret = jsapi::JS_NewStringCopyN(cx, repr.as_ptr() as *const libc::c_char, repr.len()); assert!(!ret.is_null()); ret } /// Hook for instanceof on interface objects. -unsafe extern "C" fn has_instance_hook(cx: *mut JSContext, - obj: HandleObject, - value: MutableHandleValue, +unsafe extern "C" fn has_instance_hook(cx: *mut jsapi::JSContext, + obj: jsapi::JS::HandleObject, + value: jsapi::JS::MutableHandleValue, rval: *mut bool) -> bool { match has_instance(cx, obj, value.handle()) { Ok(result) => { @@ -550,9 +545,9 @@ unsafe extern "C" fn has_instance_hook(cx: *mut JSContext, /// Return whether a value is an instance of a given prototype. /// http://heycam.github.io/webidl/#es-interface-hasinstance unsafe fn has_instance( - cx: *mut JSContext, - interface_object: HandleObject, - value: HandleValue) + cx: *mut jsapi::JSContext, + interface_object: jsapi::JS::HandleObject, + value: jsapi::JS::HandleValue) -> Result { if !value.is_object() { // Step 1. @@ -572,14 +567,14 @@ unsafe fn has_instance( } // Step 2. - let global = GetGlobalForObjectCrossCompartment(interface_object.get()); + let global = jsapi::js::GetGlobalForObjectCrossCompartment(interface_object.get()); assert!(!global.is_null()); let proto_or_iface_array = get_proto_or_iface_array(global); rooted!(in(cx) let prototype = (*proto_or_iface_array)[object_class.proto_id as usize]); assert!(!prototype.is_null()); // Step 3 only concern legacy callback interface objects (i.e. NodeFilter). - while JS_GetPrototype(cx, value.handle(), value.handle_mut()) { + while jsapi::JS_GetPrototype(cx, value.handle(), value.handle_mut()) { if value.is_null() { // Step 5.2. return Ok(false); @@ -588,60 +583,60 @@ unsafe fn has_instance( return Ok(true); } } - // JS_GetPrototype threw an exception. + // jsapi::JS_GetPrototype threw an exception. Err(()) } unsafe fn create_unscopable_object( - cx: *mut JSContext, + cx: *mut jsapi::JSContext, names: &[&[u8]], - rval: MutableHandleObject) { + rval: jsapi::JS::MutableHandleObject) { assert!(!names.is_empty()); assert!(rval.is_null()); - rval.set(JS_NewPlainObject(cx)); + rval.set(jsapi::JS_NewPlainObject(cx)); assert!(!rval.ptr.is_null()); for &name in names { assert!(*name.last().unwrap() == b'\0'); - assert!(JS_DefineProperty( - cx, rval.handle(), name.as_ptr() as *const libc::c_char, TrueHandleValue, - JSPROP_READONLY, None, None)); + assert!(jsapi::JS_DefineProperty( + cx, rval.handle(), name.as_ptr() as *const libc::c_char, jsapi::JS::TrueHandleValue, + jsapi::JSPROP_READONLY as _, None, None)); } } -unsafe fn define_name(cx: *mut JSContext, obj: HandleObject, name: &[u8]) { +unsafe fn define_name(cx: *mut jsapi::JSContext, obj: jsapi::JS::HandleObject, name: &[u8]) { assert!(*name.last().unwrap() == b'\0'); - rooted!(in(cx) let name = JS_AtomizeAndPinString(cx, name.as_ptr() as *const libc::c_char)); + rooted!(in(cx) let name = jsapi::JS_AtomizeAndPinString(cx, name.as_ptr() as *const libc::c_char)); assert!(!name.is_null()); - assert!(JS_DefineProperty2(cx, + assert!(jsapi::JS_DefineProperty2(cx, obj, b"name\0".as_ptr() as *const libc::c_char, name.handle(), - JSPROP_READONLY, + jsapi::JSPROP_READONLY as _, None, None)); } -unsafe fn define_length(cx: *mut JSContext, obj: HandleObject, length: u32) { - assert!(JS_DefineProperty4(cx, +unsafe fn define_length(cx: *mut jsapi::JSContext, obj: jsapi::JS::HandleObject, length: u32) { + assert!(jsapi::JS_DefineProperty4(cx, obj, b"length\0".as_ptr() as *const libc::c_char, length, - JSPROP_READONLY, + jsapi::JSPROP_READONLY as _, None, None)); } unsafe extern "C" fn invalid_constructor( - cx: *mut JSContext, + cx: *mut jsapi::JSContext, _argc: libc::c_uint, - _vp: *mut JSVal) + _vp: *mut jsapi::JS::Value) -> bool { throw_type_error(cx, "Illegal constructor."); false } unsafe extern "C" fn non_new_constructor( - cx: *mut JSContext, + cx: *mut jsapi::JSContext, _argc: libc::c_uint, - _vp: *mut JSVal) + _vp: *mut jsapi::JS::Value) -> bool { throw_type_error(cx, "This constructor needs to be called with `new`."); false @@ -650,9 +645,9 @@ unsafe extern "C" fn non_new_constructor( /// Returns the constructor object for the element associated with the given local name. /// This list should only include elements marked with the [HTMLConstructor] extended attribute. pub fn get_constructor_object_from_local_name(name: LocalName, - cx: *mut JSContext, - global: HandleObject, - rval: MutableHandleObject) + cx: *mut jsapi::JSContext, + global: jsapi::JS::HandleObject, + rval: jsapi::JS::MutableHandleObject) -> bool { macro_rules! get_constructor( ($binding:ident) => ({ diff --git a/components/script/dom/bindings/iterable.rs b/components/script/dom/bindings/iterable.rs index 03fac1cb27fb..0133dfe96492 100644 --- a/components/script/dom/bindings/iterable.rs +++ b/components/script/dom/bindings/iterable.rs @@ -16,7 +16,8 @@ use dom::bindings::trace::JSTraceable; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::conversions::ToJSValConvertible; -use js::jsapi::{HandleValue, Heap, JSContext, JSObject, MutableHandleObject}; +use js::heap::Heap; +use js::jsapi; use js::jsval::UndefinedValue; use std::cell::Cell; use std::ptr; @@ -60,7 +61,7 @@ impl IterableIterator { /// Create a new iterator instance for the provided iterable DOM interface. pub fn new(iterable: &T, type_: IteratorType, - wrap: unsafe fn(*mut JSContext, &GlobalScope, Box>) + wrap: unsafe fn(*mut jsapi::JSContext, &GlobalScope, Box>) -> Root) -> Root { let iterator = box IterableIterator { reflector: Reflector::new(), @@ -73,7 +74,7 @@ impl IterableIterator { /// Return the next value from the iterable object. #[allow(non_snake_case)] - pub fn Next(&self, cx: *mut JSContext) -> Fallible> { + pub fn Next(&self, cx: *mut jsapi::JSContext) -> Fallible> { let index = self.index.get(); rooted!(in(cx) let mut value = UndefinedValue()); rooted!(in(cx) let mut rval = ptr::null_mut()); @@ -111,10 +112,10 @@ impl IterableIterator { } } -fn dict_return(cx: *mut JSContext, - result: MutableHandleObject, +fn dict_return(cx: *mut jsapi::JSContext, + result: jsapi::JS::MutableHandleObject, done: bool, - value: HandleValue) -> Fallible<()> { + value: jsapi::JS::HandleValue) -> Fallible<()> { let mut dict = unsafe { IterableKeyOrValueResult::empty(cx) }; dict.done = done; dict.value.set(value.get()); @@ -126,10 +127,10 @@ fn dict_return(cx: *mut JSContext, Ok(()) } -fn key_and_value_return(cx: *mut JSContext, - result: MutableHandleObject, - key: HandleValue, - value: HandleValue) -> Fallible<()> { +fn key_and_value_return(cx: *mut jsapi::JSContext, + result: jsapi::JS::MutableHandleObject, + key: jsapi::JS::HandleValue, + value: jsapi::JS::HandleValue) -> Fallible<()> { let mut dict = unsafe { IterableKeyAndValueResult::empty(cx) }; dict.done = false; dict.value = Some(vec![Heap::new(key.get()), Heap::new(value.get())]); diff --git a/components/script/dom/bindings/js.rs b/components/script/dom/bindings/js.rs index abfd9f47eff1..643bcecd80a2 100644 --- a/components/script/dom/bindings/js.rs +++ b/components/script/dom/bindings/js.rs @@ -31,7 +31,7 @@ use dom::bindings::trace::JSTraceable; use dom::bindings::trace::trace_reflector; use dom::node::Node; use heapsize::HeapSizeOf; -use js::jsapi::{JSObject, JSTracer}; +use js::jsapi; use script_layout_interface::TrustedNodeAddress; use script_thread::STACK_ROOTS; use std::cell::UnsafeCell; @@ -105,7 +105,7 @@ impl Deref for JS { } unsafe impl JSTraceable for JS { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { #[cfg(debug_assertions)] let trace_str = format!("for {} on heap", type_name::()); #[cfg(debug_assertions)] @@ -159,7 +159,7 @@ impl LayoutJS { impl LayoutJS { /// Get the reflector. - pub unsafe fn get_jsobject(&self) -> *mut JSObject { + pub unsafe fn get_jsobject(&self) -> *mut jsapi::JSObject { debug_assert!(thread_state::get().is_layout()); (*self.ptr.get()).reflector().get_jsobject().get() } @@ -490,7 +490,7 @@ impl RootCollection { } /// SM Callback that traces the rooted reflectors -pub unsafe fn trace_roots(tracer: *mut JSTracer) { +pub unsafe fn trace_roots(tracer: *mut jsapi::JSTracer) { debug!("tracing stack roots"); STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); @@ -600,7 +600,7 @@ impl Drop for Root { } unsafe impl JSTraceable for Root { - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Already traced. } } diff --git a/components/script/dom/bindings/mod.rs b/components/script/dom/bindings/mod.rs index 5d0cd864dad7..77bf6ab72f28 100644 --- a/components/script/dom/bindings/mod.rs +++ b/components/script/dom/bindings/mod.rs @@ -9,7 +9,7 @@ //! //! As [explained earlier](../index.html#a-dom-object-and-its-reflector), the //! implementation of an interface `Foo` involves two objects: the DOM object -//! (implemented in Rust) and the reflector (a `JSObject`). +//! (implemented in Rust) and the reflector (a `jsapi::JSObject`). //! //! In order to expose the interface's members to the web, properties //! corresponding to the operations and attributes are defined on an object in @@ -42,9 +42,9 @@ //! (#throwing-exceptions) will have the return value wrapped in //! [`Fallible`](error/type.Fallible.html). //! Methods that use certain WebIDL types like `any` or `object` will get a -//! `*mut JSContext` argument prepended to the argument list. Static methods +//! `*mut jsapi::JSContext` argument prepended to the argument list. Static methods //! will be passed a [`&GlobalScope`](../globalscope/struct.GlobalScope.html) -//! for the relevant global. This argument comes before the `*mut JSContext` +//! for the relevant global. This argument comes before the `*mut jsapi::JSContext` //! argument, if any. //! //! Rust reflections of WebIDL operations (methods) diff --git a/components/script/dom/bindings/mozmap.rs b/components/script/dom/bindings/mozmap.rs index 19f65ec05f8f..fbea854a18a4 100644 --- a/components/script/dom/bindings/mozmap.rs +++ b/components/script/dom/bindings/mozmap.rs @@ -7,15 +7,7 @@ use dom::bindings::conversions::jsid_to_string; use dom::bindings::str::DOMString; use js::conversions::{FromJSValConvertible, ToJSValConvertible, ConversionResult}; -use js::jsapi::GetPropertyKeys; -use js::jsapi::HandleValue; -use js::jsapi::JSContext; -use js::jsapi::JSITER_OWNONLY; -use js::jsapi::JSPROP_ENUMERATE; -use js::jsapi::JS_DefineUCProperty2; -use js::jsapi::JS_GetPropertyById; -use js::jsapi::JS_NewPlainObject; -use js::jsapi::MutableHandleValue; +use js::jsapi; use js::jsval::ObjectValue; use js::jsval::UndefinedValue; use js::rust::IdVector; @@ -50,7 +42,7 @@ impl FromJSValConvertible for MozMap C: Clone, { type Config = C; - unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, config: C) + unsafe fn from_jsval(cx: *mut jsapi::JSContext, value: jsapi::JS::HandleValue, config: C) -> Result, ()> { if !value.is_object() { return Ok(ConversionResult::Failure("MozMap value was not an object".into())); @@ -58,14 +50,14 @@ impl FromJSValConvertible for MozMap rooted!(in(cx) let object = value.to_object()); let ids = IdVector::new(cx); - assert!(GetPropertyKeys(cx, object.handle(), JSITER_OWNONLY, ids.get())); + assert!(jsapi::js::GetPropertyKeys(cx, object.handle(), jsapi::JSITER_OWNONLY, ids.get())); let mut map = HashMap::new(); for id in &*ids { rooted!(in(cx) let id = *id); rooted!(in(cx) let mut property = UndefinedValue()); - if !JS_GetPropertyById(cx, object.handle(), id.handle(), property.handle_mut()) { + if !jsapi::JS_GetPropertyById(cx, object.handle(), id.handle(), property.handle_mut()) { return Err(()); } @@ -86,8 +78,8 @@ impl FromJSValConvertible for MozMap impl ToJSValConvertible for MozMap { #[inline] - unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { - rooted!(in(cx) let js_object = JS_NewPlainObject(cx)); + unsafe fn to_jsval(&self, cx: *mut jsapi::JSContext, rval: jsapi::JS::MutableHandleValue) { + rooted!(in(cx) let js_object = jsapi::JS_NewPlainObject(cx)); assert!(!js_object.handle().is_null()); rooted!(in(cx) let mut js_value = UndefinedValue()); @@ -95,12 +87,12 @@ impl ToJSValConvertible for MozMap { let key = key.encode_utf16().collect::>(); value.to_jsval(cx, js_value.handle_mut()); - assert!(JS_DefineUCProperty2(cx, + assert!(jsapi::JS_DefineUCProperty2(cx, js_object.handle(), key.as_ptr(), key.len(), js_value.handle(), - JSPROP_ENUMERATE, + jsapi::JSPROP_ENUMERATE as _, None, None)); } diff --git a/components/script/dom/bindings/namespace.rs b/components/script/dom/bindings/namespace.rs index 8ca1116ea1ec..2b6c98bf4bdc 100644 --- a/components/script/dom/bindings/namespace.rs +++ b/components/script/dom/bindings/namespace.rs @@ -6,20 +6,20 @@ use dom::bindings::guard::Guard; use dom::bindings::interface::{create_object, define_on_global_object}; -use js::jsapi::{HandleObject, JSClass, JSContext, JSFunctionSpec, MutableHandleObject}; +use js::jsapi; use libc; use std::ptr; /// The class of a namespace object. #[derive(Clone, Copy)] -pub struct NamespaceObjectClass(JSClass); +pub struct NamespaceObjectClass(jsapi::JSClass); unsafe impl Sync for NamespaceObjectClass {} impl NamespaceObjectClass { /// Create a new `NamespaceObjectClass` structure. pub const unsafe fn new(name: &'static [u8]) -> Self { - NamespaceObjectClass(JSClass { + NamespaceObjectClass(jsapi::JSClass { name: name as *const _ as *const libc::c_char, flags: 0, cOps: ptr::null_mut(), @@ -30,13 +30,13 @@ impl NamespaceObjectClass { /// Create a new namespace object. pub unsafe fn create_namespace_object( - cx: *mut JSContext, - global: HandleObject, - proto: HandleObject, + cx: *mut jsapi::JSContext, + global: jsapi::JS::HandleObject, + proto: jsapi::JS::HandleObject, class: &'static NamespaceObjectClass, - methods: &[Guard<&'static [JSFunctionSpec]>], + methods: &[Guard<&'static [jsapi::JSFunctionSpec]>], name: &[u8], - rval: MutableHandleObject) { + rval: jsapi::JS::MutableHandleObject) { create_object(cx, proto, &class.0, methods, &[], &[], rval); define_on_global_object(cx, global, name, rval.handle()); } diff --git a/components/script/dom/bindings/proxyhandler.rs b/components/script/dom/bindings/proxyhandler.rs index 67c68927c9f9..3b34677aca72 100644 --- a/components/script/dom/bindings/proxyhandler.rs +++ b/components/script/dom/bindings/proxyhandler.rs @@ -8,63 +8,53 @@ use dom::bindings::conversions::is_dom_proxy; use dom::bindings::utils::delete_property_by_id; -use js::glue::{GetProxyHandler, GetProxyHandlerFamily, SetProxyExtra}; -use js::glue::GetProxyExtra; +use js::glue::{GetProxyHandler, GetProxyHandlerFamily}; +use js::glue::{GetProxyPrivate, SetProxyPrivate}; use js::glue::InvokeGetOwnPropertyDescriptor; -use js::jsapi::{DOMProxyShadowsResult, JSContext, JSObject, JSPROP_GETTER, PropertyDescriptor}; -use js::jsapi::{Handle, HandleId, HandleObject, MutableHandle, ObjectOpResult}; -use js::jsapi::{JSErrNum, JS_AlreadyHasOwnPropertyById, JS_StrictPropertyStub}; -use js::jsapi::{JS_DefinePropertyById, JS_NewObjectWithGivenProto, SetDOMProxyInformation}; -use js::jsapi::GetObjectProto; -use js::jsapi::GetStaticPrototype; -use js::jsapi::JS_GetPropertyDescriptorById; -use js::jsapi::MutableHandleObject; +use js::jsapi; use js::jsval::ObjectValue; use libc; use std::{mem, ptr}; -static JSPROXYSLOT_EXPANDO: u32 = 0; - /// Determine if this id shadows any existing properties for this proxy. -pub unsafe extern "C" fn shadow_check_callback(cx: *mut JSContext, - object: HandleObject, - id: HandleId) - -> DOMProxyShadowsResult { +pub unsafe extern "C" fn shadow_check_callback(cx: *mut jsapi::JSContext, + object: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId) + -> jsapi::js::DOMProxyShadowsResult { // TODO: support OverrideBuiltins when #12978 is fixed. rooted!(in(cx) let mut expando = ptr::null_mut()); get_expando_object(object, expando.handle_mut()); if !expando.get().is_null() { let mut has_own = false; - if !JS_AlreadyHasOwnPropertyById(cx, expando.handle(), id, &mut has_own) { - return DOMProxyShadowsResult::ShadowCheckFailed; + if !jsapi::JS_AlreadyHasOwnPropertyById(cx, expando.handle(), id, &mut has_own) { + return jsapi::js::DOMProxyShadowsResult::ShadowCheckFailed; } if has_own { - return DOMProxyShadowsResult::ShadowsViaDirectExpando; + return jsapi::js::DOMProxyShadowsResult::ShadowsViaDirectExpando; } } // Our expando, if any, didn't shadow, so we're not shadowing at all. - DOMProxyShadowsResult::DoesntShadow + jsapi::js::DOMProxyShadowsResult::DoesntShadow } /// Initialize the infrastructure for DOM proxy objects. pub unsafe fn init() { - SetDOMProxyInformation(GetProxyHandlerFamily(), - JSPROXYSLOT_EXPANDO, - Some(shadow_check_callback)); + jsapi::js::SetDOMProxyInformation(GetProxyHandlerFamily(), + Some(shadow_check_callback)); } /// Invoke the [[GetOwnProperty]] trap (`getOwnPropertyDescriptor`) on `proxy`, /// with argument `id` and return the result, if it is not `undefined`. /// Otherwise, walk along the prototype chain to find a property with that /// name. -pub unsafe extern "C" fn get_property_descriptor(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId, - desc: MutableHandle) +pub unsafe extern "C" fn get_property_descriptor(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, + desc: jsapi::JS::MutableHandle) -> bool { let handler = GetProxyHandler(proxy.get()); if !InvokeGetOwnPropertyDescriptor(handler, cx, proxy, id, desc) { @@ -75,41 +65,41 @@ pub unsafe extern "C" fn get_property_descriptor(cx: *mut JSContext, } rooted!(in(cx) let mut proto = ptr::null_mut()); - if !GetObjectProto(cx, proxy, proto.handle_mut()) { + if !jsapi::js::GetObjectProto(cx, proxy, proto.handle_mut()) { // FIXME(#11868) Should assign to desc.obj, desc.get() is a copy. desc.get().obj = ptr::null_mut(); return true; } - JS_GetPropertyDescriptorById(cx, proto.handle(), id, desc) + jsapi::JS_GetPropertyDescriptorById(cx, proto.handle(), id, desc) } /// Defines an expando on the given `proxy`. -pub unsafe extern "C" fn define_property(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId, - desc: Handle, - result: *mut ObjectOpResult) +pub unsafe extern "C" fn define_property(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, + desc: jsapi::JS::Handle, + result: *mut jsapi::JS::ObjectOpResult) -> bool { // FIXME: Workaround for https://github.com/rust-lang/rfcs/issues/718 let setter: *const libc::c_void = mem::transmute(desc.get().setter); - let setter_stub: unsafe extern fn(_, _, _, _, _) -> _ = JS_StrictPropertyStub; + let setter_stub: unsafe extern fn(_, _, _, _, _) -> _ = jsapi::JS_StrictPropertyStub; let setter_stub: *const libc::c_void = mem::transmute(setter_stub); - if (desc.get().attrs & JSPROP_GETTER) != 0 && setter == setter_stub { - (*result).code_ = JSErrNum::JSMSG_GETTER_ONLY as ::libc::uintptr_t; + if (desc.get().attrs & (jsapi::JSPROP_GETTER as u32)) != 0 && setter == setter_stub { + (*result).code_ = jsapi::JSErrNum::JSMSG_GETTER_ONLY as ::libc::uintptr_t; return true; } rooted!(in(cx) let mut expando = ptr::null_mut()); ensure_expando_object(cx, proxy, expando.handle_mut()); - JS_DefinePropertyById(cx, expando.handle(), id, desc, result) + jsapi::JS_DefinePropertyById(cx, expando.handle(), id, desc, result) } /// Deletes an expando off the given `proxy`. -pub unsafe extern "C" fn delete(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId, - bp: *mut ObjectOpResult) +pub unsafe extern "C" fn delete(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, + bp: *mut jsapi::JS::ObjectOpResult) -> bool { rooted!(in(cx) let mut expando = ptr::null_mut()); get_expando_object(proxy, expando.handle_mut()); @@ -122,17 +112,17 @@ pub unsafe extern "C" fn delete(cx: *mut JSContext, } /// Controls whether the Extensible bit can be changed -pub unsafe extern "C" fn prevent_extensions(_cx: *mut JSContext, - _proxy: HandleObject, - result: *mut ObjectOpResult) +pub unsafe extern "C" fn prevent_extensions(_cx: *mut jsapi::JSContext, + _proxy: jsapi::JS::HandleObject, + result: *mut jsapi::JS::ObjectOpResult) -> bool { - (*result).code_ = JSErrNum::JSMSG_CANT_PREVENT_EXTENSIONS as ::libc::uintptr_t; + (*result).code_ = jsapi::JSErrNum::JSMSG_CANT_PREVENT_EXTENSIONS as ::libc::uintptr_t; true } /// Reports whether the object is Extensible -pub unsafe extern "C" fn is_extensible(_cx: *mut JSContext, - _proxy: HandleObject, +pub unsafe extern "C" fn is_extensible(_cx: *mut jsapi::JSContext, + _proxy: jsapi::JS::HandleObject, succeeded: *mut bool) -> bool { *succeeded = true; @@ -148,20 +138,20 @@ pub unsafe extern "C" fn is_extensible(_cx: *mut JSContext, /// This implementation always handles the case of the ordinary /// `[[GetPrototypeOf]]` behavior. An alternative implementation will be /// necessary for the Location object. -pub unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext, - proxy: HandleObject, +pub unsafe extern "C" fn get_prototype_if_ordinary(_: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, is_ordinary: *mut bool, - proto: MutableHandleObject) + proto: jsapi::JS::MutableHandleObject) -> bool { *is_ordinary = true; - proto.set(GetStaticPrototype(proxy.get())); + proto.set(jsapi::js::GetStaticPrototype(proxy.get())); true } /// Get the expando object, or null if there is none. -pub unsafe fn get_expando_object(obj: HandleObject, expando: MutableHandleObject) { +pub unsafe fn get_expando_object(obj: jsapi::JS::HandleObject, expando: jsapi::JS::MutableHandleObject) { assert!(is_dom_proxy(obj.get())); - let val = GetProxyExtra(obj.get(), JSPROXYSLOT_EXPANDO); + let val = GetProxyPrivate(obj.get()); expando.set(if val.is_undefined() { ptr::null_mut() } else { @@ -171,21 +161,26 @@ pub unsafe fn get_expando_object(obj: HandleObject, expando: MutableHandleObject /// Get the expando object, or create it if it doesn't exist yet. /// Fails on JSAPI failure. -pub unsafe fn ensure_expando_object(cx: *mut JSContext, obj: HandleObject, expando: MutableHandleObject) { +pub unsafe fn ensure_expando_object(cx: *mut jsapi::JSContext, + obj: jsapi::JS::HandleObject, + expando: jsapi::JS::MutableHandleObject) { assert!(is_dom_proxy(obj.get())); get_expando_object(obj, expando); if expando.is_null() { - expando.set(JS_NewObjectWithGivenProto(cx, ptr::null_mut(), HandleObject::null())); + expando.set(jsapi::JS_NewObjectWithGivenProto( + cx, + ptr::null_mut(), + jsapi::JS::HandleObject::null())); assert!(!expando.is_null()); - SetProxyExtra(obj.get(), JSPROXYSLOT_EXPANDO, &ObjectValue(expando.get())); + SetProxyPrivate(obj.get(), &ObjectValue(expando.get())); } } /// Set the property descriptor's object to `obj` and set it to enumerable, /// and writable if `readonly` is true. -pub fn fill_property_descriptor(mut desc: MutableHandle, - obj: *mut JSObject, +pub fn fill_property_descriptor(mut desc: jsapi::JS::MutableHandle, + obj: *mut jsapi::JSObject, attrs: u32) { desc.obj = obj; desc.attrs = attrs; diff --git a/components/script/dom/bindings/refcounted.rs b/components/script/dom/bindings/refcounted.rs index 8acbe823e7c1..2ba52386bb21 100644 --- a/components/script/dom/bindings/refcounted.rs +++ b/components/script/dom/bindings/refcounted.rs @@ -29,8 +29,8 @@ use dom::bindings::js::Root; use dom::bindings::reflector::{DomObject, Reflector}; use dom::bindings::trace::trace_reflector; use dom::promise::Promise; -use js::jsapi::JSAutoCompartment; -use js::jsapi::JSTracer; +use js; +use js::jsapi; use libc; use script_thread::Runnable; use script_thread::ScriptThread; @@ -122,7 +122,7 @@ impl TrustedPromise { } /// A runnable which will reject the promise. - #[allow(unrooted_must_root)] + #[allow(unrooted_must_root, unsafe_code)] pub fn reject_runnable(self, error: Error) -> impl Runnable + Send { struct RejectPromise(TrustedPromise, Error); impl Runnable for RejectPromise { @@ -131,7 +131,9 @@ impl TrustedPromise { let this = *self; let cx = script_thread.get_cx(); let promise = this.0.root(); - let _ac = JSAutoCompartment::new(cx, promise.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, promise.reflector().get_jsobject().get()) + }; promise.reject_error(cx, this.1); } } @@ -139,7 +141,7 @@ impl TrustedPromise { } /// A runnable which will resolve the promise. - #[allow(unrooted_must_root)] + #[allow(unrooted_must_root, unsafe_code)] pub fn resolve_runnable(self, value: T) -> impl Runnable + Send where T: ToJSValConvertible + Send { @@ -150,7 +152,9 @@ impl TrustedPromise { let this = *self; let cx = script_thread.get_cx(); let promise = this.0.root(); - let _ac = JSAutoCompartment::new(cx, promise.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, promise.reflector().get_jsobject().get()) + }; promise.resolve_native(cx, &this.1); } } @@ -283,7 +287,7 @@ fn remove_nulls (table: &mut HashMap>) { /// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES #[allow(unrooted_must_root)] -pub unsafe extern "C" fn trace_refcounted_objects(tracer: *mut JSTracer, +pub unsafe extern "C" fn trace_refcounted_objects(tracer: *mut jsapi::JSTracer, _data: *mut os::raw::c_void) { info!("tracing live refcounted references"); LIVE_REFERENCES.with(|ref r| { diff --git a/components/script/dom/bindings/reflector.rs b/components/script/dom/bindings/reflector.rs index 896cf74a34f9..e32722b5550a 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -7,7 +7,8 @@ use dom::bindings::conversions::DerivedFrom; use dom::bindings::js::Root; use dom::globalscope::GlobalScope; -use js::jsapi::{HandleObject, JSContext, JSObject, Heap}; +use js::heap::Heap; +use js::jsapi; use std::default::Default; /// Create the reflector for a new DOM object and yield ownership to the @@ -15,7 +16,7 @@ use std::default::Default; pub fn reflect_dom_object( obj: Box, global: &U, - wrap_fn: unsafe fn(*mut JSContext, &GlobalScope, Box) -> Root) + wrap_fn: unsafe fn(*mut jsapi::JSContext, &GlobalScope, Box) -> Root) -> Root where T: DomObject, U: DerivedFrom { @@ -32,7 +33,7 @@ pub fn reflect_dom_object( // If you're renaming or moving this field, update the path in plugins::reflector as well pub struct Reflector { #[ignore_heap_size_of = "defined and measured in rust-mozjs"] - object: Heap<*mut JSObject>, + object: Heap<*mut jsapi::JSObject>, } #[allow(unrooted_must_root)] @@ -45,12 +46,12 @@ impl PartialEq for Reflector { impl Reflector { /// Get the reflector. #[inline] - pub fn get_jsobject(&self) -> HandleObject { + pub fn get_jsobject(&self) -> jsapi::JS::HandleObject { self.object.handle() } /// Initialize the reflector. (May be called only once.) - pub fn set_jsobject(&mut self, object: *mut JSObject) { + pub fn set_jsobject(&mut self, object: *mut jsapi::JSObject) { assert!(self.object.get().is_null()); assert!(!object.is_null()); self.object.set(object); @@ -59,7 +60,7 @@ impl Reflector { /// Return a pointer to the memory location at which the JS reflector /// object is stored. Used to root the reflector, as /// required by the JSAPI rooting APIs. - pub fn rootable(&self) -> &Heap<*mut JSObject> { + pub fn rootable(&self) -> &Heap<*mut jsapi::JSObject> { &self.object } @@ -91,11 +92,11 @@ impl DomObject for Reflector { /// A trait to initialize the `Reflector` for a DOM object. pub trait MutDomObject: DomObject { /// Initializes the Reflector - fn init_reflector(&mut self, obj: *mut JSObject); + fn init_reflector(&mut self, obj: *mut jsapi::JSObject); } impl MutDomObject for Reflector { - fn init_reflector(&mut self, obj: *mut JSObject) { + fn init_reflector(&mut self, obj: *mut jsapi::JSObject) { self.set_jsobject(obj) } } diff --git a/components/script/dom/bindings/settings_stack.rs b/components/script/dom/bindings/settings_stack.rs index bf67bae5f3f8..0fe95a42fd5b 100644 --- a/components/script/dom/bindings/settings_stack.rs +++ b/components/script/dom/bindings/settings_stack.rs @@ -5,10 +5,7 @@ use dom::bindings::js::{JS, Root}; use dom::bindings::trace::JSTraceable; use dom::globalscope::GlobalScope; -use js::jsapi::GetScriptedCallerGlobal; -use js::jsapi::HideScriptedCaller; -use js::jsapi::JSTracer; -use js::jsapi::UnhideScriptedCaller; +use js::jsapi; use js::rust::Runtime; use std::cell::RefCell; use std::thread; @@ -29,7 +26,7 @@ struct StackEntry { } /// Traces the script settings stack. -pub unsafe fn trace(tracer: *mut JSTracer) { +pub unsafe fn trace(tracer: *mut jsapi::JSTracer) { STACK.with(|stack| { stack.borrow().trace(tracer); }) @@ -102,7 +99,7 @@ impl AutoIncumbentScript { unsafe { let cx = Runtime::get(); assert!(!cx.is_null()); - HideScriptedCaller(cx); + jsapi::JS::HideScriptedCaller(cx); } STACK.with(|stack| { trace!("Prepare to run a callback with {:p}", global); @@ -137,7 +134,7 @@ impl Drop for AutoIncumbentScript { // Step 1-2. let cx = Runtime::get(); assert!(!cx.is_null()); - UnhideScriptedCaller(cx); + jsapi::JS::UnhideScriptedCaller(cx); } } } @@ -155,7 +152,7 @@ pub fn incumbent_global() -> Option> { unsafe { let cx = Runtime::get(); assert!(!cx.is_null()); - let global = GetScriptedCallerGlobal(cx); + let global = jsapi::JS::GetScriptedCallerGlobal(cx); if !global.is_null() { return Some(GlobalScope::from_object(global)); } diff --git a/components/script/dom/bindings/str.rs b/components/script/dom/bindings/str.rs index ea0b4f529b0d..2a13338c9661 100644 --- a/components/script/dom/bindings/str.rs +++ b/components/script/dom/bindings/str.rs @@ -151,7 +151,7 @@ pub fn is_token(s: &[u8]) -> bool { /// and in Servo.) /// /// This type is currently `!Send`, in order to help with an independent -/// experiment to store `JSString`s rather than Rust `String`s. +/// experiment to store `jsapi::JSString`s rather than Rust `String`s. #[derive(Clone, Debug, Eq, Hash, HeapSizeOf, Ord, PartialEq, PartialOrd)] pub struct DOMString(String, PhantomData<*const ()>); diff --git a/components/script/dom/bindings/structuredclone.rs b/components/script/dom/bindings/structuredclone.rs index 5644784e10c3..0b861461c5e1 100644 --- a/components/script/dom/bindings/structuredclone.rs +++ b/components/script/dom/bindings/structuredclone.rs @@ -11,17 +11,10 @@ use dom::bindings::js::Root; use dom::bindings::reflector::DomObject; use dom::blob::{Blob, BlobImpl}; use dom::globalscope::GlobalScope; -use js::jsapi::{Handle, HandleObject, HandleValue, MutableHandleValue, JSAutoCompartment, JSContext}; -use js::jsapi::{JSStructuredCloneCallbacks, JSStructuredCloneReader, JSStructuredCloneWriter}; -use js::jsapi::{JS_ClearPendingException, JSObject, JS_ReadStructuredClone}; -use js::jsapi::{JS_ReadBytes, JS_WriteBytes}; -use js::jsapi::{JS_ReadUint32Pair, JS_WriteUint32Pair}; -use js::jsapi::{JS_STRUCTURED_CLONE_VERSION, JS_WriteStructuredClone}; -use js::jsapi::{MutableHandleObject, TransferableOwnership}; -use libc::size_t; +use js; +use js::jsapi; use std::os::raw; use std::ptr; -use std::slice; // TODO: Should we add Min and Max const to https://github.com/servo/rust-mozjs/blob/master/src/consts.rs? // TODO: Determine for sure which value Min and Max should have. @@ -36,97 +29,73 @@ enum StructuredCloneTags { } #[cfg(target_pointer_width = "64")] -unsafe fn write_length(w: *mut JSStructuredCloneWriter, +unsafe fn write_length(w: *mut jsapi::JSStructuredCloneWriter, length: usize) { let high: u32 = (length >> 32) as u32; let low: u32 = length as u32; - assert!(JS_WriteUint32Pair(w, high, low)); + assert!(jsapi::JS_WriteUint32Pair(w, high, low)); } #[cfg(target_pointer_width = "32")] -unsafe fn write_length(w: *mut JSStructuredCloneWriter, +unsafe fn write_length(w: *mut jsapi::JSStructuredCloneWriter, length: usize) { - assert!(JS_WriteUint32Pair(w, length as u32, 0)); + assert!(jsapi::JS_WriteUint32Pair(w, length as u32, 0)); } #[cfg(target_pointer_width = "64")] -unsafe fn read_length(r: *mut JSStructuredCloneReader) +unsafe fn read_length(r: *mut jsapi::JSStructuredCloneReader) -> usize { let mut high: u32 = 0; let mut low: u32 = 0; - assert!(JS_ReadUint32Pair(r, &mut high as *mut u32, &mut low as *mut u32)); + assert!(jsapi::JS_ReadUint32Pair(r, &mut high as *mut u32, &mut low as *mut u32)); return (low << high) as usize; } #[cfg(target_pointer_width = "32")] -unsafe fn read_length(r: *mut JSStructuredCloneReader) +unsafe fn read_length(r: *mut jsapi::JSStructuredCloneReader) -> usize { let mut length: u32 = 0; let mut zero: u32 = 0; - assert!(JS_ReadUint32Pair(r, &mut length as *mut u32, &mut zero as *mut u32)); + assert!(jsapi::JS_ReadUint32Pair(r, &mut length as *mut u32, &mut zero as *mut u32)); return length as usize; } -struct StructuredCloneWriter { - w: *mut JSStructuredCloneWriter, -} - -impl StructuredCloneWriter { - unsafe fn write_slice(&self, v: &[u8]) { - let type_length = v.len(); - write_length(self.w, type_length); - assert!(JS_WriteBytes(self.w, v.as_ptr() as *const raw::c_void, type_length)); - } - unsafe fn write_str(&self, s: &str) { - self.write_slice(s.as_bytes()); - } -} - -struct StructuredCloneReader { - r: *mut JSStructuredCloneReader, -} - -impl StructuredCloneReader { - unsafe fn read_bytes(&self) -> Vec { - let mut bytes = vec![0u8; read_length(self.r)]; - let blob_length = bytes.len(); - assert!(JS_ReadBytes(self.r, bytes.as_mut_ptr() as *mut raw::c_void, blob_length)); - return bytes; - } - unsafe fn read_str(&self) -> String { - let str_buffer = self.read_bytes(); - return String::from_utf8_unchecked(str_buffer); - } -} - -unsafe fn read_blob(cx: *mut JSContext, - r: *mut JSStructuredCloneReader) - -> *mut JSObject { - let structured_reader = StructuredCloneReader { r: r }; - let blob_buffer = structured_reader.read_bytes(); - let type_str = structured_reader.read_str(); +unsafe fn read_blob(cx: *mut jsapi::JSContext, + r: *mut jsapi::JSStructuredCloneReader) + -> *mut jsapi::JSObject { + let blob_length = read_length(r); + let type_str_length = read_length(r); + let mut blob_buffer = vec![0u8; blob_length]; + assert!(jsapi::JS_ReadBytes(r, blob_buffer.as_mut_ptr() as *mut raw::c_void, blob_length)); + let mut type_str_buffer = vec![0u8; type_str_length]; + assert!(jsapi::JS_ReadBytes(r, type_str_buffer.as_mut_ptr() as *mut raw::c_void, type_str_length)); + let type_str = String::from_utf8_unchecked(type_str_buffer); let target_global = GlobalScope::from_context(cx); let blob = Blob::new(&target_global, BlobImpl::new_from_bytes(blob_buffer), type_str); return blob.reflector().get_jsobject().get() } unsafe fn write_blob(blob: Root, - w: *mut JSStructuredCloneWriter) + w: *mut jsapi::JSStructuredCloneWriter) -> Result<(), ()> { - let structured_writer = StructuredCloneWriter { w: w }; let blob_vec = blob.get_bytes()?; - assert!(JS_WriteUint32Pair(w, StructuredCloneTags::DomBlob as u32, 0)); - structured_writer.write_slice(&blob_vec); - structured_writer.write_str(&blob.type_string()); + let blob_length = blob_vec.len(); + let type_string_bytes = blob.type_string().as_bytes().to_vec(); + let type_string_length = type_string_bytes.len(); + assert!(jsapi::JS_WriteUint32Pair(w, StructuredCloneTags::DomBlob as u32, 0)); + write_length(w, blob_length); + write_length(w, type_string_length); + assert!(jsapi::JS_WriteBytes(w, blob_vec.as_ptr() as *const raw::c_void, blob_length)); + assert!(jsapi::JS_WriteBytes(w, type_string_bytes.as_ptr() as *const raw::c_void, type_string_length)); return Ok(()) } -unsafe extern "C" fn read_callback(cx: *mut JSContext, - r: *mut JSStructuredCloneReader, +unsafe extern "C" fn read_callback(cx: *mut jsapi::JSContext, + r: *mut jsapi::JSStructuredCloneReader, tag: u32, _data: u32, _closure: *mut raw::c_void) - -> *mut JSObject { + -> *mut jsapi::JSObject { assert!(tag < StructuredCloneTags::Max as u32, "tag should be lower than StructuredCloneTags::Max"); assert!(tag > StructuredCloneTags::Min as u32, "tag should be higher than StructuredCloneTags::Min"); if tag == StructuredCloneTags::DomBlob as u32 { @@ -135,9 +104,9 @@ unsafe extern "C" fn read_callback(cx: *mut JSContext, return ptr::null_mut() } -unsafe extern "C" fn write_callback(_cx: *mut JSContext, - w: *mut JSStructuredCloneWriter, - obj: HandleObject, +unsafe extern "C" fn write_callback(_cx: *mut jsapi::JSContext, + w: *mut jsapi::JSStructuredCloneWriter, + obj: jsapi::JS::HandleObject, _closure: *mut raw::c_void) -> bool { if let Ok(blob) = root_from_handleobject::(obj) { @@ -146,22 +115,22 @@ unsafe extern "C" fn write_callback(_cx: *mut JSContext, return false } -unsafe extern "C" fn read_transfer_callback(_cx: *mut JSContext, - _r: *mut JSStructuredCloneReader, +unsafe extern "C" fn read_transfer_callback(_cx: *mut jsapi::JSContext, + _r: *mut jsapi::JSStructuredCloneReader, _tag: u32, _content: *mut raw::c_void, _extra_data: u64, _closure: *mut raw::c_void, - _return_object: MutableHandleObject) + _return_object: jsapi::JS::MutableHandleObject) -> bool { false } -unsafe extern "C" fn write_transfer_callback(_cx: *mut JSContext, - _obj: Handle<*mut JSObject>, +unsafe extern "C" fn write_transfer_callback(_cx: *mut jsapi::JSContext, + _obj: jsapi::JS::Handle<*mut jsapi::JSObject>, _closure: *mut raw::c_void, _tag: *mut u32, - _ownership: *mut TransferableOwnership, + _ownership: *mut jsapi::JS::TransferableOwnership, _content: *mut *mut raw::c_void, _extra_data: *mut u64) -> bool { @@ -169,16 +138,16 @@ unsafe extern "C" fn write_transfer_callback(_cx: *mut JSContext, } unsafe extern "C" fn free_transfer_callback(_tag: u32, - _ownership: TransferableOwnership, + _ownership: jsapi::JS::TransferableOwnership, _content: *mut raw::c_void, _extra_data: u64, _closure: *mut raw::c_void) { } -unsafe extern "C" fn report_error_callback(_cx: *mut JSContext, _errorid: u32) { +unsafe extern "C" fn report_error_callback(_cx: *mut jsapi::JSContext, _errorid: u32) { } -static STRUCTURED_CLONE_CALLBACKS: JSStructuredCloneCallbacks = JSStructuredCloneCallbacks { +static STRUCTURED_CLONE_CALLBACKS: jsapi::JSStructuredCloneCallbacks = jsapi::JSStructuredCloneCallbacks { read: Some(read_callback), write: Some(write_callback), reportError: Some(report_error_callback), @@ -190,76 +159,64 @@ static STRUCTURED_CLONE_CALLBACKS: JSStructuredCloneCallbacks = JSStructuredClon /// A buffer for a structured clone. pub enum StructuredCloneData { /// A non-serializable (default) variant - Struct(*mut u64, size_t), + Struct(js::sc::StructuredCloneBuffer), /// A variant that can be serialized Vector(Vec) } impl StructuredCloneData { /// Writes a structured clone. Returns a `DataClone` error if that fails. - pub fn write(cx: *mut JSContext, message: HandleValue) -> Fallible { - let mut data = ptr::null_mut(); - let mut nbytes = 0; - let result = unsafe { - JS_WriteStructuredClone(cx, - message, - &mut data, - &mut nbytes, - &STRUCTURED_CLONE_CALLBACKS, - ptr::null_mut(), - HandleValue::undefined()) - }; - if !result { - unsafe { - JS_ClearPendingException(cx); + pub fn write(cx: *mut jsapi::JSContext, message: jsapi::JS::HandleValue) -> Fallible { + let scope = jsapi::JS::StructuredCloneScope::SameProcessDifferentThread; + let callbacks = &STRUCTURED_CLONE_CALLBACKS; + let mut data = js::sc::StructuredCloneBuffer::new(scope, callbacks); + + match data.write(message, callbacks) { + Ok(()) => Ok(StructuredCloneData::Struct(data)), + Err(()) => { + unsafe { + jsapi::JS_ClearPendingException(cx); + } + Err(Error::DataClone) } - return Err(Error::DataClone); } - Ok(StructuredCloneData::Struct(data, nbytes)) } /// Converts a StructuredCloneData to Vec for inter-thread sharing pub fn move_to_arraybuffer(self) -> Vec { match self { - StructuredCloneData::Struct(data, nbytes) => { - unsafe { - slice::from_raw_parts(data as *mut u8, nbytes).to_vec() - } - } + StructuredCloneData::Struct(data) => data.copy_to_vec(), StructuredCloneData::Vector(msg) => msg } } /// Reads a structured clone. /// - /// Panics if `JS_ReadStructuredClone` fails. + /// Panics if `jsapi::JS_ReadStructuredClone` fails. fn read_clone(global: &GlobalScope, - data: *mut u64, - nbytes: size_t, - rval: MutableHandleValue) { + data: &mut js::sc::StructuredCloneBuffer, + rval: jsapi::JS::MutableHandleValue) { let cx = global.get_cx(); let globalhandle = global.reflector().get_jsobject(); - let _ac = JSAutoCompartment::new(cx, globalhandle.get()); - unsafe { - assert!(JS_ReadStructuredClone(cx, - data, - nbytes, - JS_STRUCTURED_CLONE_VERSION, - rval, - &STRUCTURED_CLONE_CALLBACKS, - ptr::null_mut())); - } + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, globalhandle.get()) + }; + data.read(rval, &STRUCTURED_CLONE_CALLBACKS).unwrap(); } /// Thunk for the actual `read_clone` method. Resolves proper variant for read_clone. - pub fn read(self, global: &GlobalScope, rval: MutableHandleValue) { + pub fn read(mut self, global: &GlobalScope, rval: jsapi::JS::MutableHandleValue) { match self { - StructuredCloneData::Vector(mut vec_msg) => { - let nbytes = vec_msg.len(); - let data = vec_msg.as_mut_ptr() as *mut u64; - StructuredCloneData::read_clone(global, data, nbytes, rval); + StructuredCloneData::Vector(vec_msg) => { + let scope = jsapi::JS::StructuredCloneScope::SameProcessDifferentThread; + let callbacks = &STRUCTURED_CLONE_CALLBACKS; + let mut data = js::sc::StructuredCloneBuffer::new(scope, callbacks); + data.write_bytes(&vec_msg[..]).unwrap(); + StructuredCloneData::read_clone(global, &mut data, rval); + } + StructuredCloneData::Struct(ref mut data) => { + StructuredCloneData::read_clone(global, data, rval); } - StructuredCloneData::Struct(data, nbytes) => StructuredCloneData::read_clone(global, data, nbytes, rval) } } } diff --git a/components/script/dom/bindings/trace.rs b/components/script/dom/bindings/trace.rs index df681e3add9f..25a6dff31929 100644 --- a/components/script/dom/bindings/trace.rs +++ b/components/script/dom/bindings/trace.rs @@ -20,8 +20,8 @@ //! calls `trace()` on the field. //! For example, for fields of type `JS`, `JS::trace()` calls //! `trace_reflector()`. -//! 4. `trace_reflector()` calls `JS::TraceEdge()` with a -//! pointer to the `JSObject` for the reflector. This notifies the GC, which +//! 4. `trace_reflector()` calls `jsapi::JS::TraceEdge()` with a +//! pointer to the `jsapi::JSObject` for the reflector. This notifies the GC, which //! will add the object to the graph, and will trace that object as well. //! 5. When the GC finishes tracing, it [`finalizes`](../index.html#destruction) //! any reflectors that were not reachable. @@ -57,8 +57,8 @@ use hyper::mime::Mime; use hyper::status::StatusCode; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use js::glue::{CallObjectTracer, CallValueTracer}; -use js::jsapi::{GCTraceKindToAscii, Heap, JSObject, JSTracer, TraceKind}; -use js::jsval::JSVal; +use js::heap::Heap; +use js::jsapi; use js::rust::Runtime; use msg::constellation_msg::{BrowsingContextId, FrameType, PipelineId, TopLevelBrowsingContextId}; use net_traits::{Metadata, NetworkError, ReferrerPolicy, ResourceThreads}; @@ -115,7 +115,7 @@ use webvr_traits::WebVRGamepadHand; /// A trait to allow tracing (only) DOM objects. pub unsafe trait JSTraceable { /// Trace `self`. - unsafe fn trace(&self, trc: *mut JSTracer); + unsafe fn trace(&self, trc: *mut jsapi::JSTracer); } unsafe_no_jsmanaged_fields!(CSSError); @@ -126,8 +126,8 @@ unsafe_no_jsmanaged_fields!(Reflector); unsafe_no_jsmanaged_fields!(Duration); -/// Trace a `JSVal`. -pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: &Heap) { +/// Trace a `jsapi::JS::Value`. +pub fn trace_jsval(tracer: *mut jsapi::JSTracer, description: &str, val: &Heap) { unsafe { if !val.get().is_markable() { return; @@ -135,54 +135,54 @@ pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: &Heap) trace!("tracing value {}", description); CallValueTracer(tracer, - val.ptr.get() as *mut _, - GCTraceKindToAscii(val.get().trace_kind())); + val as *const _ as *mut _, + jsapi::JS::GCTraceKindToAscii(val.get().trace_kind())); } } -/// Trace the `JSObject` held by `reflector`. +/// Trace the `jsapi::JSObject` held by `reflector`. #[allow(unrooted_must_root)] -pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) { +pub fn trace_reflector(tracer: *mut jsapi::JSTracer, description: &str, reflector: &Reflector) { trace!("tracing reflector {}", description); trace_object(tracer, description, reflector.rootable()) } -/// Trace a `JSObject`. -pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: &Heap<*mut JSObject>) { +/// Trace a `jsapi::JSObject`. +pub fn trace_object(tracer: *mut jsapi::JSTracer, description: &str, obj: &Heap<*mut jsapi::JSObject>) { unsafe { trace!("tracing {}", description); CallObjectTracer(tracer, - obj.ptr.get() as *mut _, - GCTraceKindToAscii(TraceKind::Object)); + obj as *const _ as *mut _, + jsapi::JS::GCTraceKindToAscii(jsapi::JS::TraceKind::Object)); } } unsafe impl JSTraceable for Rc { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { (**self).trace(trc) } } unsafe impl JSTraceable for Arc { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { (**self).trace(trc) } } unsafe impl JSTraceable for ServoArc { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { (**self).trace(trc) } } unsafe impl JSTraceable for Box { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { (**self).trace(trc) } } unsafe impl JSTraceable for [T] { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { for e in self.iter() { e.trace(trc); } @@ -190,25 +190,25 @@ unsafe impl JSTraceable for [T] { } unsafe impl JSTraceable for Cell { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { self.get().trace(trc) } } unsafe impl JSTraceable for UnsafeCell { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { (*self.get()).trace(trc) } } unsafe impl JSTraceable for DOMRefCell { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { (*self).borrow_for_gc_trace().trace(trc) } } -unsafe impl JSTraceable for Heap<*mut JSObject> { - unsafe fn trace(&self, trc: *mut JSTracer) { +unsafe impl JSTraceable for Heap<*mut jsapi::JSObject> { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { if self.get().is_null() { return; } @@ -216,8 +216,8 @@ unsafe impl JSTraceable for Heap<*mut JSObject> { } } -unsafe impl JSTraceable for Heap { - unsafe fn trace(&self, trc: *mut JSTracer) { +unsafe impl JSTraceable for Heap { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { trace_jsval(trc, "heap value", self); } } @@ -226,7 +226,7 @@ unsafe impl JSTraceable for Heap { // if e.trace() is a no-op (e.g it is an unsafe_no_jsmanaged_fields type) unsafe impl JSTraceable for Vec { #[inline] - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { for e in &*self { e.trace(trc); } @@ -235,7 +235,7 @@ unsafe impl JSTraceable for Vec { unsafe impl JSTraceable for VecDeque { #[inline] - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { for e in &*self { e.trace(trc); } @@ -243,7 +243,7 @@ unsafe impl JSTraceable for VecDeque { } unsafe impl JSTraceable for (T, T, T, T) { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { self.0.trace(trc); self.1.trace(trc); self.2.trace(trc); @@ -255,7 +255,7 @@ unsafe impl JSTraceable for (T, T, T, T) { // if e.trace() is a no-op (e.g it is an unsafe_no_jsmanaged_fields type) unsafe impl JSTraceable for SmallVec<[T; 1]> { #[inline] - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { for e in self.iter() { e.trace(trc); } @@ -264,14 +264,14 @@ unsafe impl JSTraceable for SmallVec<[T; 1]> { unsafe impl JSTraceable for Option { #[inline] - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { self.as_ref().map(|e| e.trace(trc)); } } unsafe impl JSTraceable for Result { #[inline] - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { match *self { Ok(ref inner) => inner.trace(trc), Err(ref inner) => inner.trace(trc), @@ -285,7 +285,7 @@ unsafe impl JSTraceable for HashMap S: BuildHasher { #[inline] - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { for (k, v) in &*self { k.trace(trc); v.trace(trc); @@ -298,7 +298,7 @@ unsafe impl JSTraceable for HashSet S: BuildHasher { #[inline] - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { for v in &*self { v.trace(trc); } @@ -307,7 +307,7 @@ unsafe impl JSTraceable for HashSet unsafe impl JSTraceable for BTreeMap { #[inline] - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { for (k, v) in self { k.trace(trc); v.trace(trc); @@ -317,7 +317,7 @@ unsafe impl JSTraceable for BTreeMap unsafe impl JSTraceable for (A, B) { #[inline] - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { let (ref a, ref b) = *self; a.trace(trc); b.trace(trc); @@ -326,7 +326,7 @@ unsafe impl JSTraceable for (A, B) { unsafe impl JSTraceable for (A, B, C) { #[inline] - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { let (ref a, ref b, ref c) = *self; a.trace(trc); b.trace(trc); @@ -413,21 +413,21 @@ unsafe_no_jsmanaged_fields!(ScriptToConstellationChan); unsafe impl<'a> JSTraceable for &'a str { #[inline] - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for fn(A) -> B { #[inline] - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for IpcSender where T: for<'de> Deserialize<'de> + Serialize { #[inline] - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing } } @@ -435,210 +435,210 @@ unsafe impl JSTraceable for IpcSender where T: for<'de> Deserialize<'de> + // Safe thanks to the Send bound. unsafe impl JSTraceable for Box { #[inline] - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for () { #[inline] - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for IpcReceiver where T: for<'de> Deserialize<'de> + Serialize { #[inline] - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for Trusted { #[inline] - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for Receiver { #[inline] - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for Sender { #[inline] - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for WebGLReceiver where T: for<'de> Deserialize<'de> + Serialize { #[inline] - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for WebGLSender where T: for<'de> Deserialize<'de> + Serialize { #[inline] - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for Transform2D { #[inline] - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for Transform3D { #[inline] - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for Point2D { #[inline] - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for ScaleFactor { #[inline] - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for Vector2D { #[inline] - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for EuclidLength { #[inline] - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for Rect { #[inline] - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for Rect { #[inline] - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for TypedSize2D { #[inline] - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for TypedSize2D { #[inline] - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing } } unsafe impl JSTraceable for Mutex> { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for RwLock { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } unsafe impl JSTraceable for StyleLocked { - unsafe fn trace(&self, _trc: *mut JSTracer) { + unsafe fn trace(&self, _trc: *mut jsapi::JSTracer) { // Do nothing. } } @@ -647,7 +647,7 @@ unsafe impl JSTraceable for StylesheetSet where S: JSTraceable + ::style::stylesheets::StylesheetInDocument + PartialEq + 'static, { - unsafe fn trace(&self, tracer: *mut JSTracer) { + unsafe fn trace(&self, tracer: *mut jsapi::JSTracer) { for s in self.iter() { s.trace(tracer) } @@ -692,7 +692,7 @@ impl RootedTraceableSet { }) } - unsafe fn trace(&self, tracer: *mut JSTracer) { + unsafe fn trace(&self, tracer: *mut jsapi::JSTracer) { for traceable in &self.set { (**traceable).trace(tracer); } @@ -702,7 +702,7 @@ impl RootedTraceableSet { /// Roots any JSTraceable thing /// /// If you have a valid DomObject, use Root. -/// If you have GC things like *mut JSObject or JSVal, use rooted!. +/// If you have GC things like *mut jsapi::JSObject or jsapi::JS::Value, use rooted!. /// If you have an arbitrary number of DomObjects to root, use rooted_vec!. /// If you know what you're doing, use this. #[derive(JSTraceable)] @@ -733,7 +733,7 @@ impl<'a, T: JSTraceable + 'static> Drop for RootedTraceable<'a, T> { /// Roots any JSTraceable thing /// /// If you have a valid DomObject, use Root. -/// If you have GC things like *mut JSObject or JSVal, use rooted!. +/// If you have GC things like *mut jsapi::JSObject or jsapi::JS::Value, use rooted!. /// If you have an arbitrary number of DomObjects to root, use rooted_vec!. /// If you know what you're doing, use this. pub struct RootedTraceableBox { @@ -741,7 +741,7 @@ pub struct RootedTraceableBox { } unsafe impl JSTraceable for RootedTraceableBox { - unsafe fn trace(&self, tracer: *mut JSTracer) { + unsafe fn trace(&self, tracer: *mut jsapi::JSTracer) { (*self.ptr).trace(tracer); } } @@ -863,7 +863,7 @@ impl<'a, T: JSTraceable> DerefMut for RootedVec<'a, T> { } /// SM Callback that traces the rooted traceables -pub unsafe fn trace_traceables(tracer: *mut JSTracer) { +pub unsafe fn trace_traceables(tracer: *mut jsapi::JSTracer) { trace!("tracing stack-rooted traceables"); ROOTED_TRACEABLES.with(|ref traceables| { let traceables = traceables.borrow(); diff --git a/components/script/dom/bindings/utils.rs b/components/script/dom/bindings/utils.rs index 1c4682225b02..0f1d5bafe88d 100644 --- a/components/script/dom/bindings/utils.rs +++ b/components/script/dom/bindings/utils.rs @@ -15,22 +15,14 @@ use dom::bindings::trace::trace_object; use dom::windowproxy; use heapsize::HeapSizeOf; use js; -use js::JS_CALLEE; use js::glue::{CallJitGetterOp, CallJitMethodOp, CallJitSetterOp, IsWrapper}; use js::glue::{GetCrossCompartmentWrapper, WrapperNew}; use js::glue::{RUST_FUNCTION_VALUE_TO_JITINFO, RUST_JSID_IS_INT, RUST_JSID_IS_STRING}; use js::glue::{RUST_JSID_TO_INT, RUST_JSID_TO_STRING, UnwrapObject}; -use js::jsapi::{CallArgs, DOMCallbacks, GetGlobalForObjectCrossCompartment}; -use js::jsapi::{HandleId, HandleObject, HandleValue, Heap, JSAutoCompartment, JSContext}; -use js::jsapi::{JSJitInfo, JSObject, JSTracer, JSWrapObjectCallbacks}; -use js::jsapi::{JS_DeletePropertyById, JS_EnumerateStandardClasses}; -use js::jsapi::{JS_ForwardGetPropertyTo, JS_GetLatin1StringCharsAndLength}; -use js::jsapi::{JS_GetProperty, JS_GetPrototype, JS_GetReservedSlot, JS_HasProperty}; -use js::jsapi::{JS_HasPropertyById, JS_IsExceptionPending, JS_IsGlobalObject}; -use js::jsapi::{JS_ResolveStandardClass, JS_SetProperty, ToWindowProxyIfWindow}; -use js::jsapi::{JS_StringHasLatin1Chars, MutableHandleValue, ObjectOpResult}; -use js::jsval::{JSVal, UndefinedValue}; -use js::rust::{GCMethods, ToString, get_object_class, is_dom_class}; +use js::heap::Heap; +use js::jsapi; +use js::jsval::UndefinedValue; +use js::rust::{GCMethods, ToString, get_object_class, is_dom_class, is_global}; use libc; use std::ffi::CString; use std::os::raw::{c_char, c_void}; @@ -69,17 +61,17 @@ pub const DOM_PROTO_UNFORGEABLE_HOLDER_SLOT: u32 = 0; /// The index of the slot that contains a reference to the ProtoOrIfaceArray. // All DOM globals must have a slot at DOM_PROTOTYPE_SLOT. -pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT; +pub const DOM_PROTOTYPE_SLOT: u32 = js::jsapi::JSCLASS_GLOBAL_SLOT_COUNT; /// The flag set on the `JSClass`es for DOM global objects. // NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and // LSetDOMProperty. Those constants need to be changed accordingly if this value // changes. -pub const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1; +pub const JSCLASS_DOM_GLOBAL: u32 = js::jsapi::JSCLASS_USERBIT1; /// The struct that holds inheritance information for DOM object reflectors. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug)] pub struct DOMClass { /// A list of interfaces that this object implements, in order of decreasing /// derivedness. @@ -113,34 +105,34 @@ unsafe impl Sync for DOMJSClass {} /// Returns the ProtoOrIfaceArray for the given global object. /// Fails if `global` is not a DOM global object. -pub fn get_proto_or_iface_array(global: *mut JSObject) -> *mut ProtoOrIfaceArray { +pub fn get_proto_or_iface_array(global: *mut jsapi::JSObject) -> *mut ProtoOrIfaceArray { unsafe { assert!(((*get_object_class(global)).flags & JSCLASS_DOM_GLOBAL) != 0); - JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT).to_private() as *mut ProtoOrIfaceArray + jsapi::JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT).to_private() as *mut ProtoOrIfaceArray } } -/// An array of *mut JSObject of size PROTO_OR_IFACE_LENGTH. -pub type ProtoOrIfaceArray = [*mut JSObject; PROTO_OR_IFACE_LENGTH]; +/// An array of *mut jsapi::JSObject of size PROTO_OR_IFACE_LENGTH. +pub type ProtoOrIfaceArray = [*mut jsapi::JSObject; PROTO_OR_IFACE_LENGTH]; /// Gets the property `id` on `proxy`'s prototype. If it exists, `*found` is /// set to true and `*vp` to the value, otherwise `*found` is set to false. /// /// Returns false on JSAPI failure. -pub unsafe fn get_property_on_prototype(cx: *mut JSContext, - proxy: HandleObject, - receiver: HandleValue, - id: HandleId, +pub unsafe fn get_property_on_prototype(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + receiver: jsapi::JS::HandleValue, + id: jsapi::JS::HandleId, found: *mut bool, - vp: MutableHandleValue) + vp: jsapi::JS::MutableHandleValue) -> bool { rooted!(in(cx) let mut proto = ptr::null_mut()); - if !JS_GetPrototype(cx, proxy, proto.handle_mut()) || proto.is_null() { + if !jsapi::JS_GetPrototype(cx, proxy, proto.handle_mut()) || proto.is_null() { *found = false; return true; } let mut has_property = false; - if !JS_HasPropertyById(cx, proto.handle(), id, &mut has_property) { + if !jsapi::JS_HasPropertyById(cx, proto.handle(), id, &mut has_property) { return false; } *found = has_property; @@ -149,12 +141,12 @@ pub unsafe fn get_property_on_prototype(cx: *mut JSContext, return true; } - JS_ForwardGetPropertyTo(cx, proto.handle(), id, receiver, vp) + jsapi::JS_ForwardGetPropertyTo(cx, proto.handle(), id, receiver, vp) } /// Get an array index from the given `jsid`. Returns `None` if the given /// `jsid` is not an integer. -pub fn get_array_index_from_id(_cx: *mut JSContext, id: HandleId) -> Option { +pub fn get_array_index_from_id(_cx: *mut jsapi::JSContext, id: jsapi::JS::HandleId) -> Option { unsafe { if RUST_JSID_IS_INT(id) { return Some(RUST_JSID_TO_INT(id) as u32); @@ -180,8 +172,8 @@ pub fn get_array_index_from_id(_cx: *mut JSContext, id: HandleId) -> Option /// Find the enum equivelent of a string given by `v` in `pairs`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and /// `Ok((None, value))` if there was no matching string. -pub unsafe fn find_enum_value<'a, T>(cx: *mut JSContext, - v: HandleValue, +pub unsafe fn find_enum_value<'a, T>(cx: *mut jsapi::JSContext, + v: jsapi::JS::HandleValue, pairs: &'a [(&'static str, T)]) -> Result<(Option<&'a T>, DOMString), ()> { let jsstr = ToString(cx, v); @@ -195,7 +187,7 @@ pub unsafe fn find_enum_value<'a, T>(cx: *mut JSContext, /// Returns wether `obj` is a platform object /// https://heycam.github.io/webidl/#dfn-platform-object -pub fn is_platform_object(obj: *mut JSObject) -> bool { +pub fn is_platform_object(obj: *mut jsapi::JSObject) -> bool { unsafe { // Fast-path the common case let mut clasp = get_object_class(obj); @@ -210,7 +202,7 @@ pub fn is_platform_object(obj: *mut JSObject) -> bool { } clasp = get_object_class(obj); } - // TODO also check if JS_IsArrayBufferObject + // TODO also check if jsapi::JS_IsArrayBufferObject is_dom_class(&*clasp) } } @@ -218,24 +210,24 @@ pub fn is_platform_object(obj: *mut JSObject) -> bool { /// Get the property with name `property` from `object`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and /// `Ok(false)` if there was no property with the given name. -pub fn get_dictionary_property(cx: *mut JSContext, - object: HandleObject, +pub fn get_dictionary_property(cx: *mut jsapi::JSContext, + object: jsapi::JS::HandleObject, property: &str, - rval: MutableHandleValue) + rval: jsapi::JS::MutableHandleValue) -> Result { - fn has_property(cx: *mut JSContext, - object: HandleObject, + fn has_property(cx: *mut jsapi::JSContext, + object: jsapi::JS::HandleObject, property: &CString, found: &mut bool) -> bool { - unsafe { JS_HasProperty(cx, object, property.as_ptr(), found) } + unsafe { jsapi::JS_HasProperty(cx, object, property.as_ptr(), found) } } - fn get_property(cx: *mut JSContext, - object: HandleObject, + fn get_property(cx: *mut jsapi::JSContext, + object: jsapi::JS::HandleObject, property: &CString, - value: MutableHandleValue) + value: jsapi::JS::MutableHandleValue) -> bool { - unsafe { JS_GetProperty(cx, object, property.as_ptr(), value) } + unsafe { jsapi::JS_GetProperty(cx, object, property.as_ptr(), value) } } let property = CString::new(property).unwrap(); @@ -262,10 +254,10 @@ pub fn get_dictionary_property(cx: *mut JSContext, /// Set the property with name `property` from `object`. /// Returns `Err(())` on JSAPI failure, or null object, /// and Ok(()) otherwise -pub fn set_dictionary_property(cx: *mut JSContext, - object: HandleObject, +pub fn set_dictionary_property(cx: *mut jsapi::JSContext, + object: jsapi::JS::HandleObject, property: &str, - value: HandleValue) + value: jsapi::JS::HandleValue) -> Result<(), ()> { if object.get().is_null() { return Err(()); @@ -273,7 +265,7 @@ pub fn set_dictionary_property(cx: *mut JSContext, let property = CString::new(property).unwrap(); unsafe { - if !JS_SetProperty(cx, object, property.as_ptr(), value) { + if !jsapi::JS_SetProperty(cx, object, property.as_ptr(), value) { return Err(()); } } @@ -282,47 +274,47 @@ pub fn set_dictionary_property(cx: *mut JSContext, } /// Returns whether `proxy` has a property `id` on its prototype. -pub unsafe fn has_property_on_prototype(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId, +pub unsafe fn has_property_on_prototype(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, found: &mut bool) -> bool { rooted!(in(cx) let mut proto = ptr::null_mut()); - if !JS_GetPrototype(cx, proxy, proto.handle_mut()) { + if !jsapi::JS_GetPrototype(cx, proxy, proto.handle_mut()) { return false; } assert!(!proto.is_null()); - JS_HasPropertyById(cx, proto.handle(), id, found) + jsapi::JS_HasPropertyById(cx, proto.handle(), id, found) } /// Drop the resources held by reserved slots of a global object -pub unsafe fn finalize_global(obj: *mut JSObject) { +pub unsafe fn finalize_global(obj: *mut jsapi::JSObject) { let protolist = get_proto_or_iface_array(obj); let list = (*protolist).as_mut_ptr(); for idx in 0..PROTO_OR_IFACE_LENGTH as isize { let entry = list.offset(idx); let value = *entry; - <*mut JSObject>::post_barrier(entry, value, ptr::null_mut()); + <*mut jsapi::JSObject>::post_barrier(entry, value, ptr::null_mut()); } let _: Box = Box::from_raw(protolist); } /// Trace the resources held by reserved slots of a global object -pub unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) { +pub unsafe fn trace_global(tracer: *mut jsapi::JSTracer, obj: *mut jsapi::JSObject) { let array = get_proto_or_iface_array(obj); for proto in (*array).iter() { if !proto.is_null() { trace_object(tracer, "prototype", - &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>)); + &*(proto as *const *mut jsapi::JSObject as *const Heap<*mut jsapi::JSObject>)); } } } /// Enumerate lazy properties of a global object. -pub unsafe extern "C" fn enumerate_global(cx: *mut JSContext, obj: HandleObject) -> bool { - assert!(JS_IsGlobalObject(obj.get())); - if !JS_EnumerateStandardClasses(cx, obj) { +pub unsafe extern "C" fn enumerate_global(cx: *mut jsapi::JSContext, obj: jsapi::JS::HandleObject) -> bool { + assert!(jsapi::JS_IsGlobalObject(obj.get())); + if !jsapi::JS_EnumerateStandardClasses(cx, obj) { return false; } for init_fun in InterfaceObjectMap::MAP.values() { @@ -333,13 +325,13 @@ pub unsafe extern "C" fn enumerate_global(cx: *mut JSContext, obj: HandleObject) /// Resolve a lazy global property, for interface objects and named constructors. pub unsafe extern "C" fn resolve_global( - cx: *mut JSContext, - obj: HandleObject, - id: HandleId, + cx: *mut jsapi::JSContext, + obj: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, rval: *mut bool) -> bool { - assert!(JS_IsGlobalObject(obj.get())); - if !JS_ResolveStandardClass(cx, obj, id, rval) { + assert!(jsapi::JS_IsGlobalObject(obj.get())); + if !jsapi::JS_ResolveStandardClass(cx, obj, id, rval) { return false; } if *rval { @@ -351,12 +343,12 @@ pub unsafe extern "C" fn resolve_global( } let string = RUST_JSID_TO_STRING(id); - if !JS_StringHasLatin1Chars(string) { + if !jsapi::JS_StringHasLatin1Chars(string) { *rval = false; return true; } let mut length = 0; - let ptr = JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length); + let ptr = jsapi::JS_GetLatin1StringCharsAndLength(cx, ptr::null(), string, &mut length); assert!(!ptr.is_null()); let bytes = slice::from_raw_parts(ptr, length as usize); @@ -369,51 +361,53 @@ pub unsafe extern "C" fn resolve_global( true } -unsafe extern "C" fn wrap(cx: *mut JSContext, - _existing: HandleObject, - obj: HandleObject) - -> *mut JSObject { +unsafe extern "C" fn wrap(cx: *mut jsapi::JSContext, + _existing: jsapi::JS::HandleObject, + obj: jsapi::JS::HandleObject) + -> *mut jsapi::JSObject { // FIXME terrible idea. need security wrappers // https://github.com/servo/servo/issues/2382 WrapperNew(cx, obj, GetCrossCompartmentWrapper(), ptr::null(), false) } -unsafe extern "C" fn pre_wrap(cx: *mut JSContext, - _existing: HandleObject, - obj: HandleObject, - _object_passed_to_wrap: HandleObject) - -> *mut JSObject { - let _ac = JSAutoCompartment::new(cx, obj.get()); - let obj = ToWindowProxyIfWindow(obj.get()); - assert!(!obj.is_null()); - obj +unsafe extern "C" fn pre_wrap(cx: *mut jsapi::JSContext, + _existing: jsapi::JS::HandleObject, + obj: jsapi::JS::HandleObject, + _object_passed_to_wrap: jsapi::JS::HandleObject, + rval: jsapi::JS::MutableHandleObject) { + let _ac = js::ac::AutoCompartment::with_obj(cx, obj.get()); + if is_global(obj.get()) { + rval.set(jsapi::js::detail::ToWindowProxyIfWindowSlow(obj.get())); + } else { + rval.set(obj.get()); + } } -/// Callback table for use with JS_SetWrapObjectCallbacks -pub static WRAP_CALLBACKS: JSWrapObjectCallbacks = JSWrapObjectCallbacks { +/// Callback table for use with jsapi::JS_SetWrapObjectCallbacks +pub static WRAP_CALLBACKS: jsapi::JSWrapObjectCallbacks = jsapi::JSWrapObjectCallbacks { wrap: Some(wrap), preWrap: Some(pre_wrap), }; /// Deletes the property `id` from `object`. -pub unsafe fn delete_property_by_id(cx: *mut JSContext, - object: HandleObject, - id: HandleId, - bp: *mut ObjectOpResult) +pub unsafe fn delete_property_by_id(cx: *mut jsapi::JSContext, + object: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, + bp: *mut jsapi::JS::ObjectOpResult) -> bool { - JS_DeletePropertyById(cx, object, id, bp) + jsapi::JS_DeletePropertyById(cx, object, id, bp) } -unsafe fn generic_call(cx: *mut JSContext, +unsafe fn generic_call(cx: *mut jsapi::JSContext, argc: libc::c_uint, - vp: *mut JSVal, + vp: *mut jsapi::JS::Value, is_lenient: bool, - call: unsafe extern fn(*const JSJitInfo, *mut JSContext, - HandleObject, *mut libc::c_void, u32, - *mut JSVal) + call: unsafe extern fn(*const jsapi::JSJitInfo, *mut jsapi::JSContext, + jsapi::JS::HandleObject, *mut libc::c_void, u32, + *mut jsapi::JS::Value) -> bool) -> bool { - let args = CallArgs::from_vp(vp, argc); + let args = jsapi::JS::CallArgs::from_vp(vp, argc); let thisobj = args.thisv(); if !thisobj.get().is_null_or_undefined() && !thisobj.get().is_object() { return false; @@ -421,12 +415,12 @@ unsafe fn generic_call(cx: *mut JSContext, let obj = if thisobj.get().is_object() { thisobj.get().to_object() } else { - GetGlobalForObjectCrossCompartment(JS_CALLEE(cx, vp).to_object_or_null()) + jsapi::js::GetGlobalForObjectCrossCompartment(args.calleev().to_object_or_null()) }; rooted!(in(cx) let obj = obj); - let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp)); - let proto_id = (*info).protoID; - let depth = (*info).depth; + let info = RUST_FUNCTION_VALUE_TO_JITINFO(args.calleev().get()); + let proto_id = (*info).__bindgen_anon_2.protoID; + let depth = (*info).__bindgen_anon_3.depth; let proto_check = |class: &'static DOMClass| { class.interface_chain[depth as usize] as u16 == proto_id }; @@ -434,7 +428,7 @@ unsafe fn generic_call(cx: *mut JSContext, Ok(val) => val, Err(()) => { if is_lenient { - debug_assert!(!JS_IsExceptionPending(cx)); + debug_assert!(!jsapi::JS_IsExceptionPending(cx)); *vp = UndefinedValue(); return true; } else { @@ -447,35 +441,35 @@ unsafe fn generic_call(cx: *mut JSContext, } /// Generic method of IDL interface. -pub unsafe extern "C" fn generic_method(cx: *mut JSContext, +pub unsafe extern "C" fn generic_method(cx: *mut jsapi::JSContext, argc: libc::c_uint, - vp: *mut JSVal) + vp: *mut jsapi::JS::Value) -> bool { generic_call(cx, argc, vp, false, CallJitMethodOp) } /// Generic getter of IDL interface. -pub unsafe extern "C" fn generic_getter(cx: *mut JSContext, +pub unsafe extern "C" fn generic_getter(cx: *mut jsapi::JSContext, argc: libc::c_uint, - vp: *mut JSVal) + vp: *mut jsapi::JS::Value) -> bool { generic_call(cx, argc, vp, false, CallJitGetterOp) } /// Generic lenient getter of IDL interface. -pub unsafe extern "C" fn generic_lenient_getter(cx: *mut JSContext, +pub unsafe extern "C" fn generic_lenient_getter(cx: *mut jsapi::JSContext, argc: libc::c_uint, - vp: *mut JSVal) + vp: *mut jsapi::JS::Value) -> bool { generic_call(cx, argc, vp, true, CallJitGetterOp) } -unsafe extern "C" fn call_setter(info: *const JSJitInfo, - cx: *mut JSContext, - handle: HandleObject, +unsafe extern "C" fn call_setter(info: *const jsapi::JSJitInfo, + cx: *mut jsapi::JSContext, + handle: jsapi::JS::HandleObject, this: *mut libc::c_void, argc: u32, - vp: *mut JSVal) + vp: *mut jsapi::JS::Value) -> bool { if !CallJitSetterOp(info, cx, handle, this, argc, vp) { return false; @@ -485,22 +479,22 @@ unsafe extern "C" fn call_setter(info: *const JSJitInfo, } /// Generic setter of IDL interface. -pub unsafe extern "C" fn generic_setter(cx: *mut JSContext, +pub unsafe extern "C" fn generic_setter(cx: *mut jsapi::JSContext, argc: libc::c_uint, - vp: *mut JSVal) + vp: *mut jsapi::JS::Value) -> bool { generic_call(cx, argc, vp, false, call_setter) } /// Generic lenient setter of IDL interface. -pub unsafe extern "C" fn generic_lenient_setter(cx: *mut JSContext, +pub unsafe extern "C" fn generic_lenient_setter(cx: *mut jsapi::JSContext, argc: libc::c_uint, - vp: *mut JSVal) + vp: *mut jsapi::JS::Value) -> bool { generic_call(cx, argc, vp, true, call_setter) } -unsafe extern "C" fn instance_class_has_proto_at_depth(clasp: *const js::jsapi::Class, +unsafe extern "C" fn instance_class_has_proto_at_depth(clasp: *const js::jsapi::js::Class, proto_id: u32, depth: u32) -> bool { @@ -510,7 +504,7 @@ unsafe extern "C" fn instance_class_has_proto_at_depth(clasp: *const js::jsapi:: } #[allow(missing_docs)] // FIXME -pub const DOM_CALLBACKS: DOMCallbacks = DOMCallbacks { +pub const DOM_CALLBACKS: jsapi::js::DOMCallbacks = jsapi::js::DOMCallbacks { instanceClassMatchesProto: Some(instance_class_has_proto_at_depth), }; @@ -534,3 +528,11 @@ impl AsCCharPtrPtr for [u8] { self as *const [u8] as *const c_char } } + +pub fn leak_as_static(t: T) -> &'static T { + let boxed = Box::new(t); + let ptr = Box::into_raw(boxed) as *const T; + unsafe { + ptr.as_ref().unwrap() + } +} diff --git a/components/script/dom/bindings/weakref.rs b/components/script/dom/bindings/weakref.rs index 7291405e5f65..8001ab2e7680 100644 --- a/components/script/dom/bindings/weakref.rs +++ b/components/script/dom/bindings/weakref.rs @@ -16,7 +16,7 @@ use dom::bindings::js::Root; use dom::bindings::reflector::DomObject; use dom::bindings::trace::JSTraceable; use heapsize::HeapSizeOf; -use js::jsapi::{JSTracer, JS_GetReservedSlot, JS_SetReservedSlot}; +use js::jsapi; use js::jsval::PrivateValue; use libc::c_void; use std::cell::{Cell, UnsafeCell}; @@ -51,7 +51,7 @@ pub trait WeakReferenceable: DomObject + Sized { fn downgrade(&self) -> WeakRef { unsafe { let object = self.reflector().get_jsobject().get(); - let mut ptr = JS_GetReservedSlot(object, + let mut ptr = jsapi::JS_GetReservedSlot(object, DOM_WEAK_SLOT) .to_private() as *mut WeakBox; if ptr.is_null() { @@ -60,7 +60,8 @@ pub trait WeakReferenceable: DomObject + Sized { count: Cell::new(1), value: Cell::new(Some(NonZero::new_unchecked(self))), }); - JS_SetReservedSlot(object, DOM_WEAK_SLOT, PrivateValue(ptr as *const c_void)); + let ptr = PrivateValue(ptr as *const c_void); + jsapi::JS_SetReservedSlot(object, DOM_WEAK_SLOT, &ptr as *const _); } let box_ = &*ptr; assert!(box_.value.get().is_some()); @@ -134,7 +135,7 @@ impl PartialEq for WeakRef { } unsafe impl JSTraceable for WeakRef { - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { // Do nothing. } } @@ -193,7 +194,7 @@ impl HeapSizeOf for MutableWeakRef { } unsafe impl JSTraceable for MutableWeakRef { - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { let ptr = self.cell.get(); let should_drop = match *ptr { Some(ref value) => !value.is_alive(), diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index 846b1ff666c5..4251aa33712d 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -33,8 +33,9 @@ use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::router::ROUTER; +use js; use js::conversions::ConversionResult; -use js::jsapi::{JSAutoCompartment, JSContext, JSObject}; +use js::jsapi; use js::jsval::{ObjectValue, UndefinedValue}; use script_thread::Runnable; use std::cell::Ref; @@ -95,18 +96,21 @@ struct BluetoothContext { } pub trait AsyncBluetoothListener { - fn handle_response(&self, result: BluetoothResponse, cx: *mut JSContext, promise: &Rc); + fn handle_response(&self, result: BluetoothResponse, cx: *mut jsapi::JSContext, promise: &Rc); } impl BluetoothContext { - #[allow(unrooted_must_root)] + #[allow(unrooted_must_root, unsafe_code)] fn response(&mut self, response: BluetoothResponseResult) { let promise = self.promise.take().expect("bt promise is missing").root(); let promise_cx = promise.global().get_cx(); // JSAutoCompartment needs to be manually made. // Otherwise, Servo will crash. - let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(promise_cx, + promise.reflector().get_jsobject().get()) + }; match response { Ok(response) => self.receiver.root().handle_response(response, promise_cx, &promise), // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice @@ -506,7 +510,7 @@ impl BluetoothMethods for Bluetooth { } impl AsyncBluetoothListener for Bluetooth { - fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut JSContext, promise: &Rc) { + fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut jsapi::JSContext, promise: &Rc) { match response { // https://webbluetoothcg.github.io/web-bluetooth/#request-bluetooth-devices // Step 11, 13 - 14. @@ -546,8 +550,8 @@ impl PermissionAlgorithm for Bluetooth { type Status = BluetoothPermissionResult; #[allow(unsafe_code)] - fn create_descriptor(cx: *mut JSContext, - permission_descriptor_obj: *mut JSObject) + fn create_descriptor(cx: *mut jsapi::JSContext, + permission_descriptor_obj: *mut jsapi::JSObject) -> Result { rooted!(in(cx) let mut property = UndefinedValue()); property.handle_mut().set(ObjectValue(permission_descriptor_obj)); @@ -561,7 +565,7 @@ impl PermissionAlgorithm for Bluetooth { } // https://webbluetoothcg.github.io/web-bluetooth/#query-the-bluetooth-permission - fn permission_query(cx: *mut JSContext, promise: &Rc, + fn permission_query(cx: *mut jsapi::JSContext, promise: &Rc, descriptor: &BluetoothPermissionDescriptor, status: &BluetoothPermissionResult) { // Step 1: We are not using the `global` variable. @@ -640,7 +644,7 @@ impl PermissionAlgorithm for Bluetooth { } // https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission - fn permission_request(cx: *mut JSContext, promise: &Rc, + fn permission_request(cx: *mut jsapi::JSContext, promise: &Rc, descriptor: &BluetoothPermissionDescriptor, status: &BluetoothPermissionResult) { // Step 1. diff --git a/components/script/dom/bluetoothdevice.rs b/components/script/dom/bluetoothdevice.rs index d3e742678bc2..21233b693da6 100644 --- a/components/script/dom/bluetoothdevice.rs +++ b/components/script/dom/bluetoothdevice.rs @@ -26,7 +26,7 @@ use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::{self, IpcSender}; -use js::jsapi::JSContext; +use js::jsapi; use std::cell::Cell; use std::collections::HashMap; use std::rc::Rc; @@ -267,7 +267,7 @@ impl BluetoothDeviceMethods for BluetoothDevice { } impl AsyncBluetoothListener for BluetoothDevice { - fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut JSContext, promise: &Rc) { + fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut jsapi::JSContext, promise: &Rc) { match response { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-unwatchadvertisements BluetoothResponse::WatchAdvertisements(_result) => { diff --git a/components/script/dom/bluetoothpermissionresult.rs b/components/script/dom/bluetoothpermissionresult.rs index da5de4bf5b19..710b9a7e5788 100644 --- a/components/script/dom/bluetoothpermissionresult.rs +++ b/components/script/dom/bluetoothpermissionresult.rs @@ -20,7 +20,7 @@ use dom::permissionstatus::PermissionStatus; use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; -use js::jsapi::JSContext; +use js::jsapi; use std::rc::Rc; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothpermissionresult @@ -83,7 +83,7 @@ impl BluetoothPermissionResultMethods for BluetoothPermissionResult { } impl AsyncBluetoothListener for BluetoothPermissionResult { - fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut JSContext, promise: &Rc) { + fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut jsapi::JSContext, promise: &Rc) { match response { // https://webbluetoothcg.github.io/web-bluetooth/#request-bluetooth-devices // Step 3, 11, 13 - 14. diff --git a/components/script/dom/bluetoothremotegattcharacteristic.rs b/components/script/dom/bluetoothremotegattcharacteristic.rs index d6a39c154e39..ea3fdf8a836c 100644 --- a/components/script/dom/bluetoothremotegattcharacteristic.rs +++ b/components/script/dom/bluetoothremotegattcharacteristic.rs @@ -27,7 +27,7 @@ use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; -use js::jsapi::JSContext; +use js::jsapi; use std::rc::Rc; // Maximum length of an attribute value. @@ -256,7 +256,7 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris } impl AsyncBluetoothListener for BluetoothRemoteGATTCharacteristic { - fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut JSContext, promise: &Rc) { + fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut jsapi::JSContext, promise: &Rc) { let device = self.Service().Device(); match response { // https://webbluetoothcg.github.io/web-bluetooth/#getgattchildren diff --git a/components/script/dom/bluetoothremotegattdescriptor.rs b/components/script/dom/bluetoothremotegattdescriptor.rs index c9e24c499bee..46b7cca19c45 100644 --- a/components/script/dom/bluetoothremotegattdescriptor.rs +++ b/components/script/dom/bluetoothremotegattdescriptor.rs @@ -21,7 +21,7 @@ use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; -use js::jsapi::JSContext; +use js::jsapi; use std::rc::Rc; // http://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattdescriptor @@ -147,7 +147,7 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { } impl AsyncBluetoothListener for BluetoothRemoteGATTDescriptor { - fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut JSContext, promise: &Rc) { + fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut jsapi::JSContext, promise: &Rc) { match response { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-readvalue BluetoothResponse::ReadValue(result) => { diff --git a/components/script/dom/bluetoothremotegattserver.rs b/components/script/dom/bluetoothremotegattserver.rs index 4a67e03e9847..66e9e8fc052c 100644 --- a/components/script/dom/bluetoothremotegattserver.rs +++ b/components/script/dom/bluetoothremotegattserver.rs @@ -17,7 +17,7 @@ use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; -use js::jsapi::JSContext; +use js::jsapi; use std::cell::Cell; use std::rc::Rc; @@ -120,7 +120,7 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { } impl AsyncBluetoothListener for BluetoothRemoteGATTServer { - fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut JSContext, promise: &Rc) { + fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut jsapi::JSContext, promise: &Rc) { match response { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect BluetoothResponse::GATTServerConnect(connected) => { diff --git a/components/script/dom/bluetoothremotegattservice.rs b/components/script/dom/bluetoothremotegattservice.rs index 347604df311e..68843f4a74da 100644 --- a/components/script/dom/bluetoothremotegattservice.rs +++ b/components/script/dom/bluetoothremotegattservice.rs @@ -18,7 +18,7 @@ use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom_struct::dom_struct; -use js::jsapi::JSContext; +use js::jsapi; use std::rc::Rc; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattservice @@ -129,7 +129,7 @@ impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService { } impl AsyncBluetoothListener for BluetoothRemoteGATTService { - fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut JSContext, promise: &Rc) { + fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut jsapi::JSContext, promise: &Rc) { let device = self.Device(); match response { // https://webbluetoothcg.github.io/web-bluetooth/#getgattchildren diff --git a/components/script/dom/crypto.rs b/components/script/dom/crypto.rs index 986e1b0ab09d..e37ec93df74c 100644 --- a/components/script/dom/crypto.rs +++ b/components/script/dom/crypto.rs @@ -11,8 +11,7 @@ use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use js::jsapi::{JSContext, JSObject}; -use js::jsapi::Type; +use js::jsapi; use servo_rand::{ServoRng, Rng}; unsafe_no_jsmanaged_fields!(ServoRng); @@ -42,9 +41,9 @@ impl CryptoMethods for Crypto { #[allow(unsafe_code)] // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues unsafe fn GetRandomValues(&self, - _cx: *mut JSContext, - input: *mut JSObject) - -> Fallible> { + _cx: *mut jsapi::JSContext, + input: *mut jsapi::JSObject) + -> Fallible> { assert!(!input.is_null()); typedarray!(in(_cx) let mut array_buffer_view: ArrayBufferView = input); let (array_type, mut data) = match array_buffer_view.as_mut() { @@ -69,15 +68,15 @@ impl CryptoMethods for Crypto { } } -fn is_integer_buffer(array_type: Type) -> bool { +fn is_integer_buffer(array_type: jsapi::js::Scalar::Type) -> bool { match array_type { - Type::Uint8 | - Type::Uint8Clamped | - Type::Int8 | - Type::Uint16 | - Type::Int16 | - Type::Uint32 | - Type::Int32 => true, + jsapi::js::Scalar::Type::Uint8 | + jsapi::js::Scalar::Type::Uint8Clamped | + jsapi::js::Scalar::Type::Int8 | + jsapi::js::Scalar::Type::Uint16 | + jsapi::js::Scalar::Type::Int16 | + jsapi::js::Scalar::Type::Uint32 | + jsapi::js::Scalar::Type::Int32 => true, _ => false, } } diff --git a/components/script/dom/customelementregistry.rs b/components/script/dom/customelementregistry.rs index de4d77533152..72e940ed40f6 100644 --- a/components/script/dom/customelementregistry.rs +++ b/components/script/dom/customelementregistry.rs @@ -26,11 +26,10 @@ use dom::promise::Promise; use dom::window::Window; use dom_struct::dom_struct; use html5ever::{LocalName, Namespace, Prefix}; +use js; use js::conversions::ToJSValConvertible; -use js::glue::UnwrapObject; -use js::jsapi::{Construct1, IsCallable, IsConstructor, HandleValueArray, HandleObject, MutableHandleValue}; -use js::jsapi::{Heap, JS_GetProperty, JS_SameValue, JSAutoCompartment, JSContext}; -use js::jsval::{JSVal, NullValue, ObjectValue, UndefinedValue}; +use js::jsapi; +use js::jsval::{NullValue, ObjectValue, UndefinedValue}; use microtask::Microtask; use script_thread::ScriptThread; use std::cell::Cell; @@ -91,7 +90,9 @@ impl CustomElementRegistry { }).cloned() } - pub fn lookup_definition_by_constructor(&self, constructor: HandleObject) -> Option> { + pub fn lookup_definition_by_constructor(&self, + constructor: jsapi::JS::HandleObject) + -> Option> { self.definitions.borrow().values().find(|definition| { definition.constructor.callback() == constructor.get() }).cloned() @@ -100,11 +101,14 @@ impl CustomElementRegistry { /// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define /// Steps 10.1, 10.2 #[allow(unsafe_code)] - fn check_prototype(&self, constructor: HandleObject, prototype: MutableHandleValue) -> ErrorResult { + fn check_prototype(&self, + constructor: jsapi::JS::HandleObject, + prototype: jsapi::JS::MutableHandleValue) + -> ErrorResult { let global_scope = self.window.upcast::(); unsafe { // Step 10.1 - if !JS_GetProperty(global_scope.get_cx(), + if !jsapi::JS_GetProperty(global_scope.get_cx(), constructor, b"prototype\0".as_ptr() as *const _, prototype) { @@ -121,7 +125,7 @@ impl CustomElementRegistry { /// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define /// Steps 10.3, 10.4 - fn get_callbacks(&self, prototype: HandleObject) -> Fallible { + fn get_callbacks(&self, prototype: jsapi::JS::HandleObject) -> Fallible { let cx = self.window.get_cx(); // Step 4 @@ -136,10 +140,10 @@ impl CustomElementRegistry { /// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define /// Step 10.6 #[allow(unsafe_code)] - fn get_observed_attributes(&self, constructor: HandleObject) -> Fallible> { + fn get_observed_attributes(&self, constructor: jsapi::JS::HandleObject) -> Fallible> { let cx = self.window.get_cx(); rooted!(in(cx) let mut observed_attributes = UndefinedValue()); - if unsafe { !JS_GetProperty(cx, + if unsafe { !jsapi::JS_GetProperty(cx, constructor, b"observedAttributes\0".as_ptr() as *const _, observed_attributes.handle_mut()) } { @@ -164,11 +168,11 @@ impl CustomElementRegistry { /// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define /// Step 10.4 #[allow(unsafe_code)] -fn get_callback(cx: *mut JSContext, prototype: HandleObject, name: &[u8]) -> Fallible>> { +fn get_callback(cx: *mut jsapi::JSContext, prototype: jsapi::JS::HandleObject, name: &[u8]) -> Fallible>> { rooted!(in(cx) let mut callback = UndefinedValue()); // Step 10.4.1 - if unsafe { !JS_GetProperty(cx, + if unsafe { !jsapi::JS_GetProperty(cx, prototype, name.as_ptr() as *const _, callback.handle_mut()) } { @@ -177,7 +181,7 @@ fn get_callback(cx: *mut JSContext, prototype: HandleObject, name: &[u8]) -> Fal // Step 10.4.2 if !callback.is_undefined() { - if !callback.is_object() || unsafe { !IsCallable(callback.to_object()) } { + if !callback.is_object() || unsafe { !jsapi::JS::IsCallable(callback.to_object()) } { return Err(Error::Type("Lifecycle callback is not callable".to_owned())); } Ok(Some(Function::new(cx, callback.to_object()))) @@ -196,14 +200,14 @@ impl CustomElementRegistryMethods for CustomElementRegistry { // Step 1 // We must unwrap the constructor as all wrappers are constructable if they are callable. - rooted!(in(cx) let unwrapped_constructor = unsafe { UnwrapObject(constructor.get(), 1) }); + rooted!(in(cx) let unwrapped_constructor = unsafe { js::glue::UnwrapObject(constructor.get(), 1) }); if unwrapped_constructor.is_null() { // We do not have permission to access the unwrapped constructor. return Err(Error::Security); } - if unsafe { !IsConstructor(unwrapped_constructor.get()) } { + if unsafe { !jsapi::JS::IsConstructor(unwrapped_constructor.get()) } { return Err(Error::Type("Second argument of CustomElementRegistry.define is not a constructor".to_owned())); } @@ -254,7 +258,9 @@ impl CustomElementRegistryMethods for CustomElementRegistry { // Steps 10.1 - 10.2 rooted!(in(cx) let mut prototype = UndefinedValue()); { - let _ac = JSAutoCompartment::new(cx, constructor.get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, constructor.get()) + }; if let Err(error) = self.check_prototype(constructor.handle(), prototype.handle_mut()) { self.element_definition_is_running.set(false); return Err(error); @@ -264,7 +270,9 @@ impl CustomElementRegistryMethods for CustomElementRegistry { // Steps 10.3 - 10.4 rooted!(in(cx) let proto_object = prototype.to_object()); let callbacks = { - let _ac = JSAutoCompartment::new(cx, proto_object.get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, proto_object.get()) + }; match self.get_callbacks(proto_object.handle()) { Ok(callbacks) => callbacks, Err(error) => { @@ -276,7 +284,9 @@ impl CustomElementRegistryMethods for CustomElementRegistry { // Step 10.5 - 10.6 let observed_attributes = if callbacks.attribute_changed_callback.is_some() { - let _ac = JSAutoCompartment::new(cx, constructor.get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, constructor.get()) + }; match self.get_observed_attributes(constructor.handle()) { Ok(attributes) => attributes, Err(error) => { @@ -326,7 +336,7 @@ impl CustomElementRegistryMethods for CustomElementRegistry { /// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-get #[allow(unsafe_code)] - unsafe fn Get(&self, cx: *mut JSContext, name: DOMString) -> JSVal { + unsafe fn Get(&self, cx: *mut jsapi::JSContext, name: DOMString) -> jsapi::JS::Value { match self.definitions.borrow().get(&LocalName::from(&*name)) { Some(definition) => { rooted!(in(cx) let mut constructor = UndefinedValue()); @@ -442,9 +452,11 @@ impl CustomElementDefinition { rooted!(in(cx) let mut element = ptr::null_mut()); { // Go into the constructor's compartment - let _ac = JSAutoCompartment::new(cx, self.constructor.callback()); - let args = HandleValueArray::new(); - if unsafe { !Construct1(cx, constructor.handle(), &args, element.handle_mut()) } { + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, self.constructor.callback()) + }; + let args = jsapi::JS::HandleValueArray::new(); + if unsafe { !jsapi::JS::Construct1(cx, constructor.handle(), &args, element.handle_mut()) } { return Err(Error::JSFailed); } } @@ -551,16 +563,18 @@ fn run_upgrade_constructor(constructor: &Rc, element: &Element) -> Err rooted!(in(cx) let mut construct_result = ptr::null_mut()); { // Go into the constructor's compartment - let _ac = JSAutoCompartment::new(cx, constructor.callback()); - let args = HandleValueArray::new(); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, constructor.callback()) + }; + let args = jsapi::JS::HandleValueArray::new(); // Step 7.1 - if unsafe { !Construct1(cx, constructor_val.handle(), &args, construct_result.handle_mut()) } { + if unsafe { !jsapi::JS::Construct1(cx, constructor_val.handle(), &args, construct_result.handle_mut()) } { return Err(Error::JSFailed); } // Step 7.2 let mut same = false; rooted!(in(cx) let construct_result_val = ObjectValue(construct_result.get())); - if unsafe { !JS_SameValue(cx, construct_result_val.handle(), element_val.handle(), &mut same) } { + if unsafe { !jsapi::JS_SameValue(cx, construct_result_val.handle(), element_val.handle(), &mut same) } { return Err(Error::JSFailed); } if !same { @@ -593,7 +607,7 @@ pub enum CustomElementReaction { Callback( #[ignore_heap_size_of = "Rc"] Rc, - Box<[Heap]> + Box<[js::heap::Heap]> ), } @@ -710,7 +724,7 @@ impl CustomElementReactionStack { CallbackReaction::Connected => (definition.callbacks.connected_callback.clone(), Vec::new()), CallbackReaction::Disconnected => (definition.callbacks.disconnected_callback.clone(), Vec::new()), CallbackReaction::Adopted(ref old_doc, ref new_doc) => { - let args = vec![Heap::default(), Heap::default()]; + let args = vec![js::heap::Heap::default(), js::heap::Heap::default()]; args[0].set(ObjectValue(old_doc.reflector().get_jsobject().get())); args[1].set(ObjectValue(new_doc.reflector().get_jsobject().get())); (definition.callbacks.adopted_callback.clone(), args) @@ -743,7 +757,7 @@ impl CustomElementReactionStack { unsafe { namespace.to_jsval(cx, namespace_value.handle_mut()); } } - let args = vec![Heap::default(), Heap::default(), Heap::default(), Heap::default()]; + let args = vec![js::heap::Heap::default(), js::heap::Heap::default(), js::heap::Heap::default(), js::heap::Heap::default()]; args[0].set(name_value.get()); args[1].set(old_value.get()); args[2].set(value.get()); diff --git a/components/script/dom/customevent.rs b/components/script/dom/customevent.rs index 7b522cde3ed0..3d27b2103630 100644 --- a/components/script/dom/customevent.rs +++ b/components/script/dom/customevent.rs @@ -14,8 +14,8 @@ use dom::bindings::trace::RootedTraceableBox; use dom::event::Event; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use js::jsapi::{Heap, HandleValue, JSContext}; -use js::jsval::JSVal; +use js; +use js::jsapi; use servo_atoms::Atom; // https://dom.spec.whatwg.org/#interface-customevent @@ -23,14 +23,14 @@ use servo_atoms::Atom; pub struct CustomEvent { event: Event, #[ignore_heap_size_of = "Defined in rust-mozjs"] - detail: Heap, + detail: js::heap::Heap, } impl CustomEvent { fn new_inherited() -> CustomEvent { CustomEvent { event: Event::new_inherited(), - detail: Heap::default(), + detail: js::heap::Heap::default(), } } @@ -43,7 +43,7 @@ impl CustomEvent { type_: Atom, bubbles: bool, cancelable: bool, - detail: HandleValue) + detail: jsapi::JS::HandleValue) -> Root { let ev = CustomEvent::new_uninitialized(global); ev.init_custom_event(type_, bubbles, cancelable, detail); @@ -66,7 +66,7 @@ impl CustomEvent { type_: Atom, can_bubble: bool, cancelable: bool, - detail: HandleValue) { + detail: jsapi::JS::HandleValue) { let event = self.upcast::(); if event.dispatching() { return; @@ -80,18 +80,18 @@ impl CustomEvent { impl CustomEventMethods for CustomEvent { #[allow(unsafe_code)] // https://dom.spec.whatwg.org/#dom-customevent-detail - unsafe fn Detail(&self, _cx: *mut JSContext) -> JSVal { + unsafe fn Detail(&self, _cx: *mut jsapi::JSContext) -> jsapi::JS::Value { self.detail.get() } #[allow(unsafe_code)] // https://dom.spec.whatwg.org/#dom-customevent-initcustomevent unsafe fn InitCustomEvent(&self, - _cx: *mut JSContext, + _cx: *mut jsapi::JSContext, type_: DOMString, can_bubble: bool, cancelable: bool, - detail: HandleValue) { + detail: jsapi::JS::HandleValue) { self.init_custom_event(Atom::from(type_), can_bubble, cancelable, detail) } diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index e6ec843e5713..81f074799954 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -23,8 +23,8 @@ use dom::workerglobalscope::WorkerGlobalScope; use dom_struct::dom_struct; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use ipc_channel::router::ROUTER; -use js::jsapi::{HandleValue, JS_SetInterruptCallback}; -use js::jsapi::{JSAutoCompartment, JSContext}; +use js; +use js::jsapi; use js::jsval::UndefinedValue; use js::rust::Runtime; use msg::constellation_msg::TopLevelBrowsingContextId; @@ -224,7 +224,7 @@ impl DedicatedWorkerGlobalScope { unsafe { // Handle interrupt requests - JS_SetInterruptCallback(scope.runtime(), Some(interrupt_callback)); + jsapi::JS_AddInterruptCallback(js::rust::Runtime::get(), Some(interrupt_callback)); } if scope.is_closing() { @@ -304,13 +304,16 @@ impl DedicatedWorkerGlobalScope { } } + #[allow(unsafe_code)] fn handle_script_event(&self, msg: WorkerScriptMsg) { match msg { WorkerScriptMsg::DOMMessage(data) => { let scope = self.upcast::(); let target = self.upcast(); - let _ac = JSAutoCompartment::new(scope.get_cx(), - scope.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(scope.get_cx(), + scope.reflector().get_jsobject().get()) + }; rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); data.read(scope.upcast(), message.handle_mut()); MessageEvent::dispatch_jsval(target, scope.upcast(), message.handle()); @@ -371,7 +374,7 @@ impl DedicatedWorkerGlobalScope { } #[allow(unsafe_code)] -unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { +unsafe extern "C" fn interrupt_callback(cx: *mut jsapi::JSContext) -> bool { let worker = Root::downcast::(GlobalScope::from_context(cx)) .expect("global is not a worker scope"); @@ -384,7 +387,7 @@ unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage - unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { + unsafe fn PostMessage(&self, cx: *mut jsapi::JSContext, message: jsapi::JS::HandleValue) -> ErrorResult { let data = StructuredCloneData::write(cx, message)?; let worker = self.worker.borrow().as_ref().unwrap().clone(); self.parent_sender diff --git a/components/script/dom/dissimilaroriginwindow.rs b/components/script/dom/dissimilaroriginwindow.rs index a0eeb7d4a6e5..becd251286e2 100644 --- a/components/script/dom/dissimilaroriginwindow.rs +++ b/components/script/dom/dissimilaroriginwindow.rs @@ -14,8 +14,8 @@ use dom::globalscope::GlobalScope; use dom::windowproxy::WindowProxy; use dom_struct::dom_struct; use ipc_channel::ipc; -use js::jsapi::{JSContext, HandleValue}; -use js::jsval::{JSVal, UndefinedValue}; +use js::jsapi; +use js::jsval::UndefinedValue; use msg::constellation_msg::PipelineId; use script_traits::ScriptMsg; use servo_url::ImmutableOrigin; @@ -130,7 +130,11 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-window-postmessage - unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue, origin: DOMString) -> ErrorResult { + unsafe fn PostMessage(&self, + cx: *mut jsapi::JSContext, + message: jsapi::JS::HandleValue, + origin: DOMString) + -> ErrorResult { // Step 3-5. let origin = match &origin[..] { "*" => None, @@ -155,14 +159,14 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-opener - unsafe fn Opener(&self, _: *mut JSContext) -> JSVal { + unsafe fn Opener(&self, _: *mut jsapi::JSContext) -> jsapi::JS::Value { // TODO: Implement x-origin opener UndefinedValue() } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-opener - unsafe fn SetOpener(&self, _: *mut JSContext, _: HandleValue) { + unsafe fn SetOpener(&self, _: *mut jsapi::JSContext, _: jsapi::JS::HandleValue) { // TODO: Implement x-origin opener } diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 1141565784ca..af3180d8e5ba 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -101,8 +101,7 @@ use html5ever::{LocalName, Namespace, QualName}; use hyper::header::{Header, SetCookie}; use hyper_serde::Serde; use ipc_channel::ipc::{self, IpcSender}; -use js::jsapi::{JSContext, JSObject, JSRuntime}; -use js::jsapi::JS_GetRuntime; +use js::jsapi; use msg::constellation_msg::{ALT, CONTROL, SHIFT, SUPER}; use msg::constellation_msg::{BrowsingContextId, Key, KeyModifiers, KeyState, TopLevelBrowsingContextId}; use net_traits::{FetchResponseMsg, IpcSend, ReferrerPolicy}; @@ -844,7 +843,7 @@ impl Document { #[allow(unsafe_code)] pub fn handle_mouse_event(&self, - js_runtime: *mut JSRuntime, + _js_runtime: *mut jsapi::JSRuntime, button: MouseButton, client_point: Point2D, mouse_event_type: MouseEventType) { @@ -858,9 +857,7 @@ impl Document { let node = match self.window.hit_test_query(client_point, false) { Some(node_address) => { debug!("node address is {:?}", node_address); - unsafe { - node::from_untrusted_node_address(js_runtime, node_address) - } + unsafe { node::from_untrusted_node_address(node_address) } }, None => return, }; @@ -1009,14 +1006,12 @@ impl Document { #[allow(unsafe_code)] pub fn handle_touchpad_pressure_event(&self, - js_runtime: *mut JSRuntime, + _js_runtime: *mut jsapi::JSRuntime, client_point: Point2D, pressure: f32, phase_now: TouchpadPressurePhase) { let node = match self.window.hit_test_query(client_point, false) { - Some(node_address) => unsafe { - node::from_untrusted_node_address(js_runtime, node_address) - }, + Some(node_address) => unsafe { node::from_untrusted_node_address(node_address) }, None => return }; @@ -1113,7 +1108,7 @@ impl Document { #[allow(unsafe_code)] pub fn handle_mouse_move_event(&self, - js_runtime: *mut JSRuntime, + _js_runtime: *mut jsapi::JSRuntime, client_point: Option>, prev_mouse_over_target: &MutNullableJS) { let client_point = match client_point { @@ -1127,7 +1122,7 @@ impl Document { }; let maybe_new_target = self.window.hit_test_query(client_point, true).and_then(|address| { - let node = unsafe { node::from_untrusted_node_address(js_runtime, address) }; + let node = unsafe { node::from_untrusted_node_address(address) }; node.inclusive_ancestors() .filter_map(Root::downcast::) .next() @@ -1211,7 +1206,7 @@ impl Document { #[allow(unsafe_code)] pub fn handle_touch_event(&self, - js_runtime: *mut JSRuntime, + _js_runtime: *mut jsapi::JSRuntime, event_type: TouchEventType, touch_id: TouchId, point: Point2D) @@ -1226,9 +1221,7 @@ impl Document { }; let node = match self.window.hit_test_query(point, false) { - Some(node_address) => unsafe { - node::from_untrusted_node_address(js_runtime, node_address) - }, + Some(node_address) => unsafe { node::from_untrusted_node_address(node_address) }, None => return TouchEventResult::Processed(false), }; let el = match node.downcast::() { @@ -3512,7 +3505,7 @@ impl DocumentMethods for Document { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter - unsafe fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString) -> Option> { + unsafe fn NamedGetter(&self, _cx: *mut jsapi::JSContext, name: DOMString) -> Option> { #[derive(HeapSizeOf, JSTraceable)] struct NamedElementFilter { name: Atom, @@ -3640,11 +3633,7 @@ impl DocumentMethods for Document { match self.window.hit_test_query(*point, false) { Some(untrusted_node_address) => { - let js_runtime = unsafe { JS_GetRuntime(window.get_cx()) }; - - let node = unsafe { - node::from_untrusted_node_address(js_runtime, untrusted_node_address) - }; + let node = unsafe { node::from_untrusted_node_address(untrusted_node_address) }; let parent_node = node.GetParentNode().unwrap(); let element_ref = node.downcast::().unwrap_or_else(|| { parent_node.downcast::().unwrap() @@ -3674,16 +3663,12 @@ impl DocumentMethods for Document { return vec!(); } - let js_runtime = unsafe { JS_GetRuntime(window.get_cx()) }; - // Step 1 and Step 3 let mut elements: Vec> = self.nodes_from_point(point).iter() .flat_map(|&untrusted_node_address| { - let node = unsafe { - node::from_untrusted_node_address(js_runtime, untrusted_node_address) - }; + let node = unsafe { node::from_untrusted_node_address(untrusted_node_address) }; Root::downcast::(node) - }).collect(); + }).collect(); // Step 4 if let Some(root_element) = self.GetDocumentElement() { diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index 11df4f6bd42a..f6062334a9ef 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -82,8 +82,8 @@ use html5ever::serialize; use html5ever::serialize::SerializeOpts; use html5ever::serialize::TraversalScope; use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode}; -use js::jsapi::{HandleValue, Heap, JSAutoCompartment}; -use js::jsval::JSVal; +use js; +use js::jsapi; use net_traits::request::CorsSettings; use ref_filter_map::ref_filter_map; use script_layout_interface::message::ReflowQueryType; @@ -317,7 +317,7 @@ impl Element { (*self.custom_element_definition.borrow()).clone() } - pub fn push_callback_reaction(&self, function: Rc, args: Box<[Heap]>) { + pub fn push_callback_reaction(&self, function: Rc, args: Box<[js::heap::Heap]>) { self.custom_element_reaction_queue.borrow_mut().push(CustomElementReaction::Callback(function, args)); } @@ -3032,7 +3032,7 @@ impl ElementPerformFullscreenEnter { impl Runnable for ElementPerformFullscreenEnter { fn name(&self) -> &'static str { "ElementPerformFullscreenEnter" } - #[allow(unrooted_must_root)] + #[allow(unrooted_must_root, unsafe_code)] fn handler(self: Box) { let element = self.element.root(); let document = document_from_node(element.r()); @@ -3043,7 +3043,10 @@ impl Runnable for ElementPerformFullscreenEnter { // Otherwise, Servo will crash. let promise = self.promise.root(); let promise_cx = promise.global().get_cx(); - let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(promise_cx, + promise.reflector().get_jsobject().get()) + }; document.upcast::().fire_event(atom!("fullscreenerror")); promise.reject_error(promise.global().get_cx(), Error::Type(String::from("fullscreen is not connected"))); return @@ -3065,8 +3068,11 @@ impl Runnable for ElementPerformFullscreenEnter { // Otherwise, Servo will crash. let promise = self.promise.root(); let promise_cx = promise.global().get_cx(); - let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get()); - promise.resolve(promise.global().get_cx(), HandleValue::undefined()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(promise_cx, + promise.reflector().get_jsobject().get()) + }; + promise.resolve(promise.global().get_cx(), jsapi::JS::HandleValue::undefined()); } } @@ -3087,7 +3093,7 @@ impl ElementPerformFullscreenExit { impl Runnable for ElementPerformFullscreenExit { fn name(&self) -> &'static str { "ElementPerformFullscreenExit" } - #[allow(unrooted_must_root)] + #[allow(unrooted_must_root, unsafe_code)] fn handler(self: Box) { let element = self.element.root(); let document = document_from_node(element.r()); @@ -3109,8 +3115,11 @@ impl Runnable for ElementPerformFullscreenExit { // JSAutoCompartment needs to be manually made. // Otherwise, Servo will crash. let promise_cx = promise.global().get_cx(); - let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get()); - promise.resolve(promise.global().get_cx(), HandleValue::undefined()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(promise_cx, + promise.reflector().get_jsobject().get()) + }; + promise.resolve(promise.global().get_cx(), jsapi::JS::HandleValue::undefined()); } } diff --git a/components/script/dom/errorevent.rs b/components/script/dom/errorevent.rs index 170a979d9969..77d51bbfe630 100644 --- a/components/script/dom/errorevent.rs +++ b/components/script/dom/errorevent.rs @@ -15,8 +15,8 @@ use dom::bindings::trace::RootedTraceableBox; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use js::jsapi::{Heap, HandleValue, JSContext}; -use js::jsval::JSVal; +use js; +use js::jsapi; use servo_atoms::Atom; use std::cell::Cell; @@ -28,7 +28,7 @@ pub struct ErrorEvent { lineno: Cell, colno: Cell, #[ignore_heap_size_of = "Defined in rust-mozjs"] - error: Heap, + error: js::heap::Heap, } impl ErrorEvent { @@ -39,7 +39,7 @@ impl ErrorEvent { filename: DOMRefCell::new(DOMString::new()), lineno: Cell::new(0), colno: Cell::new(0), - error: Heap::default() + error: js::heap::Heap::default() } } @@ -57,7 +57,7 @@ impl ErrorEvent { filename: DOMString, lineno: u32, colno: u32, - error: HandleValue) -> Root { + error: jsapi::JS::HandleValue) -> Root { let ev = ErrorEvent::new_uninitialized(global); { let event = ev.upcast::(); @@ -132,7 +132,7 @@ impl ErrorEventMethods for ErrorEvent { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-errorevent-error - unsafe fn Error(&self, _cx: *mut JSContext) -> JSVal { + unsafe fn Error(&self, _cx: *mut jsapi::JSContext) -> jsapi::JS::Value { self.error.get() } diff --git a/components/script/dom/eventsource.rs b/components/script/dom/eventsource.rs index 22a49eadd810..8dbdc58e8ddf 100644 --- a/components/script/dom/eventsource.rs +++ b/components/script/dom/eventsource.rs @@ -20,8 +20,8 @@ use euclid::Length; use hyper::header::{Accept, qitem}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; +use js; use js::conversions::ToJSValConvertible; -use js::jsapi::JSAutoCompartment; use js::jsval::UndefinedValue; use mime::{Mime, TopLevel, SubLevel}; use net_traits::{CoreResourceMsg, FetchMetadata, FetchResponseMsg, FetchResponseListener, NetworkError}; @@ -175,8 +175,10 @@ impl EventSourceContext { }; // Steps 4-5 let event = { - let _ac = JSAutoCompartment::new(event_source.global().get_cx(), - event_source.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(event_source.global().get_cx(), + event_source.reflector().get_jsobject().get()) + }; rooted!(in(event_source.global().get_cx()) let mut data = UndefinedValue()); unsafe { self.data.to_jsval(event_source.global().get_cx(), data.handle_mut()) }; MessageEvent::new(&*event_source.global(), type_, false, false, data.handle(), diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index eaab9f79d9b8..f24cb3b32478 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -29,7 +29,8 @@ use dom::window::Window; use dom_struct::dom_struct; use fnv::FnvHasher; use heapsize::HeapSizeOf; -use js::jsapi::{CompileFunction, JS_GetFunctionObject, JSAutoCompartment}; +use js; +use js::jsapi; use js::rust::{AutoObjectVectorWrapper, CompileOptionsWrapper}; use libc::{c_char, size_t}; use servo_atoms::Atom; @@ -415,23 +416,25 @@ impl EventTarget { let scopechain = AutoObjectVectorWrapper::new(cx); - let _ac = JSAutoCompartment::new(cx, window.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, window.reflector().get_jsobject().get()) + }; rooted!(in(cx) let mut handler = ptr::null_mut()); let rv = unsafe { - CompileFunction(cx, - scopechain.ptr, - options.ptr, - name.as_ptr(), - args.len() as u32, - args.as_ptr(), - body.as_ptr(), - body.len() as size_t, - handler.handle_mut()) + jsapi::JS::CompileFunction(cx, + scopechain.ptr, + options.ptr, + name.as_ptr(), + args.len() as u32, + args.as_ptr(), + body.as_ptr(), + body.len() as size_t, + handler.handle_mut()) }; if !rv || handler.get().is_null() { // Step 1.8.2 unsafe { - let _ac = JSAutoCompartment::new(cx, self.reflector().get_jsobject().get()); + let _ac = js::ac::AutoCompartment::with_obj(cx, self.reflector().get_jsobject().get()); // FIXME(#13152): dispatch error event. report_pending_exception(cx, false); } @@ -440,7 +443,7 @@ impl EventTarget { } // TODO step 1.11-13 - let funobj = unsafe { JS_GetFunctionObject(handler.get()) }; + let funobj = unsafe { jsapi::JS_GetFunctionObject(handler.get()) }; assert!(!funobj.is_null()); // Step 1.14 if is_error { diff --git a/components/script/dom/extendableevent.rs b/components/script/dom/extendableevent.rs index 8cc88706fb1b..d00a882e97c8 100644 --- a/components/script/dom/extendableevent.rs +++ b/components/script/dom/extendableevent.rs @@ -12,7 +12,7 @@ use dom::bindings::str::DOMString; use dom::event::Event; use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use dom_struct::dom_struct; -use js::jsapi::{HandleValue, JSContext}; +use js::jsapi; use servo_atoms::Atom; // https://w3c.github.io/ServiceWorker/#extendable-event @@ -52,7 +52,7 @@ impl ExtendableEvent { } // https://w3c.github.io/ServiceWorker/#wait-until-method - pub fn WaitUntil(&self, _cx: *mut JSContext, _val: HandleValue) -> ErrorResult { + pub fn WaitUntil(&self, _cx: *mut jsapi::JSContext, _val: jsapi::JS::HandleValue) -> ErrorResult { // Step 1 if !self.extensions_allowed { return Err(Error::InvalidState); diff --git a/components/script/dom/extendablemessageevent.rs b/components/script/dom/extendablemessageevent.rs index 6c72655ec4c1..c86358df4532 100644 --- a/components/script/dom/extendablemessageevent.rs +++ b/components/script/dom/extendablemessageevent.rs @@ -16,14 +16,14 @@ use dom::extendableevent::ExtendableEvent; use dom::globalscope::GlobalScope; use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use dom_struct::dom_struct; -use js::jsapi::{HandleValue, Heap, JSContext}; -use js::jsval::JSVal; +use js; +use js::jsapi; use servo_atoms::Atom; #[dom_struct] pub struct ExtendableMessageEvent { event: ExtendableEvent, - data: Heap, + data: js::heap::Heap, origin: DOMString, lastEventId: DOMString, } @@ -31,11 +31,11 @@ pub struct ExtendableMessageEvent { impl ExtendableMessageEvent { pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, - data: HandleValue, origin: DOMString, lastEventId: DOMString) + data: jsapi::JS::HandleValue, origin: DOMString, lastEventId: DOMString) -> Root { let ev = box ExtendableMessageEvent { event: ExtendableEvent::new_inherited(), - data: Heap::default(), + data: js::heap::Heap::default(), origin: origin, lastEventId: lastEventId, }; @@ -68,7 +68,7 @@ impl ExtendableMessageEvent { impl ExtendableMessageEvent { pub fn dispatch_jsval(target: &EventTarget, scope: &GlobalScope, - message: HandleValue) { + message: jsapi::JS::HandleValue) { let Extendablemessageevent = ExtendableMessageEvent::new( scope, atom!("message"), false, false, message, DOMString::new(), DOMString::new()); @@ -79,7 +79,7 @@ impl ExtendableMessageEvent { impl ExtendableMessageEventMethods for ExtendableMessageEvent { #[allow(unsafe_code)] // https://w3c.github.io/ServiceWorker/#extendablemessage-event-data-attribute - unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal { + unsafe fn Data(&self, _cx: *mut jsapi::JSContext) -> jsapi::JS::Value { self.data.get() } diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index 4fd9013047cf..826fbe3e6859 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -25,10 +25,10 @@ use encoding::all::UTF_8; use encoding::label::encoding_from_whatwg_label; use encoding::types::{DecoderTrap, EncodingRef}; use hyper::mime::{Attr, Mime}; -use js::jsapi::Heap; -use js::jsapi::JSAutoCompartment; -use js::jsapi::JSContext; -use js::jsval::{self, JSVal}; +use js; +use js::heap::Heap; +use js::jsapi; +use js::jsval; use js::typedarray::{ArrayBuffer, CreateWith}; use script_thread::RunnableWrapper; use servo_atoms::Atom; @@ -79,7 +79,7 @@ pub enum FileReaderReadyState { #[derive(HeapSizeOf, JSTraceable)] pub enum FileReaderResult { - ArrayBuffer(Heap), + ArrayBuffer(Heap), String(DOMString), } @@ -198,7 +198,10 @@ impl FileReader { FileReaderFunction::ReadAsText => FileReader::perform_readastext(&fr.result, data, &blob_contents), FileReaderFunction::ReadAsArrayBuffer => { - let _ac = JSAutoCompartment::new(fr.global().get_cx(), *fr.reflector().get_jsobject()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(fr.global().get_cx(), + *fr.reflector().get_jsobject()) + }; FileReader::perform_readasarraybuffer(&fr.result, fr.global().get_cx(), data, &blob_contents) }, }; @@ -261,7 +264,7 @@ impl FileReader { // https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer #[allow(unsafe_code)] fn perform_readasarraybuffer(result: &DOMRefCell>, - cx: *mut JSContext, _: ReadMetaData, bytes: &[u8]) { + cx: *mut jsapi::JSContext, _: ReadMetaData, bytes: &[u8]) { unsafe { rooted!(in(cx) let mut array_buffer = ptr::null_mut()); assert!(ArrayBuffer::create(cx, CreateWith::Slice(bytes), array_buffer.handle_mut()).is_ok()); @@ -334,12 +337,12 @@ impl FileReaderMethods for FileReader { #[allow(unsafe_code)] // https://w3c.github.io/FileAPI/#dfn-result - unsafe fn GetResult(&self, _: *mut JSContext) -> Option { + unsafe fn GetResult(&self, _: *mut jsapi::JSContext) -> Option { self.result.borrow().as_ref().map(|r| match *r { FileReaderResult::String(ref string) => StringOrObject::String(string.clone()), FileReaderResult::ArrayBuffer(ref arr_buffer) => { - StringOrObject::Object(Heap::new((*arr_buffer.ptr.get()).to_object())) + StringOrObject::Object(Heap::new((arr_buffer.get()).to_object())) } }) } diff --git a/components/script/dom/gamepad.rs b/components/script/dom/gamepad.rs index bee219bbbcdc..2445dac7b6d0 100644 --- a/components/script/dom/gamepad.rs +++ b/components/script/dom/gamepad.rs @@ -17,7 +17,8 @@ use dom::gamepadevent::{GamepadEvent, GamepadEventType}; use dom::globalscope::GlobalScope; use dom::vrpose::VRPose; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext, JSObject}; +use js; +use js::jsapi; use js::typedarray::{Float64Array, CreateWith}; use std::cell::Cell; use std::ptr; @@ -32,7 +33,7 @@ pub struct Gamepad { connected: Cell, timestamp: Cell, mapping_type: String, - axes: Heap<*mut JSObject>, + axes: js::heap::Heap<*mut jsapi::JSObject>, buttons: JS, pose: Option>, #[ignore_heap_size_of = "Defined in rust-webvr"] @@ -59,7 +60,7 @@ impl Gamepad { connected: Cell::new(connected), timestamp: Cell::new(timestamp), mapping_type: mapping_type, - axes: Heap::default(), + axes: js::heap::Heap::default(), buttons: JS::from_ref(buttons), pose: pose.map(JS::from_ref), hand: hand, @@ -127,7 +128,7 @@ impl GamepadMethods for Gamepad { #[allow(unsafe_code)] // https://w3c.github.io/gamepad/#dom-gamepad-axes - unsafe fn Axes(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> { + unsafe fn Axes(&self, _cx: *mut jsapi::JSContext) -> NonZero<*mut jsapi::JSObject> { NonZero::new_unchecked(self.axes.get()) } diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index b90e4204c2e0..3ad1d78b7efa 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -22,12 +22,10 @@ use dom::workerglobalscope::WorkerGlobalScope; use dom::workletglobalscope::WorkletGlobalScope; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; -use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; +use js; use js::glue::{IsWrapper, UnwrapObject}; -use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; -use js::jsapi::{HandleValue, Evaluate2, JSAutoCompartment, JSContext}; -use js::jsapi::{JSObject, JS_GetContext}; -use js::jsapi::{JS_GetObjectRuntime, MutableHandleValue}; +use js::jsapi; +use js::jsapi::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; use js::panic::maybe_resume_unwind; use js::rust::{CompileOptionsWrapper, Runtime, get_object_class}; use libc; @@ -138,23 +136,23 @@ impl GlobalScope { /// Returns the global scope of the realm that the given JS object was created in. #[allow(unsafe_code)] - pub unsafe fn from_object(obj: *mut JSObject) -> Root { + pub unsafe fn from_object(obj: *mut jsapi::JSObject) -> Root { assert!(!obj.is_null()); - let global = GetGlobalForObjectCrossCompartment(obj); + let global = jsapi::js::GetGlobalForObjectCrossCompartment(obj); global_scope_from_global(global) } - /// Returns the global scope for the given JSContext + /// Returns the global scope for the given jsapi::JSContext #[allow(unsafe_code)] - pub unsafe fn from_context(cx: *mut JSContext) -> Root { - let global = CurrentGlobalOrNull(cx); + pub unsafe fn from_context(cx: *mut jsapi::JSContext) -> Root { + let global = jsapi::JS::CurrentGlobalOrNull(cx); global_scope_from_global(global) } /// Returns the global object of the realm that the given JS object /// was created in, after unwrapping any wrappers. #[allow(unsafe_code)] - pub unsafe fn from_object_maybe_wrapped(mut obj: *mut JSObject) -> Root { + pub unsafe fn from_object_maybe_wrapped(mut obj: *mut jsapi::JSObject) -> Root { if IsWrapper(obj) { obj = UnwrapObject(obj, /* stopAtWindowProxy = */ 0); assert!(!obj.is_null()); @@ -162,16 +160,8 @@ impl GlobalScope { GlobalScope::from_object(obj) } - #[allow(unsafe_code)] - pub fn get_cx(&self) -> *mut JSContext { - unsafe { - let runtime = JS_GetObjectRuntime( - self.reflector().get_jsobject().get()); - assert!(!runtime.is_null()); - let context = JS_GetContext(runtime); - assert!(!context.is_null()); - context - } + pub fn get_cx(&self) -> *mut jsapi::JSContext { + js::rust::Runtime::get() } pub fn crypto(&self) -> Root { @@ -288,7 +278,7 @@ impl GlobalScope { } /// https://html.spec.whatwg.org/multipage/#report-the-error - pub fn report_an_error(&self, error_info: ErrorInfo, value: HandleValue) { + pub fn report_an_error(&self, error_info: ErrorInfo, value: jsapi::JS::HandleValue) { // Step 1. if self.in_error_reporting_mode.get() { return; @@ -357,15 +347,21 @@ impl GlobalScope { } /// Evaluate JS code on this global scope. - pub fn evaluate_js_on_global_with_result( - &self, code: &str, rval: MutableHandleValue) -> bool { + pub fn evaluate_js_on_global_with_result(&self, + code: &str, + rval: jsapi::JS::MutableHandleValue) + -> bool { self.evaluate_script_on_global_with_result(code, "", rval, 1) } /// Evaluate a JS script on this global scope. #[allow(unsafe_code)] - pub fn evaluate_script_on_global_with_result( - &self, code: &str, filename: &str, rval: MutableHandleValue, line_number: u32) -> bool { + pub fn evaluate_script_on_global_with_result(&self, + code: &str, + filename: &str, + rval: jsapi::JS::MutableHandleValue, + line_number: u32) + -> bool { let metadata = time::TimerMetadata { url: if filename.is_empty() { self.get_url().as_str().into() @@ -385,20 +381,22 @@ impl GlobalScope { let code: Vec = code.encode_utf16().collect(); let filename = CString::new(filename).unwrap(); - let _ac = JSAutoCompartment::new(cx, globalhandle.get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, globalhandle.get()) + }; let _aes = AutoEntryScript::new(self); let options = CompileOptionsWrapper::new(cx, filename.as_ptr(), line_number); - - debug!("evaluating JS string"); let result = unsafe { - Evaluate2(cx, options.ptr, code.as_ptr(), - code.len() as libc::size_t, - rval) + jsapi::JS::Evaluate2(cx, options.ptr, code.as_ptr(), + code.len() as libc::size_t, + rval) }; if !result { debug!("error evaluating JS string"); - unsafe { report_pending_exception(cx, true) }; + unsafe { + report_pending_exception(cx, true); + } } maybe_resume_unwind(); @@ -420,7 +418,7 @@ impl GlobalScope { pub fn set_timeout_or_interval( &self, callback: TimerCallback, - arguments: Vec, + arguments: Vec, timeout: i32, is_interval: IsInterval) -> i32 { @@ -547,7 +545,7 @@ impl GlobalScope { unsafe { let cx = Runtime::get(); assert!(!cx.is_null()); - let global = CurrentGlobalOrNull(cx); + let global = jsapi::JS::CurrentGlobalOrNull(cx); if global.is_null() { None } else { @@ -577,7 +575,7 @@ fn timestamp_in_ms(time: Timespec) -> u64 { /// Returns the Rust global scope from a JS global object. #[allow(unsafe_code)] -unsafe fn global_scope_from_global(global: *mut JSObject) -> Root { +unsafe fn global_scope_from_global(global: *mut jsapi::JSObject) -> Root { assert!(!global.is_null()); let clasp = get_object_class(global); assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0); diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index 4491c22487a2..ba6ed1bbd1e4 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -32,7 +32,7 @@ use image::ColorType; use image::png::PNGEncoder; use ipc_channel::ipc; use js::error::throw_type_error; -use js::jsapi::{HandleValue, JSContext}; +use js::jsapi; use offscreen_gl_context::GLContextAttributes; use script_layout_interface::{HTMLCanvasData, HTMLCanvasDataSource}; use std::iter::repeat; @@ -167,8 +167,8 @@ impl HTMLCanvasElement { #[allow(unsafe_code)] pub fn get_or_init_webgl_context(&self, - cx: *mut JSContext, - attrs: Option) -> Option> { + cx: *mut jsapi::JSContext, + attrs: Option) -> Option> { if self.context.borrow().is_none() { let window = window_from_node(self); let size = self.get_size(); @@ -255,9 +255,9 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext unsafe fn GetContext(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, id: DOMString, - attributes: Vec) + attributes: Vec) -> Option { match &*id { "2d" => { @@ -275,9 +275,9 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl unsafe fn ToDataURL(&self, - _context: *mut JSContext, + _context: *mut jsapi::JSContext, _mime_type: Option, - _arguments: Vec) -> Fallible { + _arguments: Vec) -> Fallible { // Step 1. if let Some(CanvasContext::Context2d(ref context)) = *self.context.borrow() { if !context.origin_is_clean() { diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 4585836f7a4f..d6a8dbb50ec7 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -38,7 +38,8 @@ use dom::windowproxy::WindowProxy; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use ipc_channel::ipc; -use js::jsapi::{JSAutoCompartment, JSContext, MutableHandleValue}; +use js; +use js::jsapi; use js::jsval::{NullValue, UndefinedValue}; use msg::constellation_msg::{FrameType, BrowsingContextId, PipelineId, TopLevelBrowsingContextId, TraversalDirection}; use net_traits::response::HttpsState; @@ -445,7 +446,9 @@ pub fn build_mozbrowser_custom_event(window: &Window, event: MozBrowserEvent) -> // See https://developer.mozilla.org/en-US/docs/Web/API/Using_the_Browser_API // for a list of mozbrowser events. let cx = window.get_cx(); - let _ac = JSAutoCompartment::new(cx, window.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, window.reflector().get_jsobject().get()) + }; rooted!(in(cx) let mut detail = UndefinedValue()); let event_name = Atom::from(event.name()); unsafe { build_mozbrowser_event_detail(event, cx, detail.handle_mut()); } @@ -458,8 +461,8 @@ pub fn build_mozbrowser_custom_event(window: &Window, event: MozBrowserEvent) -> #[allow(unsafe_code)] unsafe fn build_mozbrowser_event_detail(event: MozBrowserEvent, - cx: *mut JSContext, - rval: MutableHandleValue) { + cx: *mut jsapi::JSContext, + rval: jsapi::JS::MutableHandleValue) { match event { MozBrowserEvent::AsyncScroll | MozBrowserEvent::Close | MozBrowserEvent::ContextMenu | MozBrowserEvent::LoadEnd | MozBrowserEvent::LoadStart | diff --git a/components/script/dom/imagedata.rs b/components/script/dom/imagedata.rs index 30e0e3d6dae5..073617cef9e1 100644 --- a/components/script/dom/imagedata.rs +++ b/components/script/dom/imagedata.rs @@ -11,7 +11,8 @@ use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use euclid::Size2D; -use js::jsapi::{Heap, JSContext, JSObject}; +use js; +use js::jsapi; use js::rust::Runtime; use js::typedarray::{Uint8ClampedArray, CreateWith}; use std::default::Default; @@ -23,7 +24,7 @@ pub struct ImageData { reflector_: Reflector, width: u32, height: u32, - data: Heap<*mut JSObject>, + data: js::heap::Heap<*mut jsapi::JSObject>, } impl ImageData { @@ -53,7 +54,7 @@ impl ImageData { unsafe fn new_with_jsobject(global: &GlobalScope, width: u32, mut opt_height: Option, - opt_jsobject: Option<*mut JSObject>) + opt_jsobject: Option<*mut jsapi::JSObject>) -> Fallible> { assert!(opt_jsobject.is_some() || opt_height.is_some()); @@ -95,7 +96,7 @@ impl ImageData { reflector_: Reflector::new(), width: width, height: height, - data: Heap::default(), + data: js::heap::Heap::default(), }; if let Some(jsobject) = opt_jsobject { @@ -120,9 +121,9 @@ impl ImageData { // https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-4 #[allow(unsafe_code)] #[allow(unused_variables)] - pub unsafe fn Constructor_(cx: *mut JSContext, + pub unsafe fn Constructor_(cx: *mut jsapi::JSContext, global: &GlobalScope, - jsobject: *mut JSObject, + jsobject: *mut jsapi::JSObject, width: u32, opt_height: Option) -> Fallible> { @@ -159,7 +160,7 @@ impl ImageDataMethods for ImageData { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-imagedata-data - unsafe fn Data(&self, _: *mut JSContext) -> NonZero<*mut JSObject> { + unsafe fn Data(&self, _: *mut jsapi::JSContext) -> NonZero<*mut jsapi::JSObject> { assert!(!self.data.get().is_null()); NonZero::new_unchecked(self.data.get()) } diff --git a/components/script/dom/mediaquerylist.rs b/components/script/dom/mediaquerylist.rs index 199241b14dd2..389e74f1c557 100644 --- a/components/script/dom/mediaquerylist.rs +++ b/components/script/dom/mediaquerylist.rs @@ -19,7 +19,7 @@ use dom::event::Event; use dom::eventtarget::EventTarget; use dom::mediaquerylistevent::MediaQueryListEvent; use dom_struct::dom_struct; -use js::jsapi::JSTracer; +use js::jsapi; use std::cell::Cell; use std::rc::Rc; use style::media_queries::MediaList; @@ -152,7 +152,7 @@ impl WeakMediaQueryListVec { #[allow(unsafe_code)] unsafe impl JSTraceable for WeakMediaQueryListVec { - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { self.cell.borrow_mut().retain_alive() } } diff --git a/components/script/dom/messageevent.rs b/components/script/dom/messageevent.rs index 4b49840b9c4e..3ccd9f4d4f59 100644 --- a/components/script/dom/messageevent.rs +++ b/components/script/dom/messageevent.rs @@ -15,14 +15,14 @@ use dom::event::Event; use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use js::jsapi::{HandleValue, Heap, JSContext}; -use js::jsval::JSVal; +use js; +use js::jsapi; use servo_atoms::Atom; #[dom_struct] pub struct MessageEvent { event: Event, - data: Heap, + data: js::heap::Heap, origin: DOMString, lastEventId: DOMString, } @@ -30,18 +30,18 @@ pub struct MessageEvent { impl MessageEvent { pub fn new_uninitialized(global: &GlobalScope) -> Root { MessageEvent::new_initialized(global, - HandleValue::undefined(), + jsapi::JS::HandleValue::undefined(), DOMString::new(), DOMString::new()) } pub fn new_initialized(global: &GlobalScope, - data: HandleValue, + data: jsapi::JS::HandleValue, origin: DOMString, lastEventId: DOMString) -> Root { let ev = box MessageEvent { event: Event::new_inherited(), - data: Heap::default(), + data: js::heap::Heap::default(), origin: origin, lastEventId: lastEventId, }; @@ -53,7 +53,7 @@ impl MessageEvent { pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, - data: HandleValue, origin: DOMString, lastEventId: DOMString) + data: jsapi::JS::HandleValue, origin: DOMString, lastEventId: DOMString) -> Root { let ev = MessageEvent::new_initialized(global, data, origin, lastEventId); { @@ -81,7 +81,7 @@ impl MessageEvent { impl MessageEvent { pub fn dispatch_jsval(target: &EventTarget, scope: &GlobalScope, - message: HandleValue) { + message: jsapi::JS::HandleValue) { let messageevent = MessageEvent::new( scope, atom!("message"), @@ -97,7 +97,7 @@ impl MessageEvent { impl MessageEventMethods for MessageEvent { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-messageevent-data - unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal { + unsafe fn Data(&self, _cx: *mut jsapi::JSContext) -> jsapi::JS::Value { self.data.get() } diff --git a/components/script/dom/mod.rs b/components/script/dom/mod.rs index db065419b2b0..baba28e59aae 100644 --- a/components/script/dom/mod.rs +++ b/components/script/dom/mod.rs @@ -17,7 +17,7 @@ //! //! * the **DOM object**: an instance of the Rust struct `dom::foo::Foo` //! (marked with the `#[dom_struct]` attribute) on the Rust heap; -//! * the **reflector**: a `JSObject` allocated by SpiderMonkey, that owns the +//! * the **reflector**: a `jsapi::JSObject` allocated by SpiderMonkey, that owns the //! DOM object. //! //! Memory management @@ -130,7 +130,7 @@ //! ============================= //! //! Every DOM object has a `Reflector` as its first (transitive) member field. -//! This contains a `*mut JSObject` that points to its reflector. +//! This contains a `*mut jsapi::JSObject` that points to its reflector. //! //! The `FooBinding::Wrap` function creates the reflector, stores a pointer to //! the DOM object in the reflector, and initializes the pointer to the reflector diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index 037195286554..54aeede22747 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -60,7 +60,7 @@ use dom_struct::dom_struct; use euclid::{Point2D, Vector2D, Rect, Size2D}; use heapsize::{HeapSizeOf, heap_size_of}; use html5ever::{Prefix, Namespace, QualName}; -use js::jsapi::{JSContext, JSObject, JSRuntime}; +use js::jsapi; use libc::{self, c_void, uintptr_t}; use msg::constellation_msg::{BrowsingContextId, PipelineId}; use ref_slice::ref_slice; @@ -981,13 +981,11 @@ fn first_node_not_in(mut nodes: I, not_in: &[NodeOrString]) -> Option Root { +pub unsafe fn from_untrusted_node_address(candidate: UntrustedNodeAddress) -> Root { // https://github.com/servo/servo/issues/6383 let candidate: uintptr_t = mem::transmute(candidate.0); -// let object: *mut JSObject = jsfriendapi::bindgen::JS_GetAddressableObject(runtime, -// candidate); - let object: *mut JSObject = mem::transmute(candidate); + // let object: *mut jsapi::JSObject = jsapi::JS_GetAddressableObject(runtime, candidate); + let object: *mut jsapi::JSObject = mem::transmute(candidate); if object.is_null() { panic!("Attempted to create a `JS` from an invalid pointer!") } @@ -1380,7 +1378,7 @@ impl Node { pub fn reflect_node( node: Box, document: &Document, - wrap_fn: unsafe extern "Rust" fn(*mut JSContext, &GlobalScope, Box) -> Root) + wrap_fn: unsafe extern "Rust" fn(*mut jsapi::JSContext, &GlobalScope, Box) -> Root) -> Root where N: DerivedFrom + DomObject { diff --git a/components/script/dom/paintworkletglobalscope.rs b/components/script/dom/paintworkletglobalscope.rs index 0a01e62cd9b1..cc89c562b83d 100644 --- a/components/script/dom/paintworkletglobalscope.rs +++ b/components/script/dom/paintworkletglobalscope.rs @@ -28,20 +28,10 @@ use dom_struct::dom_struct; use euclid::ScaleFactor; use euclid::TypedSize2D; use ipc_channel::ipc; -use js::jsapi::Call; -use js::jsapi::Construct1; -use js::jsapi::HandleValue; -use js::jsapi::HandleValueArray; -use js::jsapi::Heap; -use js::jsapi::IsCallable; -use js::jsapi::IsConstructor; -use js::jsapi::JSAutoCompartment; -use js::jsapi::JS_ClearPendingException; -use js::jsapi::JS_IsExceptionPending; -use js::jsapi::JS_NewArrayObject; -use js::jsval::JSVal; -use js::jsval::ObjectValue; -use js::jsval::UndefinedValue; +use js; +use js::heap::Heap; +use js::jsapi; +use js::jsval::{ObjectValue, UndefinedValue}; use js::rust::Runtime; use msg::constellation_msg::PipelineId; use net_traits::image::base::PixelFormat; @@ -75,7 +65,7 @@ pub struct PaintWorkletGlobalScope { /// https://drafts.css-houdini.org/css-paint-api/#paint-definitions paint_definitions: DOMRefCell>>, /// https://drafts.css-houdini.org/css-paint-api/#paint-class-instances - paint_class_instances: DOMRefCell>>>, + paint_class_instances: DOMRefCell>>>, /// The most recent name the worklet was called with cached_name: DOMRefCell, /// The most recent size the worklet was drawn at @@ -204,7 +194,12 @@ impl PaintWorkletGlobalScope { name, size_in_px.width, size_in_px.height, device_pixel_ratio); let cx = self.worklet_global.get_cx(); - let _ac = JSAutoCompartment::new(cx, self.worklet_global.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj( + cx, + self.worklet_global.reflector().get_jsobject().get() + ) + }; // TODO: Steps 1-2.1. // Step 2.2-5.1. @@ -238,13 +233,13 @@ impl PaintWorkletGlobalScope { Entry::Occupied(entry) => paint_instance.set(entry.get().get()), Entry::Vacant(entry) => { // Step 5.2-5.3 - let args = HandleValueArray::new(); + let args = jsapi::JS::HandleValueArray::new(); rooted!(in(cx) let mut result = null_mut()); - unsafe { Construct1(cx, class_constructor.handle(), &args, result.handle_mut()); } + unsafe { jsapi::JS::Construct1(cx, class_constructor.handle(), &args, result.handle_mut()); } paint_instance.set(ObjectValue(result.get())); - if unsafe { JS_IsExceptionPending(cx) } { + if unsafe { jsapi::JS_IsExceptionPending(cx) } { debug!("Paint constructor threw an exception {}.", name); - unsafe { JS_ClearPendingException(cx); } + unsafe { jsapi::JS_ClearPendingException(cx); } self.paint_definitions.borrow_mut().get_mut(name) .expect("Vanishing paint definition.") .constructor_valid_flag.set(false); @@ -269,11 +264,11 @@ impl PaintWorkletGlobalScope { debug!("Invoking paint function {}.", name); rooted_vec!(let arguments_values <- arguments.iter().cloned() .map(|argument| CSSStyleValue::new(self.upcast(), argument))); - let arguments_value_vec: Vec = arguments_values.iter() + let arguments_value_vec: Vec = arguments_values.iter() .map(|argument| ObjectValue(argument.reflector().get_jsobject().get())) .collect(); - let arguments_value_array = unsafe { HandleValueArray::from_rooted_slice(&*arguments_value_vec) }; - rooted!(in(cx) let argument_object = unsafe { JS_NewArrayObject(cx, &arguments_value_array) }); + let arguments_value_array = unsafe { jsapi::JS::HandleValueArray::from_rooted_slice(&*arguments_value_vec) }; + rooted!(in(cx) let argument_object = unsafe { jsapi::JS_NewArrayObject(cx, &arguments_value_array) }); let args_slice = [ ObjectValue(rendering_context.reflector().get_jsobject().get()), @@ -281,16 +276,16 @@ impl PaintWorkletGlobalScope { ObjectValue(properties.reflector().get_jsobject().get()), ObjectValue(argument_object.get()), ]; - let args = unsafe { HandleValueArray::from_rooted_slice(&args_slice) }; + let args = unsafe { jsapi::JS::HandleValueArray::from_rooted_slice(&args_slice) }; rooted!(in(cx) let mut result = UndefinedValue()); - unsafe { Call(cx, paint_instance.handle(), paint_function.handle(), &args, result.handle_mut()); } + unsafe { jsapi::JS::Call(cx, paint_instance.handle(), paint_function.handle(), &args, result.handle_mut()); } let missing_image_urls = rendering_context.take_missing_image_urls(); // Step 13. - if unsafe { JS_IsExceptionPending(cx) } { + if unsafe { jsapi::JS_IsExceptionPending(cx) } { debug!("Paint function threw an exception {}.", name); - unsafe { JS_ClearPendingException(cx); } + unsafe { jsapi::JS_ClearPendingException(cx); } return self.invalid_image(size_in_dpx, missing_image_urls); } @@ -407,7 +402,7 @@ impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope { .unwrap_or(true); // Step 14 - if unsafe { !IsConstructor(paint_obj.get()) } { + if unsafe { !jsapi::JS::IsConstructor(paint_obj.get()) } { return Err(Error::Type(String::from("Not a constructor."))); } @@ -422,7 +417,7 @@ impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope { // Steps 17-18 rooted!(in(cx) let mut paint_function = UndefinedValue()); unsafe { get_property_jsval(cx, prototype.handle(), "paint", paint_function.handle_mut())?; } - if !paint_function.is_object() || unsafe { !IsCallable(paint_function.to_object()) } { + if !paint_function.is_object() || unsafe { !jsapi::JS::IsCallable(paint_function.to_object()) } { return Err(Error::Type(String::from("Paint function is not callable."))); } @@ -465,13 +460,13 @@ pub enum PaintWorkletTask { /// A paint definition /// https://drafts.css-houdini.org/css-paint-api/#paint-definition -/// This type is dangerous, because it contains uboxed `Heap` values, +/// This type is dangerous, because it contains unboxed `Heap` values, /// which can't be moved. #[derive(HeapSizeOf, JSTraceable)] #[must_root] struct PaintDefinition { - class_constructor: Heap, - paint_function: Heap, + class_constructor: Heap, + paint_function: Heap, constructor_valid_flag: Cell, context_alpha_flag: bool, // TODO: this should be a list of CSS syntaxes. @@ -483,8 +478,8 @@ struct PaintDefinition { } impl PaintDefinition { - fn new(class_constructor: HandleValue, - paint_function: HandleValue, + fn new(class_constructor: jsapi::JS::HandleValue, + paint_function: jsapi::JS::HandleValue, alpha: bool, input_arguments_len: usize, context: &PaintRenderingContext2D) diff --git a/components/script/dom/permissions.rs b/components/script/dom/permissions.rs index 3368782d06e7..b504f2cf08ee 100644 --- a/components/script/dom/permissions.rs +++ b/components/script/dom/permissions.rs @@ -15,7 +15,7 @@ use dom::permissionstatus::PermissionStatus; use dom::promise::Promise; use dom_struct::dom_struct; use js::conversions::ConversionResult; -use js::jsapi::{JSContext, JSObject}; +use js::jsapi; use js::jsval::{ObjectValue, UndefinedValue}; #[cfg(target_os = "linux")] use servo_config::opts; @@ -34,12 +34,12 @@ const ROOT_DESC_CONVERSION_ERROR: &'static str = "Can't convert to an IDL value pub trait PermissionAlgorithm { type Descriptor; type Status; - fn create_descriptor(cx: *mut JSContext, - permission_descriptor_obj: *mut JSObject) + fn create_descriptor(cx: *mut jsapi::JSContext, + permission_descriptor_obj: *mut jsapi::JSObject) -> Result; - fn permission_query(cx: *mut JSContext, promise: &Rc, + fn permission_query(cx: *mut jsapi::JSContext, promise: &Rc, descriptor: &Self::Descriptor, status: &Self::Status); - fn permission_request(cx: *mut JSContext, promise: &Rc, + fn permission_request(cx: *mut jsapi::JSContext, promise: &Rc, descriptor: &Self::Descriptor, status: &Self::Status); fn permission_revoke(descriptor: &Self::Descriptor, status: &Self::Status); } @@ -75,8 +75,8 @@ impl Permissions { // https://w3c.github.io/permissions/#dom-permissions-revoke fn manipulate(&self, op: Operation, - cx: *mut JSContext, - permissionDesc: *mut JSObject, + cx: *mut jsapi::JSContext, + permissionDesc: *mut jsapi::JSObject, promise: Option>) -> Rc { // (Query, Request) Step 3. @@ -178,21 +178,21 @@ impl PermissionsMethods for Permissions { #[allow(unrooted_must_root)] #[allow(unsafe_code)] // https://w3c.github.io/permissions/#dom-permissions-query - unsafe fn Query(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc { + unsafe fn Query(&self, cx: *mut jsapi::JSContext, permissionDesc: *mut jsapi::JSObject) -> Rc { self.manipulate(Operation::Query, cx, permissionDesc, None) } #[allow(unrooted_must_root)] #[allow(unsafe_code)] // https://w3c.github.io/permissions/#dom-permissions-request - unsafe fn Request(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc { + unsafe fn Request(&self, cx: *mut jsapi::JSContext, permissionDesc: *mut jsapi::JSObject) -> Rc { self.manipulate(Operation::Request, cx, permissionDesc, None) } #[allow(unrooted_must_root)] #[allow(unsafe_code)] // https://w3c.github.io/permissions/#dom-permissions-revoke - unsafe fn Revoke(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc { + unsafe fn Revoke(&self, cx: *mut jsapi::JSContext, permissionDesc: *mut jsapi::JSObject) -> Rc { self.manipulate(Operation::Revoke, cx, permissionDesc, None) } } @@ -202,8 +202,8 @@ impl PermissionAlgorithm for Permissions { type Status = PermissionStatus; #[allow(unsafe_code)] - fn create_descriptor(cx: *mut JSContext, - permission_descriptor_obj: *mut JSObject) + fn create_descriptor(cx: *mut jsapi::JSContext, + permission_descriptor_obj: *mut jsapi::JSObject) -> Result { rooted!(in(cx) let mut property = UndefinedValue()); property.handle_mut().set(ObjectValue(permission_descriptor_obj)); @@ -217,7 +217,7 @@ impl PermissionAlgorithm for Permissions { } // https://w3c.github.io/permissions/#boolean-permission-query-algorithm - fn permission_query(_cx: *mut JSContext, + fn permission_query(_cx: *mut jsapi::JSContext, _promise: &Rc, _descriptor: &PermissionDescriptor, status: &PermissionStatus) { @@ -226,7 +226,7 @@ impl PermissionAlgorithm for Permissions { } // https://w3c.github.io/permissions/#boolean-permission-request-algorithm - fn permission_request(cx: *mut JSContext, + fn permission_request(cx: *mut jsapi::JSContext, promise: &Rc, descriptor: &PermissionDescriptor, status: &PermissionStatus) { diff --git a/components/script/dom/popstateevent.rs b/components/script/dom/popstateevent.rs index c5e63d4ea50b..9eade74b2a56 100644 --- a/components/script/dom/popstateevent.rs +++ b/components/script/dom/popstateevent.rs @@ -14,8 +14,8 @@ use dom::bindings::trace::RootedTraceableBox; use dom::event::Event; use dom::window::Window; use dom_struct::dom_struct; -use js::jsapi::{Heap, HandleValue, JSContext}; -use js::jsval::JSVal; +use js; +use js::jsapi; use servo_atoms::Atom; // https://html.spec.whatwg.org/multipage/#the-popstateevent-interface @@ -23,14 +23,14 @@ use servo_atoms::Atom; pub struct PopStateEvent { event: Event, #[ignore_heap_size_of = "Defined in rust-mozjs"] - state: Heap, + state: js::heap::Heap, } impl PopStateEvent { fn new_inherited() -> PopStateEvent { PopStateEvent { event: Event::new_inherited(), - state: Heap::default(), + state: js::heap::Heap::default(), } } @@ -44,7 +44,7 @@ impl PopStateEvent { type_: Atom, bubbles: bool, cancelable: bool, - state: HandleValue) + state: jsapi::JS::HandleValue) -> Root { let ev = PopStateEvent::new_uninitialized(window); ev.state.set(state.get()); @@ -70,7 +70,7 @@ impl PopStateEvent { impl PopStateEventMethods for PopStateEvent { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state - unsafe fn State(&self, _cx: *mut JSContext) -> JSVal { + unsafe fn State(&self, _cx: *mut jsapi::JSContext) -> jsapi::JS::Value { self.state.get() } diff --git a/components/script/dom/promise.rs b/components/script/dom/promise.rs index 5595e999c9da..f7ddd6229e88 100644 --- a/components/script/dom/promise.rs +++ b/components/script/dom/promise.rs @@ -20,15 +20,10 @@ use dom::bindings::utils::AsCCharPtrPtr; use dom::globalscope::GlobalScope; use dom::promisenativehandler::PromiseNativeHandler; use dom_struct::dom_struct; +use js; use js::conversions::ToJSValConvertible; -use js::jsapi::{CallOriginalPromiseResolve, CallOriginalPromiseReject, CallOriginalPromiseThen}; -use js::jsapi::{JSAutoCompartment, CallArgs, JS_GetFunctionObject, JS_NewFunction}; -use js::jsapi::{JSContext, HandleValue, HandleObject, IsPromiseObject, GetFunctionNativeReserved}; -use js::jsapi::{JS_ClearPendingException, JSObject, AddRawValueRoot, RemoveRawValueRoot, PromiseState}; -use js::jsapi::{MutableHandleObject, NewPromiseObject, ResolvePromise, RejectPromise, GetPromiseState}; -use js::jsapi::{SetFunctionNativeReserved, NewFunctionWithReserved, AddPromiseReactions}; -use js::jsapi::Heap; -use js::jsval::{JSVal, UndefinedValue, ObjectValue, Int32Value}; +use js::jsapi; +use js::jsval::{UndefinedValue, ObjectValue, Int32Value}; use std::ptr; use std::rc::Rc; @@ -40,23 +35,23 @@ pub struct Promise { /// native instance exists. This ensures that the reflector will never be GCed /// while native code could still interact with its native representation. #[ignore_heap_size_of = "SM handles JS values"] - permanent_js_root: Heap, + permanent_js_root: js::heap::Heap, } /// Private helper to enable adding new methods to Rc. trait PromiseHelper { #[allow(unsafe_code)] - unsafe fn initialize(&self, cx: *mut JSContext); + unsafe fn initialize(&self, cx: *mut jsapi::JSContext); } impl PromiseHelper for Rc { #[allow(unsafe_code)] - unsafe fn initialize(&self, cx: *mut JSContext) { + unsafe fn initialize(&self, cx: *mut jsapi::JSContext) { let obj = self.reflector().get_jsobject(); self.permanent_js_root.set(ObjectValue(*obj)); - assert!(AddRawValueRoot(cx, - self.permanent_js_root.get_unsafe(), - b"Promise::root\0".as_c_char_ptr())); + assert!(jsapi::js::AddRawValueRoot(cx, + self.permanent_js_root.get_unsafe(), + b"Promise::root\0".as_c_char_ptr())); } } @@ -65,7 +60,7 @@ impl Drop for Promise { fn drop(&mut self) { let cx = self.global().get_cx(); unsafe { - RemoveRawValueRoot(cx, self.permanent_js_root.get_unsafe()); + jsapi::js::RemoveRawValueRoot(cx, self.permanent_js_root.get_unsafe()); } } } @@ -76,7 +71,7 @@ impl Promise { let cx = global.get_cx(); rooted!(in(cx) let mut obj = ptr::null_mut()); unsafe { - Promise::create_js_promise(cx, HandleObject::null(), obj.handle_mut()); + Promise::create_js_promise(cx, jsapi::JS::HandleObject::null(), obj.handle_mut()); Promise::new_with_js_promise(obj.handle(), cx) } } @@ -90,11 +85,11 @@ impl Promise { } #[allow(unsafe_code, unrooted_must_root)] - unsafe fn new_with_js_promise(obj: HandleObject, cx: *mut JSContext) -> Rc { - assert!(IsPromiseObject(obj)); + unsafe fn new_with_js_promise(obj: jsapi::JS::HandleObject, cx: *mut jsapi::JSContext) -> Rc { + assert!(jsapi::JS::IsPromiseObject(obj)); let promise = Promise { reflector: Reflector::new(), - permanent_js_root: Heap::default(), + permanent_js_root: js::heap::Heap::default(), }; let mut promise = Rc::new(promise); Rc::get_mut(&mut promise).unwrap().init_reflector(obj.get()); @@ -103,22 +98,26 @@ impl Promise { } #[allow(unsafe_code)] - unsafe fn create_js_promise(cx: *mut JSContext, proto: HandleObject, obj: MutableHandleObject) { - let do_nothing_func = JS_NewFunction(cx, Some(do_nothing_promise_executor), /* nargs = */ 2, + unsafe fn create_js_promise(cx: *mut jsapi::JSContext, + proto: jsapi::JS::HandleObject, + obj: jsapi::JS::MutableHandleObject) { + let do_nothing_func = jsapi::JS_NewFunction(cx, Some(do_nothing_promise_executor), /* nargs = */ 2, /* flags = */ 0, ptr::null()); assert!(!do_nothing_func.is_null()); - rooted!(in(cx) let do_nothing_obj = JS_GetFunctionObject(do_nothing_func)); + rooted!(in(cx) let do_nothing_obj = jsapi::JS_GetFunctionObject(do_nothing_func)); assert!(!do_nothing_obj.is_null()); - obj.set(NewPromiseObject(cx, do_nothing_obj.handle(), proto)); + obj.set(jsapi::JS::NewPromiseObject(cx, do_nothing_obj.handle(), proto)); assert!(!obj.is_null()); } #[allow(unrooted_must_root, unsafe_code)] pub fn Resolve(global: &GlobalScope, - cx: *mut JSContext, - value: HandleValue) -> Fallible> { - let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get()); - rooted!(in(cx) let p = unsafe { CallOriginalPromiseResolve(cx, value) }); + cx: *mut jsapi::JSContext, + value: jsapi::JS::HandleValue) -> Fallible> { + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, global.reflector().get_jsobject().get()) + }; + rooted!(in(cx) let p = unsafe { jsapi::JS::CallOriginalPromiseResolve(cx, value) }); assert!(!p.handle().is_null()); unsafe { Ok(Promise::new_with_js_promise(p.handle(), cx)) @@ -127,10 +126,12 @@ impl Promise { #[allow(unrooted_must_root, unsafe_code)] pub fn Reject(global: &GlobalScope, - cx: *mut JSContext, - value: HandleValue) -> Fallible> { - let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get()); - rooted!(in(cx) let p = unsafe { CallOriginalPromiseReject(cx, value) }); + cx: *mut jsapi::JSContext, + value: jsapi::JS::HandleValue) -> Fallible> { + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, global.reflector().get_jsobject().get()) + }; + rooted!(in(cx) let p = unsafe { jsapi::JS::CallOriginalPromiseReject(cx, value) }); assert!(!p.handle().is_null()); unsafe { Ok(Promise::new_with_js_promise(p.handle(), cx)) @@ -138,7 +139,7 @@ impl Promise { } #[allow(unsafe_code)] - pub fn resolve_native(&self, cx: *mut JSContext, val: &T) where T: ToJSValConvertible { + pub fn resolve_native(&self, cx: *mut jsapi::JSContext, val: &T) where T: ToJSValConvertible { rooted!(in(cx) let mut v = UndefinedValue()); unsafe { val.to_jsval(cx, v.handle_mut()); @@ -147,16 +148,16 @@ impl Promise { } #[allow(unrooted_must_root, unsafe_code)] - pub fn resolve(&self, cx: *mut JSContext, value: HandleValue) { + pub fn resolve(&self, cx: *mut jsapi::JSContext, value: jsapi::JS::HandleValue) { unsafe { - if !ResolvePromise(cx, self.promise_obj(), value) { - JS_ClearPendingException(cx); + if !jsapi::JS::ResolvePromise(cx, self.promise_obj(), value) { + jsapi::JS_ClearPendingException(cx); } } } #[allow(unsafe_code)] - pub fn reject_native(&self, cx: *mut JSContext, val: &T) where T: ToJSValConvertible { + pub fn reject_native(&self, cx: *mut jsapi::JSContext, val: &T) where T: ToJSValConvertible { rooted!(in(cx) let mut v = UndefinedValue()); unsafe { val.to_jsval(cx, v.handle_mut()); @@ -165,7 +166,7 @@ impl Promise { } #[allow(unsafe_code)] - pub fn reject_error(&self, cx: *mut JSContext, error: Error) { + pub fn reject_error(&self, cx: *mut jsapi::JSContext, error: Error) { rooted!(in(cx) let mut v = UndefinedValue()); unsafe { error.to_jsval(cx, &self.global(), v.handle_mut()); @@ -175,46 +176,47 @@ impl Promise { #[allow(unrooted_must_root, unsafe_code)] pub fn reject(&self, - cx: *mut JSContext, - value: HandleValue) { + cx: *mut jsapi::JSContext, + value: jsapi::JS::HandleValue) { unsafe { - if !RejectPromise(cx, self.promise_obj(), value) { - JS_ClearPendingException(cx); + if !jsapi::JS::RejectPromise(cx, self.promise_obj(), value) { + jsapi::JS_ClearPendingException(cx); } } } #[allow(unrooted_must_root, unsafe_code)] pub fn then(&self, - cx: *mut JSContext, - _callee: HandleObject, + cx: *mut jsapi::JSContext, + _callee: jsapi::JS::HandleObject, cb_resolve: AnyCallback, cb_reject: AnyCallback, - result: MutableHandleObject) { + result: jsapi::JS::MutableHandleObject) { let promise = self.promise_obj(); rooted!(in(cx) let resolve = cb_resolve.callback()); rooted!(in(cx) let reject = cb_reject.callback()); unsafe { rooted!(in(cx) let res = - CallOriginalPromiseThen(cx, promise, resolve.handle(), reject.handle())); + jsapi::JS::CallOriginalPromiseThen(cx, promise, resolve.handle(), reject.handle())); result.set(*res); } } #[allow(unsafe_code)] pub fn is_settled(&self) -> bool { - let state = unsafe { GetPromiseState(self.promise_obj()) }; + let state = unsafe { jsapi::JS::GetPromiseState(self.promise_obj()) }; match state { - PromiseState::Rejected | PromiseState::Fulfilled => true, + jsapi::JS::PromiseState::Rejected | + jsapi::JS::PromiseState::Fulfilled => true, _ => false } } #[allow(unsafe_code)] - fn promise_obj(&self) -> HandleObject { + fn promise_obj(&self) -> jsapi::JS::HandleObject { let obj = self.reflector().get_jsobject(); unsafe { - assert!(IsPromiseObject(obj)); + assert!(jsapi::JS::IsPromiseObject(obj)); } obj } @@ -233,18 +235,18 @@ impl Promise { NativeHandlerTask::Reject)); unsafe { - let ok = AddPromiseReactions(cx, - self.promise_obj(), - resolve_func.handle(), - reject_func.handle()); + let ok = jsapi::JS::AddPromiseReactions(cx, + self.promise_obj(), + resolve_func.handle(), + reject_func.handle()); assert!(ok); } } } #[allow(unsafe_code)] -unsafe extern fn do_nothing_promise_executor(_cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool { - let args = CallArgs::from_vp(vp, argc); +unsafe extern fn do_nothing_promise_executor(_cx: *mut jsapi::JSContext, argc: u32, vp: *mut jsapi::JS::Value) -> bool { + let args = jsapi::JS::CallArgs::from_vp(vp, argc); *args.rval() = UndefinedValue(); true } @@ -259,15 +261,15 @@ enum NativeHandlerTask { } #[allow(unsafe_code)] -unsafe extern fn native_handler_callback(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool { - let args = CallArgs::from_vp(vp, argc); - rooted!(in(cx) let v = *GetFunctionNativeReserved(args.callee(), SLOT_NATIVEHANDLER)); +unsafe extern fn native_handler_callback(cx: *mut jsapi::JSContext, argc: u32, vp: *mut jsapi::JS::Value) -> bool { + let args = jsapi::JS::CallArgs::from_vp(vp, argc); + rooted!(in(cx) let v = *jsapi::js::GetFunctionNativeReserved(args.callee(), SLOT_NATIVEHANDLER)); assert!(v.get().is_object()); let handler = root_from_object::(v.to_object()) .ok().expect("unexpected value for native handler in promise native handler callback"); - rooted!(in(cx) let v = *GetFunctionNativeReserved(args.callee(), SLOT_NATIVEHANDLER_TASK)); + rooted!(in(cx) let v = *jsapi::js::GetFunctionNativeReserved(args.callee(), SLOT_NATIVEHANDLER_TASK)); match v.to_int32() { v if v == NativeHandlerTask::Resolve as i32 => handler.resolved_callback(cx, args.get(0)), v if v == NativeHandlerTask::Reject as i32 => handler.rejected_callback(cx, args.get(0)), @@ -278,22 +280,21 @@ unsafe extern fn native_handler_callback(cx: *mut JSContext, argc: u32, vp: *mut } #[allow(unsafe_code)] -fn create_native_handler_function(cx: *mut JSContext, - holder: HandleObject, - task: NativeHandlerTask) -> *mut JSObject { +fn create_native_handler_function(cx: *mut jsapi::JSContext, + holder: jsapi::JS::HandleObject, + task: NativeHandlerTask) -> *mut jsapi::JSObject { unsafe { - let func = NewFunctionWithReserved(cx, Some(native_handler_callback), 1, 0, ptr::null()); + let func = jsapi::js::NewFunctionWithReserved(cx, Some(native_handler_callback), 1, 0, ptr::null()); assert!(!func.is_null()); - rooted!(in(cx) let obj = JS_GetFunctionObject(func)); + rooted!(in(cx) let obj = jsapi::JS_GetFunctionObject(func)); assert!(!obj.is_null()); - SetFunctionNativeReserved(obj.get(), - SLOT_NATIVEHANDLER, - &ObjectValue(*holder)); - SetFunctionNativeReserved(obj.get(), - SLOT_NATIVEHANDLER_TASK, - &Int32Value(task as i32)); + jsapi::js::SetFunctionNativeReserved(obj.get(), + SLOT_NATIVEHANDLER, + &ObjectValue(*holder)); + jsapi::js::SetFunctionNativeReserved(obj.get(), + SLOT_NATIVEHANDLER_TASK, + &Int32Value(task as i32)); obj.get() } } - diff --git a/components/script/dom/promisenativehandler.rs b/components/script/dom/promisenativehandler.rs index 59fe1d7425b9..9ed61712b494 100644 --- a/components/script/dom/promisenativehandler.rs +++ b/components/script/dom/promisenativehandler.rs @@ -9,10 +9,10 @@ use dom::bindings::trace::JSTraceable; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use heapsize::HeapSizeOf; -use js::jsapi::{JSContext, HandleValue}; +use js::jsapi; pub trait Callback: JSTraceable + HeapSizeOf { - fn callback(&self, cx: *mut JSContext, v: HandleValue); + fn callback(&self, cx: *mut jsapi::JSContext, v: jsapi::JS::HandleValue); } #[dom_struct] @@ -34,17 +34,17 @@ impl PromiseNativeHandler { }, global, PromiseNativeHandlerBinding::Wrap) } - fn callback(callback: &Option>, cx: *mut JSContext, v: HandleValue) { + fn callback(callback: &Option>, cx: *mut jsapi::JSContext, v: jsapi::JS::HandleValue) { if let Some(ref callback) = *callback { callback.callback(cx, v) } } - pub fn resolved_callback(&self, cx: *mut JSContext, v: HandleValue) { + pub fn resolved_callback(&self, cx: *mut jsapi::JSContext, v: jsapi::JS::HandleValue) { PromiseNativeHandler::callback(&self.resolve, cx, v) } - pub fn rejected_callback(&self, cx: *mut JSContext, v: HandleValue) { + pub fn rejected_callback(&self, cx: *mut jsapi::JSContext, v: jsapi::JS::HandleValue) { PromiseNativeHandler::callback(&self.reject, cx, v) } } diff --git a/components/script/dom/range.rs b/components/script/dom/range.rs index 1e65caedc9dd..83a249fd3e88 100644 --- a/components/script/dom/range.rs +++ b/components/script/dom/range.rs @@ -28,7 +28,7 @@ use dom::text::Text; use dom::window::Window; use dom_struct::dom_struct; use heapsize::HeapSizeOf; -use js::jsapi::JSTracer; +use js::jsapi; use std::cell::{Cell, UnsafeCell}; use std::cmp::{Ord, Ordering, PartialEq, PartialOrd}; @@ -1256,7 +1256,7 @@ impl HeapSizeOf for WeakRangeVec { #[allow(unsafe_code)] unsafe impl JSTraceable for WeakRangeVec { - unsafe fn trace(&self, _: *mut JSTracer) { + unsafe fn trace(&self, _: *mut jsapi::JSTracer) { (*self.cell.get()).retain_alive() } } diff --git a/components/script/dom/serviceworker.rs b/components/script/dom/serviceworker.rs index 0c651e07aa4a..6a0dbc482a89 100644 --- a/components/script/dom/serviceworker.rs +++ b/components/script/dom/serviceworker.rs @@ -16,7 +16,7 @@ use dom::bindings::structuredclone::StructuredCloneData; use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use js::jsapi::{HandleValue, JSContext}; +use js::jsapi; use script_thread::Runnable; use script_traits::{ScriptMsg, DOMMessage}; use servo_url::ServoUrl; @@ -83,7 +83,7 @@ impl ServiceWorkerMethods for ServiceWorker { #[allow(unsafe_code)] // https://w3c.github.io/ServiceWorker/#service-worker-postmessage - unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { + unsafe fn PostMessage(&self, cx: *mut jsapi::JSContext, message: jsapi::JS::HandleValue) -> ErrorResult { // Step 1 if let ServiceWorkerState::Redundant = self.state.get() { return Err(Error::InvalidState); diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index e741160c2267..48e16572ecd0 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -21,7 +21,8 @@ use dom::workerglobalscope::WorkerGlobalScope; use dom_struct::dom_struct; use ipc_channel::ipc::{self, IpcSender, IpcReceiver}; use ipc_channel::router::ROUTER; -use js::jsapi::{JS_SetInterruptCallback, JSAutoCompartment, JSContext}; +use js; +use js::jsapi; use js::jsval::UndefinedValue; use js::rust::Runtime; use net_traits::{load_whole_resource, IpcSend, CustomResponseMediator}; @@ -198,7 +199,7 @@ impl ServiceWorkerGlobalScope { unsafe { // Handle interrupt requests - JS_SetInterruptCallback(scope.runtime(), Some(interrupt_callback)); + jsapi::JS_AddInterruptCallback(js::rust::Runtime::get(), Some(interrupt_callback)); } scope.execute_script(DOMString::from(source)); @@ -251,6 +252,7 @@ impl ServiceWorkerGlobalScope { } } + #[allow(unsafe_code)] fn handle_script_event(&self, msg: ServiceWorkerScriptMsg) { use self::ServiceWorkerScriptMsg::*; @@ -258,7 +260,10 @@ impl ServiceWorkerGlobalScope { CommonWorker(WorkerScriptMsg::DOMMessage(data)) => { let scope = self.upcast::(); let target = self.upcast(); - let _ac = JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(scope.get_cx(), + scope.reflector().get_jsobject().get()) + }; rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); data.read(scope.upcast(), message.handle_mut()); ExtendableMessageEvent::dispatch_jsval(target, scope.upcast(), message.handle()); @@ -332,7 +337,7 @@ impl ServiceWorkerGlobalScope { } #[allow(unsafe_code)] -unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { +unsafe extern "C" fn interrupt_callback(cx: *mut jsapi::JSContext) -> bool { let worker = Root::downcast::(GlobalScope::from_context(cx)) .expect("global is not a worker scope"); diff --git a/components/script/dom/servoparser/html.rs b/components/script/dom/servoparser/html.rs index 4621faacf545..87298898be72 100644 --- a/components/script/dom/servoparser/html.rs +++ b/components/script/dom/servoparser/html.rs @@ -24,7 +24,7 @@ use html5ever::serialize::TraversalScope; use html5ever::serialize::TraversalScope::ChildrenOnly; use html5ever::tokenizer::{Tokenizer as HtmlTokenizer, TokenizerOpts, TokenizerResult}; use html5ever::tree_builder::{Tracer as HtmlTracer, TreeBuilder, TreeBuilderOpts}; -use js::jsapi::JSTracer; +use js::jsapi; use servo_url::ServoUrl; use std::io; @@ -97,8 +97,8 @@ impl Tokenizer { #[allow(unsafe_code)] unsafe impl JSTraceable for HtmlTokenizer, Sink>> { - unsafe fn trace(&self, trc: *mut JSTracer) { - struct Tracer(*mut JSTracer); + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { + struct Tracer(*mut jsapi::JSTracer); let tracer = Tracer(trc); impl HtmlTracer for Tracer { diff --git a/components/script/dom/servoparser/xml.rs b/components/script/dom/servoparser/xml.rs index 508a66929195..228550fb6f08 100644 --- a/components/script/dom/servoparser/xml.rs +++ b/components/script/dom/servoparser/xml.rs @@ -10,7 +10,7 @@ use dom::document::Document; use dom::htmlscriptelement::HTMLScriptElement; use dom::node::Node; use dom::servoparser::Sink; -use js::jsapi::JSTracer; +use js::jsapi; use servo_url::ServoUrl; use xml5ever::buffer_queue::BufferQueue; use xml5ever::tokenizer::XmlTokenizer; @@ -68,8 +68,8 @@ impl Tokenizer { #[allow(unsafe_code)] unsafe impl JSTraceable for XmlTokenizer, Sink>> { - unsafe fn trace(&self, trc: *mut JSTracer) { - struct Tracer(*mut JSTracer); + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { + struct Tracer(*mut jsapi::JSTracer); let tracer = Tracer(trc); impl XmlTracer for Tracer { diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index 7bdb6e9910c6..1b560baf3ff9 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -35,9 +35,10 @@ use dom::promise::Promise; use dom::promisenativehandler::{PromiseNativeHandler, Callback}; use dom::url::URL; use dom_struct::dom_struct; -use js::jsapi::{HandleObject, HandleValue, Heap, JSContext, JSObject, JSAutoCompartment}; -use js::jsapi::{JS_NewPlainObject, JS_NewUint8ClampedArray}; -use js::jsval::{JSVal, NullValue}; +use js; +use js::heap::Heap; +use js::jsapi; +use js::jsval::NullValue; use script_traits::MsDuration; use servo_config::prefs::PREFS; use std::borrow::ToOwned; @@ -151,23 +152,23 @@ impl TestBindingMethods for TestBinding { } fn SetUnion9Attribute(&self, _: ByteStringOrLong) {} #[allow(unsafe_code)] - unsafe fn ArrayAttribute(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> { - rooted!(in(cx) let array = JS_NewUint8ClampedArray(cx, 16)); + unsafe fn ArrayAttribute(&self, cx: *mut jsapi::JSContext) -> NonZero<*mut jsapi::JSObject> { + rooted!(in(cx) let array = jsapi::JS_NewUint8ClampedArray(cx, 16)); assert!(!array.is_null()); NonZero::new_unchecked(array.get()) } #[allow(unsafe_code)] - unsafe fn AnyAttribute(&self, _: *mut JSContext) -> JSVal { NullValue() } + unsafe fn AnyAttribute(&self, _: *mut jsapi::JSContext) -> jsapi::JS::Value { NullValue() } #[allow(unsafe_code)] - unsafe fn SetAnyAttribute(&self, _: *mut JSContext, _: HandleValue) {} + unsafe fn SetAnyAttribute(&self, _: *mut jsapi::JSContext, _: jsapi::JS::HandleValue) {} #[allow(unsafe_code)] - unsafe fn ObjectAttribute(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> { - rooted!(in(cx) let obj = JS_NewPlainObject(cx)); + unsafe fn ObjectAttribute(&self, cx: *mut jsapi::JSContext) -> NonZero<*mut jsapi::JSObject> { + rooted!(in(cx) let obj = jsapi::JS_NewPlainObject(cx)); assert!(!obj.is_null()); NonZero::new_unchecked(obj.get()) } #[allow(unsafe_code)] - unsafe fn SetObjectAttribute(&self, _: *mut JSContext, _: *mut JSObject) {} + unsafe fn SetObjectAttribute(&self, _: *mut jsapi::JSContext, _: *mut jsapi::JSObject) {} fn GetBooleanAttributeNullable(&self) -> Option { Some(false) } fn SetBooleanAttributeNullable(&self, _: Option) {} @@ -220,9 +221,12 @@ impl TestBindingMethods for TestBinding { self.url.set(url); } #[allow(unsafe_code)] - unsafe fn GetObjectAttributeNullable(&self, _: *mut JSContext) -> Option> { None } + unsafe fn GetObjectAttributeNullable(&self, _: *mut jsapi::JSContext) + -> Option> { + None + } #[allow(unsafe_code)] - unsafe fn SetObjectAttributeNullable(&self, _: *mut JSContext, _: *mut JSObject) {} + unsafe fn SetObjectAttributeNullable(&self, _: *mut jsapi::JSContext, _: *mut jsapi::JSObject) {} fn GetUnionAttributeNullable(&self) -> Option { Some(HTMLElementOrLong::Long(0)) } @@ -270,9 +274,9 @@ impl TestBindingMethods for TestBinding { Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) } #[allow(unsafe_code)] - unsafe fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { NullValue() } + unsafe fn ReceiveAny(&self, _: *mut jsapi::JSContext) -> jsapi::JS::Value { NullValue() } #[allow(unsafe_code)] - unsafe fn ReceiveObject(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> { + unsafe fn ReceiveObject(&self, cx: *mut jsapi::JSContext) -> NonZero<*mut jsapi::JSObject> { self.ObjectAttribute(cx) } fn ReceiveUnion(&self) -> HTMLElementOrLong { HTMLElementOrLong::Long(0) } @@ -316,7 +320,7 @@ impl TestBindingMethods for TestBinding { Some(Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) } #[allow(unsafe_code)] - unsafe fn ReceiveNullableObject(&self, cx: *mut JSContext) -> Option> { + unsafe fn ReceiveNullableObject(&self, cx: *mut jsapi::JSContext) -> Option> { self.GetObjectAttributeNullable(cx) } fn ReceiveNullableUnion(&self) -> Option { @@ -438,13 +442,13 @@ impl TestBindingMethods for TestBinding { fn PassUnion8(&self, _: ByteStringSequenceOrLong) {} fn PassUnion9(&self, _: RootedTraceableBox) {} #[allow(unsafe_code)] - unsafe fn PassUnion10(&self, _: *mut JSContext, _: RootedTraceableBox) {} + unsafe fn PassUnion10(&self, _: *mut jsapi::JSContext, _: RootedTraceableBox) {} fn PassUnionWithTypedef(&self, _: DocumentOrTestTypedef) {} fn PassUnionWithTypedef2(&self, _: LongSequenceOrTestTypedef) {} #[allow(unsafe_code)] - unsafe fn PassAny(&self, _: *mut JSContext, _: HandleValue) {} + unsafe fn PassAny(&self, _: *mut jsapi::JSContext, _: jsapi::JS::HandleValue) {} #[allow(unsafe_code)] - unsafe fn PassObject(&self, _: *mut JSContext, _: *mut JSObject) {} + unsafe fn PassObject(&self, _: *mut jsapi::JSContext, _: *mut jsapi::JSObject) {} fn PassCallbackFunction(&self, _: Rc) {} fn PassCallbackInterface(&self, _: Rc) {} fn PassSequence(&self, _: Vec) {} @@ -470,7 +474,7 @@ impl TestBindingMethods for TestBinding { // fn PassNullableEnum(self, _: Option) {} fn PassNullableInterface(&self, _: Option<&Blob>) {} #[allow(unsafe_code)] - unsafe fn PassNullableObject(&self, _: *mut JSContext, _: *mut JSObject) {} + unsafe fn PassNullableObject(&self, _: *mut jsapi::JSContext, _: *mut jsapi::JSObject) {} fn PassNullableUnion(&self, _: Option) {} fn PassNullableUnion2(&self, _: Option) {} fn PassNullableUnion3(&self, _: Option) {} @@ -506,9 +510,9 @@ impl TestBindingMethods for TestBinding { fn PassOptionalUnion5(&self, _: Option) {} fn PassOptionalUnion6(&self, _: Option) {} #[allow(unsafe_code)] - unsafe fn PassOptionalAny(&self, _: *mut JSContext, _: HandleValue) {} + unsafe fn PassOptionalAny(&self, _: *mut jsapi::JSContext, _: jsapi::JS::HandleValue) {} #[allow(unsafe_code)] - unsafe fn PassOptionalObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {} + unsafe fn PassOptionalObject(&self, _: *mut jsapi::JSContext, _: Option<*mut jsapi::JSObject>) {} fn PassOptionalCallbackFunction(&self, _: Option>) {} fn PassOptionalCallbackInterface(&self, _: Option>) {} fn PassOptionalSequence(&self, _: Option>) {} @@ -532,7 +536,7 @@ impl TestBindingMethods for TestBinding { // fn PassOptionalNullableEnum(self, _: Option>) {} fn PassOptionalNullableInterface(&self, _: Option>) {} #[allow(unsafe_code)] - unsafe fn PassOptionalNullableObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {} + unsafe fn PassOptionalNullableObject(&self, _: *mut jsapi::JSContext, _: Option<*mut jsapi::JSObject>) {} fn PassOptionalNullableUnion(&self, _: Option>) {} fn PassOptionalNullableUnion2(&self, _: Option>) {} fn PassOptionalNullableUnion3(&self, _: Option>) {} @@ -576,13 +580,13 @@ impl TestBindingMethods for TestBinding { // fn PassOptionalNullableEnumWithDefault(self, _: Option) {} fn PassOptionalNullableInterfaceWithDefault(&self, _: Option<&Blob>) {} #[allow(unsafe_code)] - unsafe fn PassOptionalNullableObjectWithDefault(&self, _: *mut JSContext, _: *mut JSObject) {} + unsafe fn PassOptionalNullableObjectWithDefault(&self, _: *mut jsapi::JSContext, _: *mut jsapi::JSObject) {} fn PassOptionalNullableUnionWithDefault(&self, _: Option) {} fn PassOptionalNullableUnion2WithDefault(&self, _: Option) {} // fn PassOptionalNullableCallbackFunctionWithDefault(self, _: Option) {} fn PassOptionalNullableCallbackInterfaceWithDefault(&self, _: Option>) {} #[allow(unsafe_code)] - unsafe fn PassOptionalAnyWithDefault(&self, _: *mut JSContext, _: HandleValue) {} + unsafe fn PassOptionalAnyWithDefault(&self, _: *mut jsapi::JSContext, _: jsapi::JS::HandleValue) {} fn PassOptionalNullableBooleanWithNonNullDefault(&self, _: Option) {} fn PassOptionalNullableByteWithNonNullDefault(&self, _: Option) {} @@ -628,9 +632,9 @@ impl TestBindingMethods for TestBinding { fn PassVariadicUnion6(&self, _: Vec) {} fn PassVariadicUnion7(&self, _: Vec) {} #[allow(unsafe_code)] - unsafe fn PassVariadicAny(&self, _: *mut JSContext, _: Vec) {} + unsafe fn PassVariadicAny(&self, _: *mut jsapi::JSContext, _: Vec) {} #[allow(unsafe_code)] - unsafe fn PassVariadicObject(&self, _: *mut JSContext, _: Vec<*mut JSObject>) {} + unsafe fn PassVariadicObject(&self, _: *mut jsapi::JSContext, _: Vec<*mut jsapi::JSObject>) {} fn BooleanMozPreference(&self, pref_name: DOMString) -> bool { PREFS.get(pref_name.as_ref()).as_boolean().unwrap_or(false) } @@ -670,27 +674,33 @@ impl TestBindingMethods for TestBinding { fn ReceiveMozMapOfNullableInts(&self) -> MozMap> { MozMap::new() } fn ReceiveNullableMozMapOfNullableInts(&self) -> Option>> { Some(MozMap::new()) } fn ReceiveMozMapOfMozMaps(&self) -> MozMap> { MozMap::new() } - fn ReceiveAnyMozMap(&self) -> MozMap { MozMap::new() } + fn ReceiveAnyMozMap(&self) -> MozMap { MozMap::new() } #[allow(unrooted_must_root)] #[allow(unsafe_code)] - unsafe fn ReturnResolvedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible> { + unsafe fn ReturnResolvedPromise(&self, + cx: *mut jsapi::JSContext, + v: jsapi::JS::HandleValue) + -> Fallible> { Promise::Resolve(&self.global(), cx, v) } #[allow(unrooted_must_root)] #[allow(unsafe_code)] - unsafe fn ReturnRejectedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible> { + unsafe fn ReturnRejectedPromise(&self, + cx: *mut jsapi::JSContext, + v: jsapi::JS::HandleValue) + -> Fallible> { Promise::Reject(&self.global(), cx, v) } #[allow(unsafe_code)] - unsafe fn PromiseResolveNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { + unsafe fn PromiseResolveNative(&self, cx: *mut jsapi::JSContext, p: &Promise, v: jsapi::JS::HandleValue) { p.resolve(cx, v); } #[allow(unsafe_code)] - unsafe fn PromiseRejectNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { + unsafe fn PromiseRejectNative(&self, cx: *mut jsapi::JSContext, p: &Promise, v: jsapi::JS::HandleValue) { p.reject(cx, v); } @@ -735,7 +745,7 @@ impl TestBindingMethods for TestBinding { } impl Callback for SimpleHandler { #[allow(unsafe_code)] - fn callback(&self, cx: *mut JSContext, v: HandleValue) { + fn callback(&self, cx: *mut jsapi::JSContext, v: jsapi::JS::HandleValue) { let global = unsafe { GlobalScope::from_context(cx) }; let _ = self.handler.Call_(&*global, v, ExceptionHandling::Report); } @@ -800,8 +810,8 @@ impl TestBinding { #[allow(unsafe_code)] impl TestBinding { - pub unsafe fn condition_satisfied(_: *mut JSContext, _: HandleObject) -> bool { true } - pub unsafe fn condition_unsatisfied(_: *mut JSContext, _: HandleObject) -> bool { false } + pub unsafe fn condition_satisfied(_: *mut jsapi::JSContext, _: jsapi::JS::HandleObject) -> bool { true } + pub unsafe fn condition_unsatisfied(_: *mut jsapi::JSContext, _: jsapi::JS::HandleObject) -> bool { false } } #[derive(HeapSizeOf, JSTraceable)] @@ -812,11 +822,13 @@ pub struct TestBindingCallback { } impl TestBindingCallback { - #[allow(unrooted_must_root)] + #[allow(unrooted_must_root, unsafe_code)] pub fn invoke(self) { let p = self.promise.root(); let cx = p.global().get_cx(); - let _ac = JSAutoCompartment::new(cx, p.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, p.reflector().get_jsobject().get()) + }; p.resolve_native(cx, &self.value); } } diff --git a/components/script/dom/textdecoder.rs b/components/script/dom/textdecoder.rs index e1b1edc10480..d1c4a71be083 100644 --- a/components/script/dom/textdecoder.rs +++ b/components/script/dom/textdecoder.rs @@ -12,7 +12,7 @@ use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use encoding::label::encoding_from_whatwg_label; use encoding::types::{DecoderTrap, EncodingRef}; -use js::jsapi::{JSContext, JSObject}; +use js::jsapi; use std::borrow::ToOwned; #[dom_struct] @@ -78,7 +78,7 @@ impl TextDecoderMethods for TextDecoder { #[allow(unsafe_code)] // https://encoding.spec.whatwg.org/#dom-textdecoder-decode - unsafe fn Decode(&self, _cx: *mut JSContext, input: Option<*mut JSObject>) + unsafe fn Decode(&self, _cx: *mut jsapi::JSContext, input: Option<*mut jsapi::JSObject>) -> Fallible { let input = match input { Some(input) => input, diff --git a/components/script/dom/textencoder.rs b/components/script/dom/textencoder.rs index fa527d710732..d07e6cdaa5e7 100644 --- a/components/script/dom/textencoder.rs +++ b/components/script/dom/textencoder.rs @@ -11,7 +11,7 @@ use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use js::jsapi::{JSContext, JSObject}; +use js::jsapi; use js::typedarray::{Uint8Array, CreateWith}; use std::ptr; @@ -47,11 +47,16 @@ impl TextEncoderMethods for TextEncoder { #[allow(unsafe_code)] // https://encoding.spec.whatwg.org/#dom-textencoder-encode - unsafe fn Encode(&self, cx: *mut JSContext, input: USVString) -> NonZero<*mut JSObject> { + unsafe fn Encode(&self, + cx: *mut jsapi::JSContext, + input: USVString) + -> NonZero<*mut jsapi::JSObject> { let encoded = input.0.as_bytes(); rooted!(in(cx) let mut js_object = ptr::null_mut()); - assert!(Uint8Array::create(cx, CreateWith::Slice(&encoded), js_object.handle_mut()).is_ok()); + assert!(Uint8Array::create(cx, + CreateWith::Slice(&encoded), + js_object.handle_mut()).is_ok()); NonZero::new_unchecked(js_object.get()) } diff --git a/components/script/dom/vrdisplay.rs b/components/script/dom/vrdisplay.rs index 853893047e08..494da8db6d5c 100644 --- a/components/script/dom/vrdisplay.rs +++ b/components/script/dom/vrdisplay.rs @@ -33,7 +33,7 @@ use dom::vrstageparameters::VRStageParameters; use dom::webglrenderingcontext::WebGLRenderingContext; use dom_struct::dom_struct; use ipc_channel::ipc::{self, IpcSender}; -use js::jsapi::JSContext; +use js::jsapi; use script_runtime::CommonScriptMsg; use script_runtime::ScriptThreadEventCategory::WebVREvent; use script_thread::Runnable; @@ -543,7 +543,7 @@ impl VRDisplay { api_sender.send_vr(WebVRCommand::Release(display_id)).unwrap(); } - // Only called when the JSContext is destroyed while presenting. + // Only called when the jsapi::JSContext is destroyed while presenting. // In this case we don't want to wait for WebVR Thread response. fn force_stop_present(&self) { self.webvr_thread().send(WebVRMsg::ExitPresent(self.global().pipeline_id(), @@ -643,7 +643,7 @@ fn parse_bounds(src: &Option>>, dst: &mut [f32; 4]) -> Result<() } } -fn validate_layer(cx: *mut JSContext, +fn validate_layer(cx: *mut jsapi::JSContext, layer: &VRLayer) -> Result<(WebVRLayer, Root), &'static str> { let ctx = layer.source.as_ref().map(|ref s| s.get_or_init_webgl_context(cx, None)).unwrap_or(None); diff --git a/components/script/dom/vreyeparameters.rs b/components/script/dom/vreyeparameters.rs index d77350ae1402..d50d40fa3769 100644 --- a/components/script/dom/vreyeparameters.rs +++ b/components/script/dom/vreyeparameters.rs @@ -11,7 +11,8 @@ use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::globalscope::GlobalScope; use dom::vrfieldofview::VRFieldOfView; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext, JSObject}; +use js; +use js::jsapi; use js::typedarray::{Float32Array, CreateWith}; use std::default::Default; use std::ptr; @@ -22,7 +23,7 @@ pub struct VREyeParameters { reflector_: Reflector, #[ignore_heap_size_of = "Defined in rust-webvr"] parameters: DOMRefCell, - offset: Heap<*mut JSObject>, + offset: js::heap::Heap<*mut jsapi::JSObject>, fov: JS, } @@ -33,7 +34,7 @@ impl VREyeParameters { VREyeParameters { reflector_: Reflector::new(), parameters: DOMRefCell::new(parameters), - offset: Heap::default(), + offset: js::heap::Heap::default(), fov: JS::from_ref(&*fov) } } @@ -60,7 +61,7 @@ impl VREyeParameters { impl VREyeParametersMethods for VREyeParameters { #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vreyeparameters-offset - unsafe fn Offset(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> { + unsafe fn Offset(&self, _cx: *mut jsapi::JSContext) -> NonZero<*mut jsapi::JSObject> { NonZero::new_unchecked(self.offset.get()) } diff --git a/components/script/dom/vrframedata.rs b/components/script/dom/vrframedata.rs index 70e238e9fb5f..b64b500f865a 100644 --- a/components/script/dom/vrframedata.rs +++ b/components/script/dom/vrframedata.rs @@ -13,7 +13,8 @@ use dom::globalscope::GlobalScope; use dom::vrpose::VRPose; use dom::window::Window; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext, JSObject}; +use js::heap::Heap; +use js::jsapi; use js::typedarray::{Float32Array, CreateWith}; use std::cell::Cell; use std::ptr; @@ -22,10 +23,10 @@ use webvr_traits::WebVRFrameData; #[dom_struct] pub struct VRFrameData { reflector_: Reflector, - left_proj: Heap<*mut JSObject>, - left_view: Heap<*mut JSObject>, - right_proj: Heap<*mut JSObject>, - right_view: Heap<*mut JSObject>, + left_proj: Heap<*mut jsapi::JSObject>, + left_view: Heap<*mut jsapi::JSObject>, + right_proj: Heap<*mut jsapi::JSObject>, + right_view: Heap<*mut jsapi::JSObject>, pose: JS, timestamp: Cell, first_timestamp: Cell @@ -72,7 +73,7 @@ impl VRFrameData { #[allow(unsafe_code)] -fn create_typed_array(cx: *mut JSContext, src: &[f32], dst: &Heap<*mut JSObject>) { +fn create_typed_array(cx: *mut jsapi::JSContext, src: &[f32], dst: &Heap<*mut jsapi::JSObject>) { rooted!(in (cx) let mut array = ptr::null_mut()); unsafe { let _ = Float32Array::create(cx, CreateWith::Slice(src), array.handle_mut()); @@ -118,25 +119,25 @@ impl VRFrameDataMethods for VRFrameData { #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrframedata-leftprojectionmatrix - unsafe fn LeftProjectionMatrix(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> { + unsafe fn LeftProjectionMatrix(&self, _cx: *mut jsapi::JSContext) -> NonZero<*mut jsapi::JSObject> { NonZero::new_unchecked(self.left_proj.get()) } #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrframedata-leftviewmatrix - unsafe fn LeftViewMatrix(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> { + unsafe fn LeftViewMatrix(&self, _cx: *mut jsapi::JSContext) -> NonZero<*mut jsapi::JSObject> { NonZero::new_unchecked(self.left_view.get()) } #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrframedata-rightprojectionmatrix - unsafe fn RightProjectionMatrix(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> { + unsafe fn RightProjectionMatrix(&self, _cx: *mut jsapi::JSContext) -> NonZero<*mut jsapi::JSObject> { NonZero::new_unchecked(self.right_proj.get()) } #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrframedata-rightviewmatrix - unsafe fn RightViewMatrix(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> { + unsafe fn RightViewMatrix(&self, _cx: *mut jsapi::JSContext) -> NonZero<*mut jsapi::JSObject> { NonZero::new_unchecked(self.right_view.get()) } diff --git a/components/script/dom/vrpose.rs b/components/script/dom/vrpose.rs index 539a42e5e3bc..81397619c5bb 100644 --- a/components/script/dom/vrpose.rs +++ b/components/script/dom/vrpose.rs @@ -9,7 +9,8 @@ use dom::bindings::js::Root; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext, JSObject}; +use js::heap::Heap; +use js::jsapi; use js::typedarray::{Float32Array, CreateWith}; use std::ptr; use webvr_traits::webvr; @@ -17,18 +18,18 @@ use webvr_traits::webvr; #[dom_struct] pub struct VRPose { reflector_: Reflector, - position: Heap<*mut JSObject>, - orientation: Heap<*mut JSObject>, - linear_vel: Heap<*mut JSObject>, - angular_vel: Heap<*mut JSObject>, - linear_acc: Heap<*mut JSObject>, - angular_acc: Heap<*mut JSObject>, + position: Heap<*mut jsapi::JSObject>, + orientation: Heap<*mut jsapi::JSObject>, + linear_vel: Heap<*mut jsapi::JSObject>, + angular_vel: Heap<*mut jsapi::JSObject>, + linear_acc: Heap<*mut jsapi::JSObject>, + angular_acc: Heap<*mut jsapi::JSObject>, } #[allow(unsafe_code)] -unsafe fn update_or_create_typed_array(cx: *mut JSContext, +unsafe fn update_or_create_typed_array(cx: *mut jsapi::JSContext, src: Option<&[f32]>, - dst: &Heap<*mut JSObject>) { + dst: &Heap<*mut jsapi::JSObject>) { match src { Some(data) => { if dst.get().is_null() { @@ -52,7 +53,7 @@ unsafe fn update_or_create_typed_array(cx: *mut JSContext, #[inline] #[allow(unsafe_code)] -fn heap_to_option(heap: &Heap<*mut JSObject>) -> Option> { +fn heap_to_option(heap: &Heap<*mut jsapi::JSObject>) -> Option> { let js_object = heap.get(); if js_object.is_null() { None @@ -101,37 +102,37 @@ impl VRPose { impl VRPoseMethods for VRPose { #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-position - unsafe fn GetPosition(&self, _cx: *mut JSContext) -> Option> { + unsafe fn GetPosition(&self, _cx: *mut jsapi::JSContext) -> Option> { heap_to_option(&self.position) } #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-linearvelocity - unsafe fn GetLinearVelocity(&self, _cx: *mut JSContext) -> Option> { + unsafe fn GetLinearVelocity(&self, _cx: *mut jsapi::JSContext) -> Option> { heap_to_option(&self.linear_vel) } #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-linearacceleration - unsafe fn GetLinearAcceleration(&self, _cx: *mut JSContext) -> Option> { + unsafe fn GetLinearAcceleration(&self, _cx: *mut jsapi::JSContext) -> Option> { heap_to_option(&self.linear_acc) } #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-orientation - unsafe fn GetOrientation(&self, _cx: *mut JSContext) -> Option> { + unsafe fn GetOrientation(&self, _cx: *mut jsapi::JSContext) -> Option> { heap_to_option(&self.orientation) } #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-angularvelocity - unsafe fn GetAngularVelocity(&self, _cx: *mut JSContext) -> Option> { + unsafe fn GetAngularVelocity(&self, _cx: *mut jsapi::JSContext) -> Option> { heap_to_option(&self.angular_vel) } #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrpose-angularacceleration - unsafe fn GetAngularAcceleration(&self, _cx: *mut JSContext) -> Option> { + unsafe fn GetAngularAcceleration(&self, _cx: *mut jsapi::JSContext) -> Option> { heap_to_option(&self.angular_acc) } } diff --git a/components/script/dom/vrstageparameters.rs b/components/script/dom/vrstageparameters.rs index 7bfaa95ea76d..36ed975aa193 100644 --- a/components/script/dom/vrstageparameters.rs +++ b/components/script/dom/vrstageparameters.rs @@ -11,7 +11,8 @@ use dom::bindings::num::Finite; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSContext, JSObject}; +use js; +use js::jsapi; use js::typedarray::{Float32Array, CreateWith}; use std::ptr; use webvr_traits::WebVRStageParameters; @@ -21,7 +22,7 @@ pub struct VRStageParameters { reflector_: Reflector, #[ignore_heap_size_of = "Defined in rust-webvr"] parameters: DOMRefCell, - transform: Heap<*mut JSObject>, + transform: js::heap::Heap<*mut jsapi::JSObject>, } unsafe_no_jsmanaged_fields!(WebVRStageParameters); @@ -31,7 +32,7 @@ impl VRStageParameters { VRStageParameters { reflector_: Reflector::new(), parameters: DOMRefCell::new(parameters), - transform: Heap::default() + transform: js::heap::Heap::default() } } @@ -69,7 +70,7 @@ impl VRStageParameters { impl VRStageParametersMethods for VRStageParameters { #[allow(unsafe_code)] // https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform - unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> { + unsafe fn SittingToStandingTransform(&self, _cx: *mut jsapi::JSContext) -> NonZero<*mut jsapi::JSObject> { NonZero::new_unchecked(self.transform.get()) } diff --git a/components/script/dom/webgl_extensions/ext/oesvertexarrayobject.rs b/components/script/dom/webgl_extensions/ext/oesvertexarrayobject.rs index 48385a3d50fa..6ad512935bd6 100644 --- a/components/script/dom/webgl_extensions/ext/oesvertexarrayobject.rs +++ b/components/script/dom/webgl_extensions/ext/oesvertexarrayobject.rs @@ -11,8 +11,8 @@ use dom::webglrenderingcontext::WebGLRenderingContext; use dom::webglvertexarrayobjectoes::WebGLVertexArrayObjectOES; use dom_struct::dom_struct; use js::conversions::ToJSValConvertible; -use js::jsapi::JSContext; -use js::jsval::{JSVal, NullValue}; +use js::jsapi; +use js::jsval::NullValue; use std::iter; use super::{WebGLExtension, WebGLExtensions}; @@ -33,7 +33,7 @@ impl OESVertexArrayObject { } #[allow(unsafe_code)] - fn get_current_binding(&self, cx:*mut JSContext) -> JSVal { + fn get_current_binding(&self, cx:*mut jsapi::JSContext) -> jsapi::JS::Value { rooted!(in(cx) let mut rval = NullValue()); if let Some(bound_vao) = self.bound_vao.get() { unsafe { diff --git a/components/script/dom/webgl_extensions/extensions.rs b/components/script/dom/webgl_extensions/extensions.rs index 62ee5f260864..764010b47cbe 100644 --- a/components/script/dom/webgl_extensions/extensions.rs +++ b/components/script/dom/webgl_extensions/extensions.rs @@ -15,8 +15,7 @@ use dom::webglrenderingcontext::WebGLRenderingContext; use fnv::{FnvHashMap, FnvHashSet}; use gleam::gl::GLenum; use heapsize::HeapSizeOf; -use js::jsapi::{JSContext, JSObject}; -use js::jsval::JSVal; +use js::jsapi; use ref_filter_map::ref_filter_map; use std::cell::Ref; use std::collections::HashMap; @@ -109,7 +108,10 @@ impl WebGLExtensions { .collect() } - pub fn get_or_init_extension(&self, name: &str, ctx: &WebGLRenderingContext) -> Option> { + pub fn get_or_init_extension(&self, + name: &str, + ctx: &WebGLRenderingContext) + -> Option> { let name = name.to_uppercase(); self.extensions.borrow().get(&name).and_then(|extension| { if extension.is_supported(self) { @@ -227,8 +229,8 @@ impl WebGLExtensions { #[derive(Eq, Hash, HeapSizeOf, JSTraceable, PartialEq)] struct TexFormatType(u32, u32); -type WebGLQueryParameterFunc = Fn(*mut JSContext, &WebGLRenderingContext) - -> Result; +type WebGLQueryParameterFunc = Fn(*mut jsapi::JSContext, &WebGLRenderingContext) + -> Result; #[derive(HeapSizeOf)] struct WebGLQueryParameterHandler { diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index ed5ff53bfe71..bcdf3e5d3828 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -47,8 +47,8 @@ use euclid::Size2D; use fnv::FnvHashMap; use half::f16; use js::conversions::ConversionBehavior; -use js::jsapi::{JSContext, JSObject, Type, Rooted}; -use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UndefinedValue}; +use js::jsapi; +use js::jsval::{BooleanValue, DoubleValue, Int32Value, NullValue, UndefinedValue}; use js::typedarray::{TypedArray, TypedArrayElement, Float32, Int32}; use net_traits::image::base::PixelFormat; use net_traits::image_cache::ImageResponse; @@ -756,8 +756,8 @@ impl WebGLRenderingContext { format: TexFormat, data_type: TexDataType, unpacking_alignment: u32, - data: *mut JSObject, - cx: *mut JSContext) + data: *mut jsapi::JSObject, + cx: *mut jsapi::JSContext) -> Result { let element_size = data_type.element_size(); let components_per_element = data_type.components_per_element(); @@ -1092,12 +1092,12 @@ impl Drop for WebGLRenderingContext { } // FIXME: After [1] lands and the relevant Servo and codegen PR too, we should -// convert all our raw JSObject pointers to proper types. +// convert all our raw jsapi::JSObject pointers to proper types. // // [1]: https://github.com/servo/rust-mozjs/pull/304 #[allow(unsafe_code)] -unsafe fn typed_array_or_sequence_to_vec(cx: *mut JSContext, - sequence_or_abv: *mut JSObject, +unsafe fn typed_array_or_sequence_to_vec(cx: *mut jsapi::JSContext, + sequence_or_abv: *mut jsapi::JSObject, config: ::Config) -> Result, Error> where T: TypedArrayElement, @@ -1105,7 +1105,7 @@ unsafe fn typed_array_or_sequence_to_vec(cx: *mut JSContext, ::Config: Clone, { // TODO(servo/rust-mozjs#330): replace this with a macro that supports generic types. - let mut typed_array_root = Rooted::new_unrooted(); + let mut typed_array_root = jsapi::JS::Rooted::new_unrooted(); let typed_array: Option> = TypedArray::from(cx, &mut typed_array_root, sequence_or_abv).ok(); if let Some(mut typed_array) = typed_array { @@ -1125,7 +1125,9 @@ unsafe fn typed_array_or_sequence_to_vec(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe fn fallible_array_buffer_view_to_vec(cx: *mut JSContext, abv: *mut JSObject) -> Result, Error> +unsafe fn fallible_array_buffer_view_to_vec(cx: *mut jsapi::JSContext, + abv: *mut jsapi::JSObject) + -> Result, Error> { assert!(!abv.is_null()); typedarray!(in(cx) let array_buffer_view: ArrayBufferView = abv); @@ -1169,7 +1171,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - unsafe fn GetBufferParameter(&self, _cx: *mut JSContext, target: u32, parameter: u32) -> JSVal { + unsafe fn GetBufferParameter(&self, _cx: *mut jsapi::JSContext, target: u32, parameter: u32) -> jsapi::JS::Value { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetBufferParameter(target, parameter, sender)); @@ -1185,7 +1187,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - unsafe fn GetParameter(&self, cx: *mut JSContext, parameter: u32) -> JSVal { + unsafe fn GetParameter(&self, cx: *mut jsapi::JSContext, parameter: u32) -> jsapi::JS::Value { // Handle the GL_*_BINDING without going all the way // to the GL, since we would just need to map back from GL's // returned ID to the WebGL* object we're tracking. @@ -1312,8 +1314,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 - unsafe fn GetExtension(&self, _cx: *mut JSContext, name: DOMString) - -> Option> { + unsafe fn GetExtension(&self, + _cx: *mut jsapi::JSContext, + name: DOMString) + -> Option> { self.extension_manager.init_once(|| { self.get_gl_extensions() }); @@ -1514,7 +1518,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - unsafe fn BufferData(&self, cx: *mut JSContext, target: u32, data: *mut JSObject, usage: u32) -> Fallible<()> { + unsafe fn BufferData(&self, + cx: *mut jsapi::JSContext, + target: u32, + data: *mut jsapi::JSObject, + usage: u32) + -> Fallible<()> { if data.is_null() { return Ok(self.webgl_error(InvalidValue)); } @@ -1582,7 +1591,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - unsafe fn BufferSubData(&self, cx: *mut JSContext, target: u32, offset: i64, data: *mut JSObject) -> Fallible<()> { + unsafe fn BufferSubData(&self, + cx: *mut jsapi::JSContext, + target: u32, + offset: i64, + data: *mut jsapi::JSObject) + -> Fallible<()> { if data.is_null() { return Ok(self.webgl_error(InvalidValue)); } @@ -1618,8 +1632,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - unsafe fn CompressedTexImage2D(&self, cx: *mut JSContext, _target: u32, _level: i32, _internal_format: u32, - _width: i32, _height: i32, _border: i32, pixels: *mut JSObject) -> Fallible<()> { + unsafe fn CompressedTexImage2D(&self, cx: *mut jsapi::JSContext, _target: u32, _level: i32, _internal_format: u32, + _width: i32, _height: i32, _border: i32, pixels: *mut jsapi::JSObject) -> Fallible<()> { let _data = fallible_array_buffer_view_to_vec(cx, pixels)?; // FIXME: No compressed texture format is currently supported, so error out as per // https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT @@ -1629,9 +1643,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - unsafe fn CompressedTexSubImage2D(&self, cx: *mut JSContext, _target: u32, _level: i32, + unsafe fn CompressedTexSubImage2D(&self, cx: *mut jsapi::JSContext, _target: u32, _level: i32, _xoffset: i32, _yoffset: i32, _width: i32, _height: i32, - _format: u32, pixels: *mut JSObject) -> Fallible<()> { + _format: u32, pixels: *mut jsapi::JSObject) -> Fallible<()> { let _data = fallible_array_buffer_view_to_vec(cx, pixels)?; // FIXME: No compressed texture format is currently supported, so error out as per // https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT @@ -2171,7 +2185,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - unsafe fn GetProgramParameter(&self, _: *mut JSContext, program: Option<&WebGLProgram>, param_id: u32) -> JSVal { + unsafe fn GetProgramParameter(&self, + _: *mut jsapi::JSContext, + program: Option<&WebGLProgram>, + param_id: u32) + -> jsapi::JS::Value { if let Some(program) = program { match handle_potential_webgl_error!(self, program.parameter(param_id), WebGLParameter::Invalid) { WebGLParameter::Int(val) => Int32Value(val), @@ -2195,9 +2213,15 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - unsafe fn GetShaderParameter(&self, _: *mut JSContext, shader: Option<&WebGLShader>, param_id: u32) -> JSVal { + unsafe fn GetShaderParameter(&self, + _: *mut jsapi::JSContext, + shader: Option<&WebGLShader>, + param_id: u32) + -> jsapi::JS::Value { if let Some(shader) = shader { - match handle_potential_webgl_error!(self, shader.parameter(param_id), WebGLParameter::Invalid) { + match handle_potential_webgl_error!(self, + shader.parameter(param_id), + WebGLParameter::Invalid) { WebGLParameter::Int(val) => Int32Value(val), WebGLParameter::Bool(val) => BooleanValue(val), WebGLParameter::String(_) => panic!("Shader parameter should not be string"), @@ -2245,7 +2269,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - unsafe fn GetVertexAttrib(&self, cx: *mut JSContext, index: u32, pname: u32) -> JSVal { + unsafe fn GetVertexAttrib(&self, cx: *mut jsapi::JSContext, index: u32, pname: u32) -> jsapi::JS::Value { if index == 0 && pname == constants::CURRENT_VERTEX_ATTRIB { rooted!(in(cx) let mut result = UndefinedValue()); let (x, y, z, w) = self.current_vertex_attrib_0.get(); @@ -2413,8 +2437,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.12 - unsafe fn ReadPixels(&self, cx: *mut JSContext, x: i32, y: i32, width: i32, height: i32, - format: u32, pixel_type: u32, pixels: *mut JSObject) -> Fallible<()> { + unsafe fn ReadPixels(&self, cx: *mut jsapi::JSContext, x: i32, y: i32, width: i32, height: i32, + format: u32, pixel_type: u32, pixels: *mut jsapi::JSObject) -> Fallible<()> { if pixels.is_null() { return Ok(self.webgl_error(InvalidValue)); } @@ -2430,7 +2454,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } match array_type { - Type::Uint8 => (), + jsapi::js::Scalar::Type::Uint8 => (), _ => return Ok(self.webgl_error(InvalidOperation)), } @@ -2644,9 +2668,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform1iv(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, uniform: Option<&WebGLUniformLocation>, - data: *mut JSObject) -> Fallible<()> { + data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default)?; @@ -2660,9 +2684,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform1fv(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, uniform: Option<&WebGLUniformLocation>, - data: *mut JSObject) -> Fallible<()> { + data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ())?; @@ -2685,9 +2709,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform2fv(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, uniform: Option<&WebGLUniformLocation>, - data: *mut JSObject) -> Fallible<()> { + data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ())?; @@ -2714,9 +2738,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform2iv(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, uniform: Option<&WebGLUniformLocation>, - data: *mut JSObject) -> Fallible<()> { + data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default)?; @@ -2743,9 +2767,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform3fv(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, uniform: Option<&WebGLUniformLocation>, - data: *mut JSObject) -> Fallible<()> { + data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ())?; @@ -2772,9 +2796,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform3iv(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, uniform: Option<&WebGLUniformLocation>, - data: *mut JSObject) -> Fallible<()> { + data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default)?; @@ -2802,9 +2826,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform4iv(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, uniform: Option<&WebGLUniformLocation>, - data: *mut JSObject) -> Fallible<()> { + data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ConversionBehavior::Default)?; @@ -2831,9 +2855,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform4fv(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, uniform: Option<&WebGLUniformLocation>, - data: *mut JSObject) -> Fallible<()> { + data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ())?; @@ -2849,10 +2873,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn UniformMatrix2fv(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, uniform: Option<&WebGLUniformLocation>, transpose: bool, - data: *mut JSObject) -> Fallible<()> { + data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ())?; if self.validate_uniform_parameters(uniform, @@ -2867,10 +2891,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn UniformMatrix3fv(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, uniform: Option<&WebGLUniformLocation>, transpose: bool, - data: *mut JSObject) -> Fallible<()> { + data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ())?; if self.validate_uniform_parameters(uniform, @@ -2885,10 +2909,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn UniformMatrix4fv(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, uniform: Option<&WebGLUniformLocation>, transpose: bool, - data: *mut JSObject) -> Fallible<()> { + data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ())?; if self.validate_uniform_parameters(uniform, @@ -2926,7 +2950,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - unsafe fn VertexAttrib1fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { + unsafe fn VertexAttrib1fv(&self, cx: *mut jsapi::JSContext, indx: u32, data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ())?; if data_vec.len() < 1 { @@ -2943,7 +2967,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - unsafe fn VertexAttrib2fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { + unsafe fn VertexAttrib2fv(&self, cx: *mut jsapi::JSContext, indx: u32, data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ())?; if data_vec.len() < 2 { @@ -2960,7 +2984,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - unsafe fn VertexAttrib3fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { + unsafe fn VertexAttrib3fv(&self, cx: *mut jsapi::JSContext, indx: u32, data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ())?; if data_vec.len() < 3 { @@ -2977,7 +3001,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] - unsafe fn VertexAttrib4fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { + unsafe fn VertexAttrib4fv(&self, cx: *mut jsapi::JSContext, indx: u32, data: *mut jsapi::JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = typed_array_or_sequence_to_vec::(cx, data, ())?; if data_vec.len() < 4 { @@ -3046,7 +3070,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 #[allow(unsafe_code)] unsafe fn TexImage2D(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, target: u32, level: i32, internal_format: u32, @@ -3055,7 +3079,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { border: i32, format: u32, data_type: u32, - data_ptr: *mut JSObject) -> Fallible<()> { + data_ptr: *mut jsapi::JSObject) -> Fallible<()> { if !self.extension_manager.is_tex_type_enabled(data_type) { return Ok(self.webgl_error(InvalidEnum)); } @@ -3177,7 +3201,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 #[allow(unsafe_code)] unsafe fn TexSubImage2D(&self, - cx: *mut JSContext, + cx: *mut jsapi::JSContext, target: u32, level: i32, xoffset: i32, @@ -3186,7 +3210,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { height: i32, format: u32, data_type: u32, - data_ptr: *mut JSObject) -> Fallible<()> { + data_ptr: *mut jsapi::JSObject) -> Fallible<()> { let data = if data_ptr.is_null() { None } else { diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index 5aab5496fd5d..86df9fdab9f0 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -24,7 +24,7 @@ use dom::messageevent::MessageEvent; use dom::urlhelper::UrlHelper; use dom_struct::dom_struct; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; -use js::jsapi::JSAutoCompartment; +use js; use js::jsval::UndefinedValue; use js::typedarray::{ArrayBuffer, CreateWith}; use net_traits::{WebSocketCommunicate, WebSocketConnectData, WebSocketDomAction, WebSocketNetworkEvent}; @@ -502,10 +502,10 @@ impl Runnable for MessageReceivedTask { // Step 2-5. let global = ws.global(); - // global.get_cx() returns a valid `JSContext` pointer, so this is safe. + // global.get_cx() returns a valid `jsapi::JSContext` pointer, so this is safe. unsafe { let cx = global.get_cx(); - let _ac = JSAutoCompartment::new(cx, ws.reflector().get_jsobject().get()); + let _ac = js::ac::AutoCompartment::with_obj(cx, ws.reflector().get_jsobject().get()); rooted!(in(cx) let mut message = UndefinedValue()); match self.message { MessageData::Text(text) => text.to_jsval(cx, message.handle_mut()), diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 960a8c683b86..637fdccdf81c 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -57,8 +57,8 @@ use euclid::{Point2D, Vector2D, Rect, Size2D}; use fetch; use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::router::ROUTER; -use js::jsapi::{HandleObject, HandleValue, JSAutoCompartment, JSContext}; -use js::jsapi::{JS_GC, JS_GetRuntime}; +use js; +use js::jsapi; use js::jsval::UndefinedValue; use js::rust::Runtime; use layout_image::fetch_image_for_layout; @@ -307,7 +307,7 @@ impl Window { self.globalscope.origin() } - pub fn get_cx(&self) -> *mut JSContext { + pub fn get_cx(&self) -> *mut jsapi::JSContext { self.js_runtime.borrow().as_ref().unwrap().cx() } @@ -616,8 +616,8 @@ impl WindowMethods for Window { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, - args: Vec) -> i32 { + unsafe fn SetTimeout(&self, _cx: *mut jsapi::JSContext, callback: Rc, timeout: i32, + args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, @@ -627,8 +627,8 @@ impl WindowMethods for Window { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, - timeout: i32, args: Vec) -> i32 { + unsafe fn SetTimeout_(&self, _cx: *mut jsapi::JSContext, callback: DOMString, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, @@ -643,8 +643,8 @@ impl WindowMethods for Window { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval(&self, _cx: *mut JSContext, callback: Rc, - timeout: i32, args: Vec) -> i32 { + unsafe fn SetInterval(&self, _cx: *mut jsapi::JSContext, callback: Rc, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, @@ -654,8 +654,8 @@ impl WindowMethods for Window { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, - timeout: i32, args: Vec) -> i32 { + unsafe fn SetInterval_(&self, _cx: *mut jsapi::JSContext, callback: DOMString, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, @@ -754,8 +754,8 @@ impl WindowMethods for Window { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-window-postmessage unsafe fn PostMessage(&self, - cx: *mut JSContext, - message: HandleValue, + cx: *mut jsapi::JSContext, + message: jsapi::JS::HandleValue, origin: DOMString) -> ErrorResult { // Step 3-5. @@ -799,7 +799,7 @@ impl WindowMethods for Window { #[allow(unsafe_code)] fn Gc(&self) { unsafe { - JS_GC(JS_GetRuntime(self.get_cx())); + jsapi::JS_GC(js::rust::Runtime::get()); } } @@ -809,7 +809,7 @@ impl WindowMethods for Window { } #[allow(unsafe_code)] - unsafe fn WebdriverCallback(&self, cx: *mut JSContext, val: HandleValue) { + unsafe fn WebdriverCallback(&self, cx: *mut jsapi::JSContext, val: jsapi::JS::HandleValue) { let rv = jsval_to_webdriver(cx, val); let opt_chan = self.webdriver_script_chan.borrow_mut().take(); if let Some(chan) = opt_chan { @@ -1285,9 +1285,9 @@ impl Window { for image in complete.pending_images { let id = image.id; - let js_runtime = self.js_runtime.borrow(); - let js_runtime = js_runtime.as_ref().unwrap(); - let node = unsafe { from_untrusted_node_address(js_runtime.rt(), image.node) }; + let node = unsafe { + from_untrusted_node_address(image.node) + }; if let PendingImageState::Unrequested(ref url) = image.state { fetch_image_for_layout(url.clone(), &*node, id, self.image_cache.clone()); @@ -1506,10 +1506,8 @@ impl Window { } let response = self.layout_rpc.offset_parent(); - let js_runtime = self.js_runtime.borrow(); - let js_runtime = js_runtime.as_ref().unwrap(); let element = response.node_address.and_then(|parent_node_address| { - let node = unsafe { from_untrusted_node_address(js_runtime.rt(), parent_node_address) }; + let node = unsafe { from_untrusted_node_address(parent_node_address) }; Root::downcast(node) }); (element, response.rect) @@ -1743,7 +1741,7 @@ impl Window { /// Returns whether mozbrowser is enabled and `obj` has been created /// in a top-level `Window` global. #[allow(unsafe_code)] - pub unsafe fn global_is_mozbrowser(_: *mut JSContext, obj: HandleObject) -> bool { + pub unsafe fn global_is_mozbrowser(_: *mut jsapi::JSContext, obj: jsapi::JS::HandleObject) -> bool { GlobalScope::from_object(obj.get()) .downcast::() .map_or(false, |window| window.is_mozbrowser()) @@ -1986,6 +1984,7 @@ impl PostMessageHandler { impl Runnable for PostMessageHandler { // https://html.spec.whatwg.org/multipage/#dom-window-postmessage steps 10-12. + #[allow(unsafe_code)] fn handler(self: Box) { let this = *self; let window = this.destination.root(); @@ -2000,7 +1999,9 @@ impl Runnable for PostMessageHandler { let cx = window.get_cx(); let globalhandle = window.reflector().get_jsobject(); - let _ac = JSAutoCompartment::new(cx, globalhandle.get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, globalhandle.get()) + }; rooted!(in(cx) let mut message = UndefinedValue()); this.message.read(window.upcast(), message.handle_mut()); diff --git a/components/script/dom/windowproxy.rs b/components/script/dom/windowproxy.rs index 2578bb3b46c6..af4ff8064c7a 100644 --- a/components/script/dom/windowproxy.rs +++ b/components/script/dom/windowproxy.rs @@ -15,19 +15,10 @@ use dom::element::Element; use dom::globalscope::GlobalScope; use dom::window::Window; use dom_struct::dom_struct; -use js::JSCLASS_IS_GLOBAL; +use js; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; -use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra}; -use js::jsapi::{Handle, HandleId, HandleObject, HandleValue}; -use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject}; -use js::jsapi::{JSPROP_READONLY, JSTracer, JS_DefinePropertyById}; -use js::jsapi::{JS_ForwardGetPropertyTo, JS_ForwardSetPropertyTo}; -use js::jsapi::{JS_GetOwnPropertyDescriptorById, JS_HasPropertyById, JS_HasOwnPropertyById}; -use js::jsapi::{JS_IsExceptionPending, JS_TransplantObject, SetWindowProxy}; -use js::jsapi::{MutableHandle, MutableHandleObject, MutableHandleValue}; -use js::jsapi::{ObjectOpResult, PropertyDescriptor}; -use js::jsval::{UndefinedValue, PrivateValue}; -use js::rust::get_object_class; +use js::glue::{GetProxyPrivate, SetProxyReservedSlot, GetProxyReservedSlot}; +use js::jsapi; use msg::constellation_msg::BrowsingContextId; use msg::constellation_msg::PipelineId; use msg::constellation_msg::TopLevelBrowsingContextId; @@ -106,8 +97,8 @@ impl WindowProxy { let cx = window.get_cx(); let window_jsobject = window.reflector().get_jsobject(); assert!(!window_jsobject.get().is_null()); - assert!(((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL) != 0); - let _ac = JSAutoCompartment::new(cx, window_jsobject.get()); + assert!(js::rust::is_global(window_jsobject.get())); + let _ac = js::ac::AutoCompartment::with_obj(cx, window_jsobject.get()); // Create a new window proxy. rooted!(in(cx) let js_proxy = NewWindowProxy(cx, window_jsobject, handler)); @@ -123,10 +114,11 @@ impl WindowProxy { // The window proxy owns the browsing context. // When we finalize the window proxy, it drops the browsing context it owns. - SetProxyExtra(js_proxy.get(), 0, &PrivateValue((&*window_proxy).as_void_ptr())); + let private = js::jsval::PrivateValue((&*window_proxy).as_void_ptr()); + SetProxyReservedSlot(js_proxy.get(), 0, &private as *const _); // Notify the JS engine about the new window proxy binding. - SetWindowProxy(cx, window_jsobject, js_proxy.handle()); + jsapi::js::SetWindowProxy(cx, window_jsobject, js_proxy.handle()); // Set the reflector. debug!("Initializing reflector of {:p} to {:p}.", window_proxy, js_proxy.get()); @@ -159,8 +151,8 @@ impl WindowProxy { let window = DissimilarOriginWindow::new(global_to_clone_from, &*window_proxy); let window_jsobject = window.reflector().get_jsobject(); assert!(!window_jsobject.get().is_null()); - assert!(((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL) != 0); - let _ac = JSAutoCompartment::new(cx, window_jsobject.get()); + assert!(js::rust::is_global(window_jsobject.get())); + let _ac = js::ac::AutoCompartment::with_obj(cx, window_jsobject.get()); // Create a new window proxy. rooted!(in(cx) let js_proxy = NewWindowProxy(cx, window_jsobject, handler)); @@ -168,10 +160,12 @@ impl WindowProxy { // The window proxy owns the browsing context. // When we finalize the window proxy, it drops the browsing context it owns. - SetProxyExtra(js_proxy.get(), 0, &PrivateValue((&*window_proxy).as_void_ptr())); + SetProxyReservedSlot(js_proxy.get(), + 0, + &js::jsval::PrivateValue((&*window_proxy).as_void_ptr())); // Notify the JS engine about the new window proxy binding. - SetWindowProxy(cx, window_jsobject, js_proxy.handle()); + jsapi::js::SetWindowProxy(cx, window_jsobject, js_proxy.handle()); // Set the reflector. debug!("Initializing reflector of {:p} to {:p}.", window_proxy, js_proxy.get()); @@ -226,29 +220,31 @@ impl WindowProxy { let window_jsobject = window.reflector().get_jsobject(); let old_js_proxy = self.reflector.get_jsobject(); assert!(!window_jsobject.get().is_null()); - assert!(((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL) != 0); - let _ac = JSAutoCompartment::new(cx, window_jsobject.get()); + assert!(js::rust::is_global(window_jsobject.get())); + let _ac = js::ac::AutoCompartment::with_obj(cx, window_jsobject.get()); // The old window proxy no longer owns this browsing context. - SetProxyExtra(old_js_proxy.get(), 0, &PrivateValue(ptr::null_mut())); + SetProxyReservedSlot(old_js_proxy.get(), 0, &js::jsval::PrivateValue(ptr::null_mut())); // Brain transpant the window proxy. // We need to do this, because the Window and WindowProxy // objects need to be in the same compartment. - // JS_TransplantObject does this by copying the contents + // jsapi::JS_TransplantObject does this by copying the contents // of the old window proxy to the new window proxy, then // making the old window proxy a cross-compartment wrapper // pointing to the new window proxy. rooted!(in(cx) let new_js_proxy = NewWindowProxy(cx, window_jsobject, handler)); debug!("Transplanting proxy from {:p} to {:p}.", old_js_proxy.get(), new_js_proxy.get()); - rooted!(in(cx) let new_js_proxy = JS_TransplantObject(cx, old_js_proxy, new_js_proxy.handle())); + rooted!(in(cx) let new_js_proxy = jsapi::JS_TransplantObject(cx, old_js_proxy, new_js_proxy.handle())); debug!("Transplanted proxy is {:p}.", new_js_proxy.get()); // Transfer ownership of this browsing context from the old window proxy to the new one. - SetProxyExtra(new_js_proxy.get(), 0, &PrivateValue(self.as_void_ptr())); + SetProxyReservedSlot(new_js_proxy.get(), + 0, + &js::jsval::PrivateValue(self.as_void_ptr())); // Notify the JS engine about the new window proxy binding. - SetWindowProxy(cx, window_jsobject, new_js_proxy.handle()); + jsapi::js::SetWindowProxy(cx, window_jsobject, new_js_proxy.handle()); // Update the reflector. debug!("Setting reflector of {:p} to {:p}.", self, new_js_proxy.get()); @@ -275,9 +271,9 @@ impl WindowProxy { } #[allow(unsafe_code)] -unsafe fn GetSubframeWindow(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId) +unsafe fn GetSubframeWindow(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId) -> Option> { let index = get_array_index_from_id(cx, id); if let Some(index) = index { @@ -291,22 +287,22 @@ unsafe fn GetSubframeWindow(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId, - mut desc: MutableHandle) +unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, + mut desc: jsapi::JS::MutableHandle) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { - rooted!(in(cx) let mut val = UndefinedValue()); + rooted!(in(cx) let mut val = js::jsval::UndefinedValue()); window.to_jsval(cx, val.handle_mut()); desc.value = val.get(); - fill_property_descriptor(desc, proxy.get(), JSPROP_READONLY); + fill_property_descriptor(desc, proxy.get(), jsapi::JSPROP_READONLY as _); return true; } rooted!(in(cx) let target = GetProxyPrivate(proxy.get()).to_object()); - if !JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) { + if !jsapi::JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) { return false; } @@ -320,29 +316,29 @@ unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn defineProperty(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId, - desc: Handle, - res: *mut ObjectOpResult) +unsafe extern "C" fn defineProperty(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, + desc: jsapi::JS::Handle, + res: *mut jsapi::JS::ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Spec says to Reject whether this is a supported index or not, // since we have no indexed setter or indexed creator. That means // throwing in strict mode (FIXME: Bug 828137), doing nothing in // non-strict mode. - (*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t; + (*res).code_ = jsapi::JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); - JS_DefinePropertyById(cx, target.handle(), id, desc, res) + jsapi::JS_DefinePropertyById(cx, target.handle(), id, desc, res) } #[allow(unsafe_code)] -unsafe extern "C" fn has(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId, +unsafe extern "C" fn has(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, bp: *mut bool) -> bool { let window = GetSubframeWindow(cx, proxy, id); @@ -353,7 +349,7 @@ unsafe extern "C" fn has(cx: *mut JSContext, rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); let mut found = false; - if !JS_HasPropertyById(cx, target.handle(), id, &mut found) { + if !jsapi::JS_HasPropertyById(cx, target.handle(), id, &mut found) { return false; } @@ -362,11 +358,11 @@ unsafe extern "C" fn has(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn get(cx: *mut JSContext, - proxy: HandleObject, - receiver: HandleValue, - id: HandleId, - vp: MutableHandleValue) +unsafe extern "C" fn get(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + receiver: jsapi::JS::HandleValue, + id: jsapi::JS::HandleId, + vp: jsapi::JS::MutableHandleValue) -> bool { let window = GetSubframeWindow(cx, proxy, id); if let Some(window) = window { @@ -375,25 +371,25 @@ unsafe extern "C" fn get(cx: *mut JSContext, } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); - JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp) + jsapi::JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp) } #[allow(unsafe_code)] -unsafe extern "C" fn set(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId, - v: HandleValue, - receiver: HandleValue, - res: *mut ObjectOpResult) +unsafe extern "C" fn set(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, + v: jsapi::JS::HandleValue, + receiver: jsapi::JS::HandleValue, + res: *mut jsapi::JS::ObjectOpResult) -> bool { if get_array_index_from_id(cx, id).is_some() { // Reject (which means throw if and only if strict) the set. - (*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t; + (*res).code_ = jsapi::JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t; return true; } rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); - JS_ForwardSetPropertyTo(cx, + jsapi::JS_ForwardSetPropertyTo(cx, target.handle(), id, v, @@ -402,10 +398,10 @@ unsafe extern "C" fn set(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext, - _: HandleObject, +unsafe extern "C" fn get_prototype_if_ordinary(_: *mut jsapi::JSContext, + _: jsapi::JS::HandleObject, is_ordinary: *mut bool, - _: MutableHandleObject) + _: jsapi::JS::MutableHandleObject) -> bool { // Window's [[GetPrototypeOf]] trap isn't the ordinary definition: // @@ -467,8 +463,8 @@ pub fn new_window_proxy_handler() -> WindowProxyHandler { // defined in the DissimilarOriginWindow IDL. #[allow(unsafe_code)] -unsafe fn throw_security_error(cx: *mut JSContext) -> bool { - if !JS_IsExceptionPending(cx) { +unsafe fn throw_security_error(cx: *mut jsapi::JSContext) -> bool { + if !jsapi::JS_IsExceptionPending(cx) { let global = GlobalScope::from_context(cx); throw_dom_exception(cx, &*global, Error::Security); } @@ -476,15 +472,15 @@ unsafe fn throw_security_error(cx: *mut JSContext) -> bool { } #[allow(unsafe_code)] -unsafe extern "C" fn has_xorigin(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId, +unsafe extern "C" fn has_xorigin(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, bp: *mut bool) -> bool { rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object()); let mut found = false; - JS_HasOwnPropertyById(cx, target.handle(), id, &mut found); + jsapi::JS_HasOwnPropertyById(cx, target.handle(), id, &mut found); if found { *bp = true; true @@ -494,11 +490,11 @@ unsafe extern "C" fn has_xorigin(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn get_xorigin(cx: *mut JSContext, - proxy: HandleObject, - receiver: HandleValue, - id: HandleId, - vp: MutableHandleValue) +unsafe extern "C" fn get_xorigin(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + receiver: jsapi::JS::HandleValue, + id: jsapi::JS::HandleId, + vp: jsapi::JS::MutableHandleValue) -> bool { let mut found = false; @@ -507,32 +503,32 @@ unsafe extern "C" fn get_xorigin(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn set_xorigin(cx: *mut JSContext, - _: HandleObject, - _: HandleId, - _: HandleValue, - _: HandleValue, - _: *mut ObjectOpResult) +unsafe extern "C" fn set_xorigin(cx: *mut jsapi::JSContext, + _: jsapi::JS::HandleObject, + _: jsapi::JS::HandleId, + _: jsapi::JS::HandleValue, + _: jsapi::JS::HandleValue, + _: *mut jsapi::JS::ObjectOpResult) -> bool { throw_security_error(cx) } #[allow(unsafe_code)] -unsafe extern "C" fn delete_xorigin(cx: *mut JSContext, - _: HandleObject, - _: HandleId, - _: *mut ObjectOpResult) +unsafe extern "C" fn delete_xorigin(cx: *mut jsapi::JSContext, + _: jsapi::JS::HandleObject, + _: jsapi::JS::HandleId, + _: *mut jsapi::JS::ObjectOpResult) -> bool { throw_security_error(cx) } #[allow(unsafe_code)] -unsafe extern "C" fn getOwnPropertyDescriptor_xorigin(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId, - desc: MutableHandle) +unsafe extern "C" fn getOwnPropertyDescriptor_xorigin(cx: *mut jsapi::JSContext, + proxy: jsapi::JS::HandleObject, + id: jsapi::JS::HandleId, + desc: jsapi::JS::MutableHandle) -> bool { let mut found = false; @@ -541,20 +537,20 @@ unsafe extern "C" fn getOwnPropertyDescriptor_xorigin(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn defineProperty_xorigin(cx: *mut JSContext, - _: HandleObject, - _: HandleId, - _: Handle, - _: *mut ObjectOpResult) +unsafe extern "C" fn defineProperty_xorigin(cx: *mut jsapi::JSContext, + _: jsapi::JS::HandleObject, + _: jsapi::JS::HandleId, + _: jsapi::JS::Handle, + _: *mut jsapi::JS::ObjectOpResult) -> bool { throw_security_error(cx) } #[allow(unsafe_code)] -unsafe extern "C" fn preventExtensions_xorigin(cx: *mut JSContext, - _: HandleObject, - _: *mut ObjectOpResult) +unsafe extern "C" fn preventExtensions_xorigin(cx: *mut jsapi::JSContext, + _: jsapi::JS::HandleObject, + _: *mut jsapi::JS::ObjectOpResult) -> bool { throw_security_error(cx) @@ -595,8 +591,8 @@ static XORIGIN_PROXY_HANDLER: ProxyTraps = ProxyTraps { // How WindowProxy objects are garbage collected. #[allow(unsafe_code)] -unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) { - let this = GetProxyExtra(obj, 0).to_private() as *mut WindowProxy; +unsafe extern fn finalize(_fop: *mut jsapi::JSFreeOp, obj: *mut jsapi::JSObject) { + let this = GetProxyReservedSlot(obj, 0).to_private() as *mut WindowProxy; if this.is_null() { // GC during obj creation or after transplanting. return; @@ -607,8 +603,8 @@ unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) { } #[allow(unsafe_code)] -unsafe extern fn trace(trc: *mut JSTracer, obj: *mut JSObject) { - let this = GetProxyExtra(obj, 0).to_private() as *const WindowProxy; +unsafe extern fn trace(trc: *mut jsapi::JSTracer, obj: *mut jsapi::JSObject) { + let this = GetProxyReservedSlot(obj, 0).to_private() as *const WindowProxy; if this.is_null() { // GC during obj creation or after transplanting. return; diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 68655c89981c..660a8c7aa76d 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -24,7 +24,8 @@ use dom::messageevent::MessageEvent; use dom::workerglobalscope::prepare_workerscope_init; use dom_struct::dom_struct; use ipc_channel::ipc; -use js::jsapi::{HandleValue, JSAutoCompartment, JSContext, NullHandleValue}; +use js; +use js::jsapi; use js::jsval::UndefinedValue; use script_thread::Runnable; use script_traits::WorkerScriptLoadOrigin; @@ -120,6 +121,7 @@ impl Worker { self.terminated.get() } + #[allow(unsafe_code)] pub fn handle_message(address: TrustedWorkerAddress, data: StructuredCloneData) { let worker = address.root(); @@ -130,7 +132,10 @@ impl Worker { let global = worker.global(); let target = worker.upcast(); - let _ac = JSAutoCompartment::new(global.get_cx(), target.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(global.get_cx(), + target.reflector().get_jsobject().get()) + }; rooted!(in(global.get_cx()) let mut message = UndefinedValue()); data.read(&global, message.handle_mut()); MessageEvent::dispatch_jsval(target, &global, message.handle()); @@ -152,21 +157,21 @@ impl Worker { error_info.filename.as_str().into(), error_info.lineno, error_info.column, - unsafe { NullHandleValue }); + unsafe { jsapi::JS::NullHandleValue }); let event_status = event.upcast::().fire(self.upcast::()); if event_status == EventStatus::Canceled { return; } - global.report_an_error(error_info, unsafe { NullHandleValue }); + global.report_an_error(error_info, unsafe { jsapi::JS::NullHandleValue }); } } impl WorkerMethods for Worker { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-worker-postmessage - unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { + unsafe fn PostMessage(&self, cx: *mut jsapi::JSContext, message: jsapi::JS::HandleValue) -> ErrorResult { let data = StructuredCloneData::write(cx, message)?; let address = Trusted::new(self); diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 7028518a7c21..4e891462cf2a 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -26,7 +26,8 @@ use dom::workernavigator::WorkerNavigator; use dom_struct::dom_struct; use fetch; use ipc_channel::ipc::IpcSender; -use js::jsapi::{HandleValue, JSAutoCompartment, JSContext, JSRuntime}; +use js; +use js::jsapi; use js::jsval::UndefinedValue; use js::panic::maybe_resume_unwind; use js::rust::Runtime; @@ -132,11 +133,7 @@ impl WorkerGlobalScope { &self.from_devtools_receiver } - pub fn runtime(&self) -> *mut JSRuntime { - self.runtime.rt() - } - - pub fn get_cx(&self) -> *mut JSContext { + pub fn get_cx(&self) -> *mut jsapi::JSContext { self.runtime.cx() } @@ -264,8 +261,8 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc, - timeout: i32, args: Vec) -> i32 { + unsafe fn SetTimeout(&self, _cx: *mut jsapi::JSContext, callback: Rc, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, @@ -275,8 +272,8 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, - timeout: i32, args: Vec) -> i32 { + unsafe fn SetTimeout_(&self, _cx: *mut jsapi::JSContext, callback: DOMString, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, @@ -291,8 +288,8 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval(&self, _cx: *mut JSContext, callback: Rc, - timeout: i32, args: Vec) -> i32 { + unsafe fn SetInterval(&self, _cx: *mut jsapi::JSContext, callback: Rc, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, @@ -302,8 +299,8 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, - timeout: i32, args: Vec) -> i32 { + unsafe fn SetInterval_(&self, _cx: *mut jsapi::JSContext, callback: DOMString, + timeout: i32, args: Vec) -> i32 { self.upcast::().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, @@ -340,7 +337,7 @@ impl WorkerGlobalScope { // https://github.com/servo/servo/issues/6422 println!("evaluate_script failed"); unsafe { - let _ac = JSAutoCompartment::new(self.runtime.cx(), + let _ac = js::ac::AutoCompartment::with_obj(self.runtime.cx(), self.reflector().get_jsobject().get()); report_pending_exception(self.runtime.cx(), true); } diff --git a/components/script/dom/worklet.rs b/components/script/dom/worklet.rs index 9783dfc14a5d..2d4aed12be0a 100644 --- a/components/script/dom/worklet.rs +++ b/components/script/dom/worklet.rs @@ -35,10 +35,7 @@ use dom::workletglobalscope::WorkletGlobalScopeInit; use dom::workletglobalscope::WorkletGlobalScopeType; use dom::workletglobalscope::WorkletTask; use dom_struct::dom_struct; -use js::jsapi::JSGCParamKey; -use js::jsapi::JSTracer; -use js::jsapi::JS_GC; -use js::jsapi::JS_GetGCParameter; +use js::jsapi; use js::rust::Runtime; use msg::constellation_msg::PipelineId; use net_traits::IpcSend; @@ -412,7 +409,7 @@ struct WorkletThread { #[allow(unsafe_code)] unsafe impl JSTraceable for WorkletThread { - unsafe fn trace(&self, trc: *mut JSTracer) { + unsafe fn trace(&self, trc: *mut jsapi::JSTracer) { debug!("Tracing worklet thread."); self.global_scopes.trace(trc); } @@ -522,14 +519,16 @@ impl WorkletThread { /// The current memory usage of the thread #[allow(unsafe_code)] fn current_memory_usage(&self) -> u32 { - unsafe { JS_GetGCParameter(self.runtime.rt(), JSGCParamKey::JSGC_BYTES) } + unsafe { + jsapi::JS_GetGCParameter(self.runtime.cx(), jsapi::JSGCParamKey::JSGC_BYTES) + } } /// Perform a GC. #[allow(unsafe_code)] fn gc(&mut self) { debug!("BEGIN GC (usage = {}, threshold = {}).", self.current_memory_usage(), self.gc_threshold); - unsafe { JS_GC(self.runtime.rt()) }; + unsafe { jsapi::JS_GC(self.runtime.cx()) }; self.gc_threshold = max(MIN_GC_THRESHOLD, self.current_memory_usage() * 2); debug!("END GC (usage = {}, threshold = {}).", self.current_memory_usage(), self.gc_threshold); } diff --git a/components/script/dom/xmldocument.rs b/components/script/dom/xmldocument.rs index 59c6739fb2d8..895d89c32638 100644 --- a/components/script/dom/xmldocument.rs +++ b/components/script/dom/xmldocument.rs @@ -15,7 +15,7 @@ use dom::location::Location; use dom::node::Node; use dom::window::Window; use dom_struct::dom_struct; -use js::jsapi::{JSContext, JSObject}; +use js::jsapi; use script_traits::DocumentActivity; use servo_url::{MutableOrigin, ServoUrl}; @@ -97,7 +97,7 @@ impl XMLDocumentMethods for XMLDocument { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter - unsafe fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString) -> Option> { + unsafe fn NamedGetter(&self, _cx: *mut jsapi::JSContext, name: DOMString) -> Option> { self.upcast::().NamedGetter(_cx, name) } } diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index d6abcda33f24..1ecd70b6ddf4 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -50,9 +50,9 @@ use hyper::mime::{self, Attr as MimeAttr, Mime, Value as MimeValue}; use hyper_serde::Serde; use ipc_channel::ipc; use ipc_channel::router::ROUTER; -use js::jsapi::{Heap, JSContext, JS_ParseJSON}; -use js::jsapi::JS_ClearPendingException; -use js::jsval::{JSVal, NullValue, UndefinedValue}; +use js; +use js::jsapi; +use js::jsval::{NullValue, UndefinedValue}; use net_traits::{FetchMetadata, FilteredMetadata}; use net_traits::{FetchResponseListener, NetworkError, ReferrerPolicy}; use net_traits::CoreResourceMsg::Fetch; @@ -133,7 +133,7 @@ pub struct XMLHttpRequest { response_xml: MutNullableJS, response_blob: MutNullableJS, #[ignore_heap_size_of = "Defined in rust-mozjs"] - response_json: Heap, + response_json: js::heap::Heap, #[ignore_heap_size_of = "Defined in hyper"] response_headers: DOMRefCell, #[ignore_heap_size_of = "Defined in hyper"] @@ -183,7 +183,7 @@ impl XMLHttpRequest { response_type: Cell::new(XMLHttpRequestResponseType::_empty), response_xml: Default::default(), response_blob: Default::default(), - response_json: Heap::default(), + response_json: js::heap::Heap::default(), response_headers: DOMRefCell::new(Headers::new()), override_mime_type: DOMRefCell::new(None), override_charset: DOMRefCell::new(None), @@ -760,7 +760,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { #[allow(unsafe_code)] // https://xhr.spec.whatwg.org/#the-response-attribute - unsafe fn Response(&self, cx: *mut JSContext) -> JSVal { + unsafe fn Response(&self, cx: *mut jsapi::JSContext) -> jsapi::JS::Value { rooted!(in(cx) let mut rval = UndefinedValue()); match self.response_type.get() { XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => { @@ -1151,7 +1151,7 @@ impl XMLHttpRequest { #[allow(unsafe_code)] // https://xhr.spec.whatwg.org/#json-response - fn json_response(&self, cx: *mut JSContext) -> JSVal { + fn json_response(&self, cx: *mut jsapi::JSContext) -> jsapi::JS::Value { // Step 1 let response_json = self.response_json.get(); if !response_json.is_null_or_undefined() { @@ -1169,11 +1169,11 @@ impl XMLHttpRequest { // Step 5 rooted!(in(cx) let mut rval = UndefinedValue()); unsafe { - if !JS_ParseJSON(cx, + if !jsapi::JS_ParseJSON(cx, json_text.as_ptr(), json_text.len() as u32, rval.handle_mut()) { - JS_ClearPendingException(cx); + jsapi::JS_ClearPendingException(cx); return NullValue(); } } diff --git a/components/script/fetch.rs b/components/script/fetch.rs index d7bd48f48739..e4bacb9a2a5c 100644 --- a/components/script/fetch.rs +++ b/components/script/fetch.rs @@ -20,7 +20,7 @@ use dom::response::Response; use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use ipc_channel::ipc; use ipc_channel::router::ROUTER; -use js::jsapi::JSAutoCompartment; +use js; use net_traits::{FetchResponseListener, NetworkError}; use net_traits::{FilteredMetadata, FetchMetadata, Metadata}; use net_traits::CoreResourceMsg::Fetch as NetTraitsFetch; @@ -124,14 +124,16 @@ impl FetchResponseListener for FetchContext { // TODO } - #[allow(unrooted_must_root)] + #[allow(unrooted_must_root, unsafe_code)] fn process_response(&mut self, fetch_metadata: Result) { let promise = self.fetch_promise.take().expect("fetch promise is missing").root(); // JSAutoCompartment needs to be manually made. // Otherwise, Servo will crash. let promise_cx = promise.global().get_cx(); - let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(promise_cx, promise.reflector().get_jsobject().get()) + }; match fetch_metadata { // Step 4.1 Err(_) => { @@ -177,11 +179,14 @@ impl FetchResponseListener for FetchContext { self.body.append(&mut chunk); } + #[allow(unsafe_code)] fn process_response_eof(&mut self, _response: Result<(), NetworkError>) { let response = self.response_object.root(); let global = response.global(); let cx = global.get_cx(); - let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(cx, global.reflector().get_jsobject().get()) + }; response.finish(mem::replace(&mut self.body, vec![])); // TODO // ... trailerObject is not supported in Servo yet. diff --git a/components/script/script_runtime.rs b/components/script/script_runtime.rs index efbdb6bdc402..ad4b1ba39e03 100644 --- a/components/script/script_runtime.rs +++ b/components/script/script_runtime.rs @@ -8,17 +8,13 @@ use dom::bindings::codegen::Bindings::PromiseBinding::PromiseJobCallback; use dom::bindings::js::{RootCollection, RootCollectionPtr, trace_roots}; use dom::bindings::refcounted::{LiveDOMReferences, trace_refcounted_objects}; +use dom::bindings::reflector::DomObject; use dom::bindings::settings_stack; use dom::bindings::trace::{JSTraceable, trace_traceables}; use dom::bindings::utils::DOM_CALLBACKS; use dom::globalscope::GlobalScope; use js::glue::CollectServoSizes; -use js::jsapi::{DisableIncrementalGC, GCDescription, GCProgress, HandleObject}; -use js::jsapi::{JSContext, JS_GetRuntime, JSRuntime, JSTracer, SetDOMCallbacks, SetGCSliceCallback}; -use js::jsapi::{JSGCInvocationKind, JSGCStatus, JS_AddExtraGCRootsTracer, JS_SetGCCallback}; -use js::jsapi::{JSGCMode, JSGCParamKey, JS_SetGCParameter, JS_SetGlobalJitCompilerOption}; -use js::jsapi::{JSJitCompilerOption, JS_SetOffthreadIonCompilationEnabled, JS_SetParallelParsingEnabled}; -use js::jsapi::{JSObject, RuntimeOptionsRef, SetPreserveWrapperCallback, SetEnqueuePromiseJobCallback}; +use js::jsapi; use js::panic::wrap_panic; use js::rust::Runtime; use microtask::{EnqueuedPromiseCallback, Microtask}; @@ -118,9 +114,10 @@ impl<'a> Drop for StackRootTLS<'a> { /// SM callback for promise job resolution. Adds a promise callback to the current /// global's microtask queue. #[allow(unsafe_code)] -unsafe extern "C" fn enqueue_job(cx: *mut JSContext, - job: HandleObject, - _allocation_site: HandleObject, +unsafe extern "C" fn enqueue_job(cx: *mut jsapi::JSContext, + job: jsapi::JS::HandleObject, + _allocation_site: jsapi::JS::HandleObject, + _incumbent_global: jsapi::JS::HandleObject, _data: *mut c_void) -> bool { wrap_panic(AssertUnwindSafe(|| { //XXXjdm - use a different global now? @@ -134,57 +131,66 @@ unsafe extern "C" fn enqueue_job(cx: *mut JSContext, }), false) } +extern "C" fn get_incumbent_global(_cx: *mut jsapi::JSContext) -> *mut jsapi::JSObject { + if let Some(g) = settings_stack::incumbent_global() { + return g.reflector().get_jsobject().get(); + } + + ptr::null_mut() +} + #[allow(unsafe_code)] pub unsafe fn new_rt_and_cx() -> Runtime { LiveDOMReferences::initialize(); let runtime = Runtime::new().unwrap(); - JS_AddExtraGCRootsTracer(runtime.rt(), Some(trace_rust_roots), ptr::null_mut()); - JS_AddExtraGCRootsTracer(runtime.rt(), Some(trace_refcounted_objects), ptr::null_mut()); + jsapi::JS_AddExtraGCRootsTracer(runtime.cx(), Some(trace_rust_roots), ptr::null_mut()); + jsapi::JS_AddExtraGCRootsTracer(runtime.cx(), Some(trace_refcounted_objects), ptr::null_mut()); // Needed for debug assertions about whether GC is running. if cfg!(debug_assertions) { - JS_SetGCCallback(runtime.rt(), Some(debug_gc_callback), ptr::null_mut()); + jsapi::JS_SetGCCallback(runtime.cx(), Some(debug_gc_callback), ptr::null_mut()); } if opts::get().gc_profile { - SetGCSliceCallback(runtime.rt(), Some(gc_slice_callback)); + jsapi::JS::SetGCSliceCallback(runtime.cx(), Some(gc_slice_callback)); } - unsafe extern "C" fn empty_wrapper_callback(_: *mut JSContext, _: *mut JSObject) -> bool { true } - SetDOMCallbacks(runtime.rt(), &DOM_CALLBACKS); - SetPreserveWrapperCallback(runtime.rt(), Some(empty_wrapper_callback)); + unsafe extern "C" fn empty_wrapper_callback(_: *mut jsapi::JSContext, _: *mut jsapi::JSObject) -> bool { true } + jsapi::js::SetDOMCallbacks(runtime.cx(), &DOM_CALLBACKS); + jsapi::js::SetPreserveWrapperCallback(runtime.cx(), Some(empty_wrapper_callback)); // Pre barriers aren't working correctly at the moment - DisableIncrementalGC(runtime.rt()); + jsapi::JS::DisableIncrementalGC(runtime.cx()); - SetEnqueuePromiseJobCallback(runtime.rt(), Some(enqueue_job), ptr::null_mut()); + jsapi::JS::SetEnqueuePromiseJobCallback(runtime.cx(), Some(enqueue_job), ptr::null_mut()); + jsapi::JS::SetGetIncumbentGlobalCallback(runtime.cx(), Some(get_incumbent_global)); set_gc_zeal_options(runtime.rt()); // Enable or disable the JITs. - let rt_opts = &mut *RuntimeOptionsRef(runtime.rt()); + let cx_opts = &mut *jsapi::JS::ContextOptionsRef(runtime.cx()); if let Some(val) = PREFS.get("js.baseline.enabled").as_boolean() { - rt_opts.set_baseline_(val); + cx_opts.set_baseline_(val); } if let Some(val) = PREFS.get("js.ion.enabled").as_boolean() { - rt_opts.set_ion_(val); + cx_opts.set_ion_(val); } if let Some(val) = PREFS.get("js.asmjs.enabled").as_boolean() { - rt_opts.set_asmJS_(val); + cx_opts.set_asmJS_(val); } if let Some(val) = PREFS.get("js.strict.enabled").as_boolean() { - rt_opts.set_extraWarnings_(val); + cx_opts.set_extraWarnings_(val); } // TODO: handle js.strict.debug.enabled // TODO: handle js.throw_on_asmjs_validation_failure (needs new Spidermonkey) if let Some(val) = PREFS.get("js.native_regexp.enabled").as_boolean() { - rt_opts.set_nativeRegExp_(val); + cx_opts.set_nativeRegExp_(val); } if let Some(val) = PREFS.get("js.parallel_parsing.enabled").as_boolean() { - JS_SetParallelParsingEnabled(runtime.rt(), val); + jsapi::JS_SetParallelParsingEnabled(runtime.cx(), val); } if let Some(val) = PREFS.get("js.offthread_compilation_enabled").as_boolean() { - JS_SetOffthreadIonCompilationEnabled(runtime.rt(), val); + jsapi::JS_SetOffthreadIonCompilationEnabled(runtime.cx(), val); } if let Some(val) = PREFS.get("js.baseline.unsafe_eager_compilation.enabled").as_boolean() { let trigger: i32 = if val { @@ -192,8 +198,8 @@ pub unsafe fn new_rt_and_cx() -> Runtime { } else { -1 }; - JS_SetGlobalJitCompilerOption(runtime.rt(), - JSJitCompilerOption::JSJITCOMPILER_BASELINE_WARMUP_TRIGGER, + jsapi::JS_SetGlobalJitCompilerOption(runtime.cx(), + jsapi::JSJitCompilerOption::JSJITCOMPILER_BASELINE_WARMUP_TRIGGER, trigger as u32); } if let Some(val) = PREFS.get("js.ion.unsafe_eager_compilation.enabled").as_boolean() { @@ -202,20 +208,20 @@ pub unsafe fn new_rt_and_cx() -> Runtime { } else { -1 }; - JS_SetGlobalJitCompilerOption(runtime.rt(), - JSJitCompilerOption::JSJITCOMPILER_ION_WARMUP_TRIGGER, - trigger as u32); + jsapi::JS_SetGlobalJitCompilerOption(runtime.cx(), + jsapi::JSJitCompilerOption::JSJITCOMPILER_ION_WARMUP_TRIGGER, + trigger as u32); } // TODO: handle js.discard_system_source.enabled // TODO: handle js.asyncstack.enabled (needs new Spidermonkey) // TODO: handle js.throw_on_debugee_would_run (needs new Spidermonkey) // TODO: handle js.dump_stack_on_debugee_would_run (needs new Spidermonkey) if let Some(val) = PREFS.get("js.werror.enabled").as_boolean() { - rt_opts.set_werror_(val); + cx_opts.set_werror_(val); } // TODO: handle js.shared_memory.enabled if let Some(val) = PREFS.get("js.mem.high_water_mark").as_i64() { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MAX_MALLOC_BYTES, val as u32 * 1024 * 1024); + jsapi::JS_SetGCParameter(runtime.cx(), jsapi::JSGCParamKey::JSGC_MAX_MALLOC_BYTES, val as u32 * 1024 * 1024); } if let Some(val) = PREFS.get("js.mem.max").as_i64() { let max = if val <= 0 || val >= 0x1000 { @@ -223,87 +229,120 @@ pub unsafe fn new_rt_and_cx() -> Runtime { } else { val * 1024 * 1024 }; - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MAX_BYTES, max as u32); + jsapi::JS_SetGCParameter(runtime.cx(), jsapi::JSGCParamKey::JSGC_MAX_BYTES, max as u32); } // NOTE: This is disabled above, so enabling it here will do nothing for now. if let Some(val) = PREFS.get("js.mem.gc.incremental.enabled").as_boolean() { - let compartment = if let Some(val) = PREFS.get("js.mem.gc.per_compartment.enabled").as_boolean() { + let zone = if let Some(val) = PREFS.get("js.mem.gc.per_compartment.enabled").as_boolean() { val } else { false }; let mode = if val { - JSGCMode::JSGC_MODE_INCREMENTAL - } else if compartment { - JSGCMode::JSGC_MODE_COMPARTMENT + jsapi::JSGCMode::JSGC_MODE_INCREMENTAL + } else if zone { + jsapi::JSGCMode::JSGC_MODE_ZONE } else { - JSGCMode::JSGC_MODE_GLOBAL + jsapi::JSGCMode::JSGC_MODE_GLOBAL }; - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MODE, mode as u32); + jsapi::JS_SetGCParameter(runtime.cx(), jsapi::JSGCParamKey::JSGC_MODE, mode as u32); } if let Some(val) = PREFS.get("js.mem.gc.incremental.slice_ms").as_i64() { if val >= 0 && val < 100000 { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_SLICE_TIME_BUDGET, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_SLICE_TIME_BUDGET, + val as u32); } } if let Some(val) = PREFS.get("js.mem.gc.compacting.enabled").as_boolean() { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_COMPACTING_ENABLED, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_COMPACTING_ENABLED, + val as u32); } if let Some(val) = PREFS.get("js.mem.gc.high_frequency_time_limit_ms").as_i64() { if val >= 0 && val < 10000 { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_HIGH_FREQUENCY_TIME_LIMIT, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_HIGH_FREQUENCY_TIME_LIMIT, + val as u32); } } if let Some(val) = PREFS.get("js.mem.gc.dynamic_mark_slice.enabled").as_boolean() { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_DYNAMIC_MARK_SLICE, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_DYNAMIC_MARK_SLICE, + val as u32); } // TODO: handle js.mem.gc.refresh_frame_slices.enabled if let Some(val) = PREFS.get("js.mem.gc.dynamic_heap_growth.enabled").as_boolean() { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_DYNAMIC_HEAP_GROWTH, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_DYNAMIC_HEAP_GROWTH, + val as u32); } if let Some(val) = PREFS.get("js.mem.gc.low_frequency_heap_growth").as_i64() { if val >= 0 && val < 10000 { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_LOW_FREQUENCY_HEAP_GROWTH, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_LOW_FREQUENCY_HEAP_GROWTH, + val as u32); } } if let Some(val) = PREFS.get("js.mem.gc.high_frequency_heap_growth_min").as_i64() { if val >= 0 && val < 10000 { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN, val as u32); } } if let Some(val) = PREFS.get("js.mem.gc.high_frequency_heap_growth_max").as_i64() { if val >= 0 && val < 10000 { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX, + val as u32); } } if let Some(val) = PREFS.get("js.mem.gc.high_frequency_low_limit_mb").as_i64() { if val >= 0 && val < 10000 { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_HIGH_FREQUENCY_LOW_LIMIT, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_HIGH_FREQUENCY_LOW_LIMIT, + val as u32); } } if let Some(val) = PREFS.get("js.mem.gc.high_frequency_high_limit_mb").as_i64() { if val >= 0 && val < 10000 { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_HIGH_FREQUENCY_HIGH_LIMIT, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_HIGH_FREQUENCY_HIGH_LIMIT, + val as u32); } } if let Some(val) = PREFS.get("js.mem.gc.allocation_threshold_mb").as_i64() { if val >= 0 && val < 10000 { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_ALLOCATION_THRESHOLD, val as u32); - } - } - if let Some(val) = PREFS.get("js.mem.gc.decommit_threshold_mb").as_i64() { - if val >= 0 && val < 10000 { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_DECOMMIT_THRESHOLD, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_ALLOCATION_THRESHOLD, + val as u32); } } if let Some(val) = PREFS.get("js.mem.gc.empty_chunk_count_min").as_i64() { if val >= 0 && val < 10000 { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MIN_EMPTY_CHUNK_COUNT, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_MIN_EMPTY_CHUNK_COUNT, + val as u32); } } if let Some(val) = PREFS.get("js.mem.gc.empty_chunk_count_max").as_i64() { if val >= 0 && val < 10000 { - JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MAX_EMPTY_CHUNK_COUNT, val as u32); + jsapi::JS_SetGCParameter( + runtime.cx(), + jsapi::JSGCParamKey::JSGC_MAX_EMPTY_CHUNK_COUNT, + val as u32); } } @@ -311,11 +350,11 @@ pub unsafe fn new_rt_and_cx() -> Runtime { } #[allow(unsafe_code)] -pub fn get_reports(cx: *mut JSContext, path_seg: String) -> Vec { +pub fn get_reports(cx: *mut jsapi::JSContext, path_seg: String) -> Vec { let mut reports = vec![]; unsafe { - let rt = JS_GetRuntime(cx); + let rt = jsapi::JS_GetRuntime(cx); let mut stats = ::std::mem::zeroed(); if CollectServoSizes(rt, &mut stats) { let mut report = |mut path_suffix, kind, size| { @@ -365,28 +404,30 @@ thread_local!(static GC_CYCLE_START: Cell> = Cell::new(None)); thread_local!(static GC_SLICE_START: Cell> = Cell::new(None)); #[allow(unsafe_code)] -unsafe extern "C" fn gc_slice_callback(_rt: *mut JSRuntime, progress: GCProgress, desc: *const GCDescription) { +unsafe extern "C" fn gc_slice_callback(_cx: *mut jsapi::JSContext, + progress: jsapi::JS::GCProgress, + desc: *const jsapi::JS::GCDescription) { match progress { - GCProgress::GC_CYCLE_BEGIN => { + jsapi::JS::GCProgress::GC_CYCLE_BEGIN => { GC_CYCLE_START.with(|start| { start.set(Some(now())); println!("GC cycle began"); }) }, - GCProgress::GC_SLICE_BEGIN => { + jsapi::JS::GCProgress::GC_SLICE_BEGIN => { GC_SLICE_START.with(|start| { start.set(Some(now())); println!("GC slice began"); }) }, - GCProgress::GC_SLICE_END => { + jsapi::JS::GCProgress::GC_SLICE_END => { GC_SLICE_START.with(|start| { let dur = now() - start.get().unwrap(); start.set(None); println!("GC slice ended: duration={}", dur); }) }, - GCProgress::GC_CYCLE_END => { + jsapi::JS::GCProgress::GC_CYCLE_END => { GC_CYCLE_START.with(|start| { let dur = now() - start.get().unwrap(); start.set(None); @@ -395,26 +436,28 @@ unsafe extern "C" fn gc_slice_callback(_rt: *mut JSRuntime, progress: GCProgress }, }; if !desc.is_null() { - let desc: &GCDescription = &*desc; + let desc: &jsapi::JS::GCDescription = &*desc; let invocation_kind = match desc.invocationKind_ { - JSGCInvocationKind::GC_NORMAL => "GC_NORMAL", - JSGCInvocationKind::GC_SHRINK => "GC_SHRINK", + jsapi::JSGCInvocationKind::GC_NORMAL => "GC_NORMAL", + jsapi::JSGCInvocationKind::GC_SHRINK => "GC_SHRINK", }; - println!(" isCompartment={}, invocation_kind={}", desc.isCompartment_, invocation_kind); + println!(" isZone={}, invocation_kind={}", desc.isZone_, invocation_kind); } let _ = stdout().flush(); } #[allow(unsafe_code)] -unsafe extern "C" fn debug_gc_callback(_rt: *mut JSRuntime, status: JSGCStatus, _data: *mut os::raw::c_void) { +unsafe extern "C" fn debug_gc_callback(_rt: *mut jsapi::JSContext, + status: jsapi::JSGCStatus, + _data: *mut os::raw::c_void) { match status { - JSGCStatus::JSGC_BEGIN => thread_state::enter(thread_state::IN_GC), - JSGCStatus::JSGC_END => thread_state::exit(thread_state::IN_GC), + jsapi::JSGCStatus::JSGC_BEGIN => thread_state::enter(thread_state::IN_GC), + jsapi::JSGCStatus::JSGC_END => thread_state::exit(thread_state::IN_GC), } } #[allow(unsafe_code)] -unsafe extern fn trace_rust_roots(tr: *mut JSTracer, _data: *mut os::raw::c_void) { +unsafe extern fn trace_rust_roots(tr: *mut jsapi::JSTracer, _data: *mut os::raw::c_void) { debug!("starting custom root handler"); trace_thread(tr); trace_traceables(tr); @@ -425,20 +468,18 @@ unsafe extern fn trace_rust_roots(tr: *mut JSTracer, _data: *mut os::raw::c_void #[allow(unsafe_code)] #[cfg(feature = "debugmozjs")] -unsafe fn set_gc_zeal_options(rt: *mut JSRuntime) { - use js::jsapi::{JS_DEFAULT_ZEAL_FREQ, JS_SetGCZeal}; - +unsafe fn set_gc_zeal_options(rt: *mut jsapi::JSRuntime) { let level = match PREFS.get("js.mem.gc.zeal.level").as_i64() { Some(level @ 0...14) => level as u8, _ => return, }; let frequency = match PREFS.get("js.mem.gc.zeal.frequency").as_i64() { Some(frequency) if frequency >= 0 => frequency as u32, - _ => JS_DEFAULT_ZEAL_FREQ, + _ => jsapi::JS_DEFAULT_ZEAL_FREQ, }; - JS_SetGCZeal(rt, level, frequency); + jsapi::JS_SetGCZeal(rt, level, frequency); } #[allow(unsafe_code)] #[cfg(not(feature = "debugmozjs"))] -unsafe fn set_gc_zeal_options(_: *mut JSRuntime) {} +unsafe fn set_gc_zeal_options(_: *mut jsapi::JSRuntime) {} diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 6bba0824270d..7dfa19851f1f 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -68,9 +68,9 @@ use hyper::mime::{Mime, SubLevel, TopLevel}; use hyper_serde::Serde; use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::router::ROUTER; +use js; use js::glue::GetWindowProxyClass; -use js::jsapi::{JSAutoCompartment, JSContext, JS_SetWrapObjectCallbacks}; -use js::jsapi::{JSTracer, SetWindowProxyClass}; +use js::jsapi; use js::jsval::UndefinedValue; use js::rust::Runtime; use mem::heap_size_of_self_and_children; @@ -129,7 +129,7 @@ pub type ImageCacheMsg = (PipelineId, PendingImageResponse); thread_local!(pub static STACK_ROOTS: Cell> = Cell::new(None)); thread_local!(static SCRIPT_THREAD_ROOT: Cell> = Cell::new(None)); -pub unsafe fn trace_thread(tr: *mut JSTracer) { +pub unsafe fn trace_thread(tr: *mut jsapi::JSTracer) { SCRIPT_THREAD_ROOT.with(|root| { if let Some(script_thread) = root.get() { debug!("tracing fields of ScriptThread"); @@ -623,10 +623,9 @@ impl ScriptThread { pub unsafe fn note_newly_transitioning_nodes(nodes: Vec) { SCRIPT_THREAD_ROOT.with(|root| { let script_thread = &*root.get().unwrap(); - let js_runtime = script_thread.js_runtime.rt(); let new_nodes = nodes .into_iter() - .map(|n| JS::from_ref(&*from_untrusted_node_address(js_runtime, n))); + .map(|n| JS::from_ref(&*from_untrusted_node_address(n))); script_thread.transitioning_nodes.borrow_mut().extend(new_nodes); }) } @@ -822,9 +821,8 @@ impl ScriptThread { let runtime = unsafe { new_rt_and_cx() }; unsafe { - JS_SetWrapObjectCallbacks(runtime.rt(), - &WRAP_CALLBACKS); - SetWindowProxyClass(runtime.rt(), GetWindowProxyClass()); + jsapi::JS_SetWrapObjectCallbacks(runtime.cx(), &WRAP_CALLBACKS); + jsapi::js::SetWindowProxyClass(runtime.cx(), GetWindowProxyClass()); } // Ask the router to proxy IPC messages from the devtools to us. @@ -906,7 +904,7 @@ impl ScriptThread { } } - pub fn get_cx(&self) -> *mut JSContext { + pub fn get_cx(&self) -> *mut jsapi::JSContext { self.js_runtime.cx() } @@ -1813,9 +1811,8 @@ impl ScriptThread { /// Handles firing of transition events. fn handle_transition_event(&self, unsafe_node: UntrustedNodeAddress, name: String, duration: f64) { - let js_runtime = self.js_runtime.rt(); let node = unsafe { - from_untrusted_node_address(js_runtime, unsafe_node) + from_untrusted_node_address(unsafe_node) }; let idx = self.transitioning_nodes @@ -2139,7 +2136,7 @@ impl ScriptThread { // Script source is ready to be evaluated (11.) unsafe { - let _ac = JSAutoCompartment::new(self.get_cx(), window.reflector().get_jsobject().get()); + let _ac = js::ac::AutoCompartment::with_obj(self.get_cx(), window.reflector().get_jsobject().get()); rooted!(in(self.get_cx()) let mut jsval = UndefinedValue()); window.upcast::().evaluate_js_on_global_with_result( &script_source, jsval.handle_mut()); diff --git a/components/script/serviceworkerjob.rs b/components/script/serviceworkerjob.rs index e1f43a347636..b38a18eb4613 100644 --- a/components/script/serviceworkerjob.rs +++ b/components/script/serviceworkerjob.rs @@ -17,7 +17,7 @@ use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom::serviceworkerregistration::ServiceWorkerRegistration; use dom::urlhelper::UrlHelper; -use js::jsapi::JSAutoCompartment; +use js; use script_thread::{ScriptThread, Runnable}; use servo_url::ServoUrl; use std::cmp::PartialEq; @@ -313,8 +313,12 @@ impl AsyncPromiseSettle { } } +#[allow(unsafe_code)] fn settle_job_promise(global: &GlobalScope, promise: &Promise, settle: SettleType) { - let _ac = JSAutoCompartment::new(global.get_cx(), promise.reflector().get_jsobject().get()); + let _ac = unsafe { + js::ac::AutoCompartment::with_obj(global.get_cx(), + promise.reflector().get_jsobject().get()) + }; match settle { SettleType::Resolve(reg) => promise.resolve_native(global.get_cx(), &*reg.root()), SettleType::Reject(err) => promise.reject_error(global.get_cx(), err), diff --git a/components/script/timers.rs b/components/script/timers.rs index 7d219bbb199d..c19445aa6cef 100644 --- a/components/script/timers.rs +++ b/components/script/timers.rs @@ -15,8 +15,9 @@ use dom::xmlhttprequest::XHRTimeoutCallback; use euclid::Length; use heapsize::HeapSizeOf; use ipc_channel::ipc::IpcSender; -use js::jsapi::{HandleValue, Heap}; -use js::jsval::{JSVal, UndefinedValue}; +use js::heap::Heap; +use js::jsapi; +use js::jsval::UndefinedValue; use script_traits::{MsDuration, precise_time_ms}; use script_traits::{TimerEvent, TimerEventId, TimerEventRequest}; use script_traits::{TimerSchedulerMsg, TimerSource}; @@ -283,7 +284,7 @@ impl OneshotTimers { pub fn set_timeout_or_interval(&self, global: &GlobalScope, callback: TimerCallback, - arguments: Vec, + arguments: Vec, timeout: i32, is_interval: IsInterval, source: TimerSource) @@ -350,7 +351,7 @@ pub enum TimerCallback { #[derive(Clone, JSTraceable)] enum InternalTimerCallback { StringTimerCallback(DOMString), - FunctionTimerCallback(Rc, Rc]>>), + FunctionTimerCallback(Rc, Rc]>>), } impl HeapSizeOf for InternalTimerCallback { @@ -374,7 +375,7 @@ impl JsTimers { pub fn set_timeout_or_interval(&self, global: &GlobalScope, callback: TimerCallback, - arguments: Vec, + arguments: Vec, timeout: i32, is_interval: IsInterval, source: TimerSource) diff --git a/components/script/webdriver_handlers.rs b/components/script/webdriver_handlers.rs index c01a7d9a51a8..7edaa4e1cb7c 100644 --- a/components/script/webdriver_handlers.rs +++ b/components/script/webdriver_handlers.rs @@ -25,7 +25,7 @@ use dom::node::{Node, window_from_node}; use euclid::{Point2D, Rect, Size2D}; use hyper_serde::Serde; use ipc_channel::ipc::{self, IpcSender}; -use js::jsapi::{HandleValue, JSContext}; +use js::jsapi; use js::jsval::UndefinedValue; use msg::constellation_msg::BrowsingContextId; use msg::constellation_msg::PipelineId; @@ -47,7 +47,7 @@ fn find_node_by_unique_id(documents: &Documents, } #[allow(unsafe_code)] -pub unsafe fn jsval_to_webdriver(cx: *mut JSContext, val: HandleValue) -> WebDriverJSResult { +pub unsafe fn jsval_to_webdriver(cx: *mut jsapi::JSContext, val: jsapi::JS::HandleValue) -> WebDriverJSResult { if val.get().is_undefined() { Ok(WebDriverJSValue::Undefined) } else if val.get().is_boolean() { diff --git a/components/webvr/webvr_thread.rs b/components/webvr/webvr_thread.rs index 77f42a6b39e9..9054c3e6f0b3 100644 --- a/components/webvr/webvr_thread.rs +++ b/components/webvr/webvr_thread.rs @@ -296,7 +296,8 @@ impl WebVRThread { /// by flooding the WebVRThread with messages while the main JavaScript tab is presenting to the headset. /// Multithreading won't be a problem because: /// * Thanks to the security rules implemented in the WebVRThread, when a VRDisplay is in a presenting loop -/// no other JSContext is granted access to the VRDisplay. So really there aren’t multithreading race conditions. +/// no other jsapi::JSContext is granted access to the VRDisplay. So really there aren’t multithreading +/// race conditions. /// * VRDisplay implementations are designed to allow calling compositor functions /// in another thread by using the Send + Sync traits. /// VRDisplays pointers are guaranteed to be valid memory: