Clean up the conversion routines

Functions returning `Root<T>` are prefixed by "root_" and the ones returning
`*const T` by "native_".

Functions taking `*mut JSObject` are now suffixed by "_from_object" and the ones
taking `&T` by "_from_reflector".
This commit is contained in:
Anthony Ramine 2015-10-25 11:11:23 +01:00
parent aa105d89b4
commit b290a3161d
10 changed files with 45 additions and 61 deletions

View file

@ -5,7 +5,7 @@
//! Base classes to work with IDL callbacks. //! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible}; use dom::bindings::error::{Error, Fallible};
use dom::bindings::global::global_object_for_js_object; use dom::bindings::global::global_root_from_object;
use dom::bindings::reflector::Reflectable; use dom::bindings::reflector::Reflectable;
use js::jsapi::GetGlobalForObjectCrossCompartment; use js::jsapi::GetGlobalForObjectCrossCompartment;
use js::jsapi::{Heap, MutableHandleObject, RootedObject, RootedValue}; use js::jsapi::{Heap, MutableHandleObject, RootedObject, RootedValue};
@ -170,7 +170,7 @@ impl CallSetup {
/// Performs the setup needed to make a call. /// Performs the setup needed to make a call.
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup { pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup {
let global = global_object_for_js_object(callback.callback()); let global = global_root_from_object(callback.callback());
let cx = global.r().get_cx(); let cx = global.r().get_cx();
unsafe { JS_BeginRequest(cx); } unsafe { JS_BeginRequest(cx); }

View file

@ -119,7 +119,7 @@ class CastableObjectUnwrapper():
def __str__(self): def __str__(self):
return string.Template("""\ return string.Template("""\
match native_from_handle${handletype}(${source}) { match root_from_handle${handletype}(${source}) {
Ok(val) => val, Ok(val) => val,
Err(()) => { Err(()) => {
${codeOnFailure} ${codeOnFailure}
@ -1996,7 +1996,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, config):
'dom::bindings::conversions::FromJSValConvertible', 'dom::bindings::conversions::FromJSValConvertible',
'dom::bindings::conversions::ToJSValConvertible', 'dom::bindings::conversions::ToJSValConvertible',
'dom::bindings::conversions::ConversionBehavior', 'dom::bindings::conversions::ConversionBehavior',
'dom::bindings::conversions::native_from_handlevalue', 'dom::bindings::conversions::root_from_handlevalue',
'dom::bindings::conversions::StringificationBehavior', 'dom::bindings::conversions::StringificationBehavior',
'dom::bindings::error::throw_not_in_union', 'dom::bindings::error::throw_not_in_union',
'dom::bindings::js::Root', 'dom::bindings::js::Root',
@ -2638,7 +2638,7 @@ class CGCallGenerator(CGThing):
if static: if static:
glob = "" glob = ""
else: else:
glob = " let global = global_object_for_js_object(this.reflector().get_jsobject().get());\n" glob = " let global = global_root_from_reflector(this);\n"
self.cgRoot.append(CGGeneric( self.cgRoot.append(CGGeneric(
"let result = match result {\n" "let result = match result {\n"
@ -2845,7 +2845,7 @@ class CGAbstractStaticBindingMethod(CGAbstractMethod):
def definition_body(self): def definition_body(self):
preamble = CGGeneric("""\ preamble = CGGeneric("""\
let global = global_object_for_js_object(JS_CALLEE(cx, vp).to_object()); let global = global_root_from_object(JS_CALLEE(cx, vp).to_object());
""") """)
return CGList([preamble, self.generate_code()]) return CGList([preamble, self.generate_code()])
@ -4532,8 +4532,8 @@ class CGAbstractClassHook(CGAbstractExternMethod):
def definition_body_prologue(self): def definition_body_prologue(self):
return CGGeneric("""\ return CGGeneric("""\
let this: *const %s = native_from_reflector::<%s>(obj); let this = private_from_object(obj) as *const %s;
""" % (self.descriptor.concreteType, self.descriptor.concreteType)) """ % self.descriptor.concreteType)
def definition_body(self): def definition_body(self):
return CGList([ return CGList([
@ -4593,7 +4593,7 @@ class CGClassConstructHook(CGAbstractExternMethod):
def definition_body(self): def definition_body(self):
preamble = CGGeneric("""\ preamble = CGGeneric("""\
let global = global_object_for_js_object(JS_CALLEE(cx, vp).to_object()); let global = global_root_from_object(JS_CALLEE(cx, vp).to_object());
let args = CallArgs::from_vp(vp, argc); let args = CallArgs::from_vp(vp, argc);
""") """)
name = self._ctor.identifier.name name = self._ctor.identifier.name
@ -4617,7 +4617,7 @@ class CGClassNameConstructHook(CGAbstractExternMethod):
def definition_body(self): def definition_body(self):
preamble = CGGeneric("""\ preamble = CGGeneric("""\
let global = global_object_for_js_object(JS_CALLEE(cx, vp).to_object()); let global = global_root_from_object(JS_CALLEE(cx, vp).to_object());
let args = CallArgs::from_vp(vp, argc); let args = CallArgs::from_vp(vp, argc);
""") """)
name = self._ctor.identifier.name name = self._ctor.identifier.name
@ -5196,8 +5196,7 @@ class CGBindingRoot(CGThing):
'js::glue::AppendToAutoIdVector', 'js::glue::AppendToAutoIdVector',
'js::rust::GCMethods', 'js::rust::GCMethods',
'dom::bindings', 'dom::bindings',
'dom::bindings::global::GlobalRef', 'dom::bindings::global::{GlobalRef, global_root_from_object, global_root_from_reflector}',
'dom::bindings::global::global_object_for_js_object',
'dom::bindings::js::{JS, Root, RootedReference}', 'dom::bindings::js::{JS, Root, RootedReference}',
'dom::bindings::js::{OptionalRootedReference}', 'dom::bindings::js::{OptionalRootedReference}',
'dom::bindings::reflector::{Reflectable}', 'dom::bindings::reflector::{Reflectable}',
@ -5223,12 +5222,11 @@ class CGBindingRoot(CGThing):
'dom::bindings::callback::{CallbackContainer,CallbackInterface,CallbackFunction}', 'dom::bindings::callback::{CallbackContainer,CallbackInterface,CallbackFunction}',
'dom::bindings::callback::{CallSetup,ExceptionHandling}', 'dom::bindings::callback::{CallSetup,ExceptionHandling}',
'dom::bindings::callback::wrap_call_this_object', 'dom::bindings::callback::wrap_call_this_object',
'dom::bindings::conversions::{FromJSValConvertible, ToJSValConvertible, ConversionBehavior}', 'dom::bindings::conversions::{ConversionBehavior, DOM_OBJECT_SLOT, IDLInterface}',
'dom::bindings::conversions::{native_from_reflector, native_from_handlevalue, native_from_handleobject}', 'dom::bindings::conversions::{FromJSValConvertible, StringificationBehavior}',
'dom::bindings::conversions::DOM_OBJECT_SLOT', 'dom::bindings::conversions::{ToJSValConvertible, jsid_to_str}',
'dom::bindings::conversions::IDLInterface', 'dom::bindings::conversions::{private_from_object, root_from_object}',
'dom::bindings::conversions::jsid_to_str', 'dom::bindings::conversions::{root_from_handleobject, root_from_handlevalue}',
'dom::bindings::conversions::StringificationBehavior',
'dom::bindings::codegen::{PrototypeList, RegisterBindings, UnionTypes}', 'dom::bindings::codegen::{PrototypeList, RegisterBindings, UnionTypes}',
'dom::bindings::codegen::Bindings::*', 'dom::bindings::codegen::Bindings::*',
'dom::bindings::error::{Fallible, Error, ErrorResult}', 'dom::bindings::error::{Fallible, Error, ErrorResult}',

View file

@ -32,7 +32,6 @@
//! | sequences | `Vec<T>` | //! | sequences | `Vec<T>` |
//! | union types | `T` | //! | union types | `T` |
use core::nonzero::NonZero;
use dom::bindings::error::throw_type_error; use dom::bindings::error::throw_type_error;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root; use dom::bindings::js::Root;
@ -657,7 +656,7 @@ pub fn is_dom_proxy(obj: *mut JSObject) -> bool {
pub const DOM_OBJECT_SLOT: u32 = 0; pub const DOM_OBJECT_SLOT: u32 = 0;
/// Get the private pointer of a DOM object from a given reflector. /// Get the private pointer of a DOM object from a given reflector.
unsafe fn private_from_reflector(obj: *mut JSObject) -> *const libc::c_void { pub unsafe fn private_from_object(obj: *mut JSObject) -> *const libc::c_void {
let clasp = JS_GetClass(obj); let clasp = JS_GetClass(obj);
let value = if is_dom_class(clasp) { let value = if is_dom_class(clasp) {
JS_GetReservedSlot(obj, DOM_OBJECT_SLOT) JS_GetReservedSlot(obj, DOM_OBJECT_SLOT)
@ -672,11 +671,6 @@ unsafe fn private_from_reflector(obj: *mut JSObject) -> *const libc::c_void {
} }
} }
/// Get the DOM object from the given reflector.
pub unsafe fn native_from_reflector<T>(obj: *mut JSObject) -> *const T {
private_from_reflector(obj) as *const T
}
/// Get the `DOMClass` from `obj`, or `Err(())` if `obj` is not a DOM object. /// 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 JSObject) -> Result<&'static DOMClass, ()> {
use dom::bindings::utils::DOMJSClass; use dom::bindings::utils::DOMJSClass;
@ -727,7 +721,7 @@ pub unsafe fn private_from_proto_check<F>(mut obj: *mut JSObject, proto_check: F
if proto_check(dom_class) { if proto_check(dom_class) {
debug!("good prototype"); debug!("good prototype");
Ok(private_from_reflector(obj)) Ok(private_from_object(obj))
} else { } else {
debug!("bad prototype"); debug!("bad prototype");
Err(()) Err(())
@ -740,28 +734,28 @@ pub unsafe fn private_from_proto_check<F>(mut obj: *mut JSObject, proto_check: F
/// Returns Err(()) if `obj` is an opaque security wrapper or if the object is /// 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 /// not a reflector for a DOM object of the given type (as defined by the
/// proto_id and proto_depth). /// proto_id and proto_depth).
pub fn native_from_reflector_jsmanaged<T>(obj: *mut JSObject) -> Result<Root<T>, ()> pub fn root_from_object<T>(obj: *mut JSObject) -> Result<Root<T>, ()>
where T: Reflectable + IDLInterface where T: Reflectable + IDLInterface
{ {
unsafe { unsafe {
private_from_proto_check(obj, T::derives).map(|obj| { private_from_proto_check(obj, T::derives).map(|ptr| {
Root::new(NonZero::new(obj as *const T)) Root::from_ref(&*(ptr as *const T))
}) })
} }
} }
/// Get a Rooted<T> for a DOM object accessible from a HandleValue /// Get a `Root<T>` for a DOM object accessible from a `HandleValue`.
pub fn native_from_handlevalue<T>(v: HandleValue) -> Result<Root<T>, ()> pub fn root_from_handlevalue<T>(v: HandleValue) -> Result<Root<T>, ()>
where T: Reflectable + IDLInterface where T: Reflectable + IDLInterface
{ {
native_from_reflector_jsmanaged(v.get().to_object()) root_from_object(v.get().to_object())
} }
/// Get a Rooted<T> for a DOM object accessible from a HandleObject /// Get a `Root<T>` for a DOM object accessible from a `HandleObject`.
pub fn native_from_handleobject<T>(obj: HandleObject) -> Result<Root<T>, ()> pub fn root_from_handleobject<T>(obj: HandleObject) -> Result<Root<T>, ()>
where T: Reflectable + IDLInterface where T: Reflectable + IDLInterface
{ {
native_from_reflector_jsmanaged(obj.get()) root_from_object(obj.get())
} }
impl<T: Reflectable> ToJSValConvertible for Root<T> { impl<T: Reflectable> ToJSValConvertible for Root<T> {

View file

@ -9,7 +9,7 @@
use devtools_traits::ScriptToDevtoolsControlMsg; use devtools_traits::ScriptToDevtoolsControlMsg;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::conversions::native_from_reflector_jsmanaged; use dom::bindings::conversions::root_from_object;
use dom::bindings::js::{JS, Root}; use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{Reflectable, Reflector}; use dom::bindings::reflector::{Reflectable, Reflector};
use dom::window::{self, ScriptHelpers}; use dom::window::{self, ScriptHelpers};
@ -255,23 +255,23 @@ impl GlobalField {
} }
/// Returns the global object of the realm that the given DOM object's reflector was created in. /// Returns the global object of the realm that the given DOM object's reflector was created in.
pub fn global_object_for_reflector<T: Reflectable>(reflector: &T) -> GlobalRoot { pub fn global_root_from_reflector<T: Reflectable>(reflector: &T) -> GlobalRoot {
global_object_for_js_object(*reflector.reflector().get_jsobject()) global_root_from_object(*reflector.reflector().get_jsobject())
} }
/// Returns the global object of the realm that the given JS object was created in. /// Returns the global object of the realm that the given JS object was created in.
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalRoot { pub fn global_root_from_object(obj: *mut JSObject) -> GlobalRoot {
unsafe { unsafe {
let global = GetGlobalForObjectCrossCompartment(obj); let global = GetGlobalForObjectCrossCompartment(obj);
let clasp = JS_GetClass(global); let clasp = JS_GetClass(global);
assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0); assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0);
match native_from_reflector_jsmanaged(global) { match root_from_object(global) {
Ok(window) => return GlobalRoot::Window(window), Ok(window) => return GlobalRoot::Window(window),
Err(_) => (), Err(_) => (),
} }
match native_from_reflector_jsmanaged(global) { match root_from_object(global) {
Ok(worker) => return GlobalRoot::Worker(worker), Ok(worker) => return GlobalRoot::Worker(worker),
Err(_) => (), Err(_) => (),
} }

View file

@ -6,12 +6,10 @@
use dom::bindings::codegen::PrototypeList; use dom::bindings::codegen::PrototypeList;
use dom::bindings::codegen::PrototypeList::MAX_PROTO_CHAIN_LENGTH; use dom::bindings::codegen::PrototypeList::MAX_PROTO_CHAIN_LENGTH;
use dom::bindings::conversions::native_from_handleobject; use dom::bindings::conversions::{DOM_OBJECT_SLOT, is_dom_class, jsstring_to_str};
use dom::bindings::conversions::private_from_proto_check; use dom::bindings::conversions::{private_from_proto_check, root_from_handleobject};
use dom::bindings::conversions::{is_dom_class, jsstring_to_str, DOM_OBJECT_SLOT};
use dom::bindings::error::{throw_invalid_this, throw_type_error}; use dom::bindings::error::{throw_invalid_this, throw_type_error};
use dom::bindings::inheritance::TopTypeId; use dom::bindings::inheritance::TopTypeId;
use dom::bindings::js::Root;
use dom::bindings::trace::trace_object; use dom::bindings::trace::trace_object;
use dom::browsercontext; use dom::browsercontext;
use dom::window; use dom::window;
@ -625,9 +623,7 @@ pub static WRAP_CALLBACKS: JSWrapObjectCallbacks = JSWrapObjectCallbacks {
/// Callback to outerize windows. /// Callback to outerize windows.
pub unsafe extern fn outerize_global(_cx: *mut JSContext, obj: HandleObject) -> *mut JSObject { pub unsafe extern fn outerize_global(_cx: *mut JSContext, obj: HandleObject) -> *mut JSObject {
debug!("outerizing"); debug!("outerizing");
let win: Root<window::Window> = native_from_handleobject(obj).unwrap(); let win = root_from_handleobject::<window::Window>(obj).unwrap();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let win = win.r();
let context = win.browsing_context(); let context = win.browsing_context();
context.as_ref().unwrap().window_proxy() context.as_ref().unwrap().window_proxy()
} }

View file

@ -2,8 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::conversions::native_from_handleobject; use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
use dom::bindings::conversions::{ToJSValConvertible};
use dom::bindings::js::{JS, Root}; use dom::bindings::js::{JS, Root};
use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor};
use dom::bindings::reflector::{Reflectable, Reflector}; use dom::bindings::reflector::{Reflectable, Reflector};
@ -113,7 +112,7 @@ unsafe fn GetSubframeWindow(cx: *mut JSContext, proxy: HandleObject, id: HandleI
let index = get_array_index_from_id(cx, id); let index = get_array_index_from_id(cx, id);
if let Some(index) = index { if let Some(index) = index {
let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object()); let target = RootedObject::new(cx, GetProxyPrivate(*proxy.ptr).to_object());
let win: Root<Window> = native_from_handleobject(target.handle()).unwrap(); let win = root_from_handleobject::<Window>(target.handle()).unwrap();
let mut found = false; let mut found = false;
return win.IndexedGetter(index, &mut found); return win.IndexedGetter(index, &mut found);
} }

View file

@ -5,7 +5,7 @@
use devtools_traits::{StartedTimelineMarker, TimelineMarker, TimelineMarkerType}; use devtools_traits::{StartedTimelineMarker, TimelineMarker, TimelineMarkerType};
use dom::bindings::callback::ExceptionHandling::Report; use dom::bindings::callback::ExceptionHandling::Report;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::global::{GlobalRoot, global_object_for_reflector}; use dom::bindings::global::{GlobalRoot, global_root_from_reflector};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root, RootedReference}; use dom::bindings::js::{JS, Root, RootedReference};
use dom::bindings::trace::RootedVec; use dom::bindings::trace::RootedVec;
@ -49,7 +49,7 @@ fn dispatch_to_listeners(event: &Event, target: &EventTarget, chain: &[&EventTar
assert!(!event.stop_propagation()); assert!(!event.stop_propagation());
assert!(!event.stop_immediate()); assert!(!event.stop_immediate());
let window = match global_object_for_reflector(target) { let window = match global_root_from_reflector(target) {
GlobalRoot::Window(window) => { GlobalRoot::Window(window) => {
if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) { if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) {
Some(window) Some(window)

View file

@ -933,7 +933,7 @@ pub fn from_untrusted_node_address(_runtime: *mut JSRuntime, candidate: Untruste
if object.is_null() { if object.is_null() {
panic!("Attempted to create a `JS<Node>` from an invalid pointer!") panic!("Attempted to create a `JS<Node>` from an invalid pointer!")
} }
let boxed_node: *const Node = conversions::native_from_reflector(object); let boxed_node = conversions::private_from_object(object) as *const Node;
Root::from_ref(&*boxed_node) Root::from_ref(&*boxed_node)
} }
} }

View file

@ -12,8 +12,7 @@ use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions}; use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions};
use dom::bindings::codegen::Bindings::WindowBinding::{self, FrameRequestCallback, WindowMethods}; use dom::bindings::codegen::Bindings::WindowBinding::{self, FrameRequestCallback, WindowMethods};
use dom::bindings::error::{Error, Fallible, report_pending_exception}; use dom::bindings::error::{Error, Fallible, report_pending_exception};
use dom::bindings::global::GlobalRef; use dom::bindings::global::{GlobalRef, global_root_from_reflector};
use dom::bindings::global::global_object_for_js_object;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::RootedReference; use dom::bindings::js::RootedReference;
use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::js::{JS, MutNullableHeap, Root};
@ -766,8 +765,7 @@ impl<'a, T: Reflectable> ScriptHelpers for &'a T {
#[allow(unsafe_code)] #[allow(unsafe_code)]
fn evaluate_script_on_global_with_result(self, code: &str, filename: &str, fn evaluate_script_on_global_with_result(self, code: &str, filename: &str,
rval: MutableHandleValue) { rval: MutableHandleValue) {
let this = self.reflector().get_jsobject(); let global = global_root_from_reflector(self);
let global = global_object_for_js_object(this.get());
let cx = global.r().get_cx(); let cx = global.r().get_cx();
let _ar = JSAutoRequest::new(cx); let _ar = JSAutoRequest::new(cx);
let globalhandle = global.r().reflector().get_jsobject(); let globalhandle = global.r().reflector().get_jsobject();

View file

@ -5,7 +5,7 @@
use dom::bindings::callback::ExceptionHandling::Report; use dom::bindings::callback::ExceptionHandling::Report;
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FunctionBinding::Function; use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::global::global_object_for_js_object; use dom::bindings::global::global_root_from_reflector;
use dom::bindings::reflector::Reflectable; use dom::bindings::reflector::Reflectable;
use dom::bindings::trace::JSTraceable; use dom::bindings::trace::JSTraceable;
use dom::window::ScriptHelpers; use dom::window::ScriptHelpers;
@ -285,8 +285,7 @@ impl ActiveTimers {
// step 14 // step 14
match callback { match callback {
InternalTimerCallback::StringTimerCallback(code_str) => { InternalTimerCallback::StringTimerCallback(code_str) => {
let proxy = this.reflector().get_jsobject(); let cx = global_root_from_reflector(this).r().get_cx();
let cx = global_object_for_js_object(proxy.get()).r().get_cx();
let mut rval = RootedValue::new(cx, UndefinedValue()); let mut rval = RootedValue::new(cx, UndefinedValue());
this.evaluate_js_on_global_with_result(&code_str, rval.handle_mut()); this.evaluate_js_on_global_with_result(&code_str, rval.handle_mut());