mirror of
https://github.com/servo/servo.git
synced 2025-08-11 00:15:32 +01:00
Auto merge of #8041 - nox:castable, r=jdm
Introduce trait Castable Removes all those messy FooCast structures in InheritTypes.rs. <!-- Reviewable:start --> [<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/servo/servo/8041) <!-- Reviewable:end -->
This commit is contained in:
commit
674589c370
84 changed files with 1193 additions and 1511 deletions
|
@ -2246,20 +2246,24 @@ class CGIDLInterface(CGThing):
|
|||
self.descriptor = descriptor
|
||||
|
||||
def define(self):
|
||||
replacer = {
|
||||
'type': self.descriptor.name,
|
||||
'depth': self.descriptor.interface.inheritanceDepth(),
|
||||
}
|
||||
return string.Template("""\
|
||||
impl IDLInterface for ${type} {
|
||||
fn get_prototype_id() -> PrototypeList::ID {
|
||||
PrototypeList::ID::${type}
|
||||
}
|
||||
fn get_prototype_depth() -> usize {
|
||||
${depth}
|
||||
interface = self.descriptor.interface
|
||||
name = self.descriptor.name
|
||||
if (interface.getUserData("hasConcreteDescendant", False) or
|
||||
interface.getUserData("hasProxyDescendant", False)):
|
||||
depth = len(self.descriptor.prototypeChain)
|
||||
check = "class.interface_chain[%s] == PrototypeList::ID::%s" % (depth - 1, name)
|
||||
elif self.descriptor.proxy:
|
||||
check = "class as *const _ == &Class as *const _"
|
||||
else:
|
||||
check = "class as *const _ == &Class.dom_class as *const _"
|
||||
return """\
|
||||
impl IDLInterface for %(name)s {
|
||||
#[inline]
|
||||
fn derives(class: &'static DOMClass) -> bool {
|
||||
%(check)s
|
||||
}
|
||||
}
|
||||
""").substitute(replacer)
|
||||
""" % {'check': check, 'name': name}
|
||||
|
||||
|
||||
class CGAbstractExternMethod(CGAbstractMethod):
|
||||
|
@ -5820,7 +5824,7 @@ class GlobalGenRoots():
|
|||
|
||||
descriptors = config.getDescriptors(register=True, isCallback=False)
|
||||
imports = [CGGeneric("use dom::types::*;\n"),
|
||||
CGGeneric("use dom::bindings::conversions::get_dom_class;\n"),
|
||||
CGGeneric("use dom::bindings::conversions::{Castable, DerivedFrom, get_dom_class};\n"),
|
||||
CGGeneric("use dom::bindings::js::{JS, LayoutJS, Root};\n"),
|
||||
CGGeneric("use dom::bindings::trace::JSTraceable;\n"),
|
||||
CGGeneric("use dom::bindings::utils::Reflectable;\n"),
|
||||
|
@ -5835,138 +5839,24 @@ class GlobalGenRoots():
|
|||
upcast = descriptor.hasDescendants()
|
||||
downcast = len(chain) != 1
|
||||
|
||||
if upcast or downcast:
|
||||
# Define a dummy structure to hold the cast functions.
|
||||
allprotos.append(CGGeneric("pub struct %sCast;\n\n" % name))
|
||||
|
||||
if upcast and not downcast:
|
||||
topTypes.append(name)
|
||||
|
||||
if upcast:
|
||||
# Define a `FooBase` trait for subclasses to implement, as well as the
|
||||
# `FooCast::from_*` methods that use it.
|
||||
allprotos.append(CGGeneric("""\
|
||||
/// Types which are derived from `%(name)s` and can be freely converted
|
||||
/// to `%(name)s`
|
||||
pub trait %(baseTrait)s: Sized {}
|
||||
if not upcast:
|
||||
# No other interface will implement DeriveFrom<Foo> for this Foo, so avoid
|
||||
# implementing it for itself.
|
||||
chain = chain[:-1]
|
||||
|
||||
impl %(name)sCast {
|
||||
#[inline]
|
||||
/// Upcast an instance of a derived class of `%(name)s` to `%(name)s`
|
||||
pub fn from_ref<T: %(baseTrait)s + Reflectable>(derived: &T) -> &%(name)s {
|
||||
unsafe { mem::transmute(derived) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[allow(unrooted_must_root)]
|
||||
pub fn from_layout_js<T: %(baseTrait)s + Reflectable>(derived: &LayoutJS<T>) -> LayoutJS<%(name)s> {
|
||||
unsafe { mem::transmute_copy(derived) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_root<T: %(baseTrait)s + Reflectable>(derived: Root<T>) -> Root<%(name)s> {
|
||||
unsafe { mem::transmute(derived) }
|
||||
}
|
||||
}
|
||||
|
||||
""" % {'baseTrait': name + 'Base', 'name': name}))
|
||||
else:
|
||||
# The `FooBase` trait is not defined, so avoid implementing it by
|
||||
# removing `Foo` itself from the chain.
|
||||
chain = descriptor.prototypeChain[:-1]
|
||||
|
||||
# Implement `BarBase` for `Foo`, for all `Bar` that `Foo` inherits from.
|
||||
# Implement `DerivedFrom<Bar>` for `Foo`, for all `Bar` that `Foo` inherits from.
|
||||
if chain:
|
||||
allprotos.append(CGGeneric("impl Castable for %s {}\n" % name))
|
||||
for baseName in chain:
|
||||
allprotos.append(CGGeneric("impl %s for %s {}\n" % (baseName + 'Base', name)))
|
||||
allprotos.append(CGGeneric("impl DerivedFrom<%s> for %s {}\n" % (baseName, name)))
|
||||
if chain:
|
||||
allprotos.append(CGGeneric("\n"))
|
||||
|
||||
if downcast:
|
||||
hierarchy[descriptor.getParentName()].append(name)
|
||||
# Define a `FooDerived` trait for superclasses to implement,
|
||||
# as well as the `FooCast::to_*` methods that use it.
|
||||
baseName = descriptor.prototypeChain[0]
|
||||
typeIdPat = descriptor.prototypeChain[-1]
|
||||
if upcast:
|
||||
typeIdPat += "(_)"
|
||||
for base in reversed(descriptor.prototypeChain[1:-1]):
|
||||
typeIdPat = "%s(%sTypeId::%s)" % (base, base, typeIdPat)
|
||||
typeIdPat = "%sTypeId::%s" % (baseName, typeIdPat)
|
||||
args = {
|
||||
'baseName': baseName,
|
||||
'derivedTrait': name + 'Derived',
|
||||
'methodName': 'is_' + name.lower(),
|
||||
'name': name,
|
||||
'typeIdPat': typeIdPat,
|
||||
}
|
||||
allprotos.append(CGGeneric("""\
|
||||
/// Types which `%(name)s` derives from
|
||||
pub trait %(derivedTrait)s: Sized {
|
||||
fn %(methodName)s(&self) -> bool;
|
||||
}
|
||||
|
||||
impl %(name)sCast {
|
||||
#[inline]
|
||||
/// Downcast an instance of a base class of `%(name)s` to an instance of
|
||||
/// `%(name)s`, if it internally is an instance of `%(name)s`
|
||||
pub fn to_ref<T: %(derivedTrait)s + Reflectable>(base: &T) -> Option<&%(name)s> {
|
||||
match base.%(methodName)s() {
|
||||
true => Some(unsafe { mem::transmute(base) }),
|
||||
false => None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[allow(unrooted_must_root)]
|
||||
pub fn to_layout_js<T: %(derivedTrait)s + Reflectable>(base: &LayoutJS<T>) -> Option<LayoutJS<%(name)s>> {
|
||||
unsafe {
|
||||
match (*base.unsafe_get()).%(methodName)s() {
|
||||
true => Some(mem::transmute_copy(base)),
|
||||
false => None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_root<T: %(derivedTrait)s + Reflectable>(base: Root<T>) -> Option<Root<%(name)s>> {
|
||||
match base.%(methodName)s() {
|
||||
true => Some(unsafe { mem::transmute(base) }),
|
||||
false => None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl %(derivedTrait)s for %(baseName)s {
|
||||
fn %(methodName)s(&self) -> bool {
|
||||
match *self.type_id() {
|
||||
%(typeIdPat)s => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
""" % args))
|
||||
|
||||
# Implement the `FooDerived` trait for non-root superclasses by deferring to
|
||||
# the direct superclass. This leaves the implementation of the `FooDerived`
|
||||
# trait for the root superclass to manual code. `FooDerived` is not
|
||||
# implemented for `Foo` itself.
|
||||
for baseName in descriptor.prototypeChain[1:-1]:
|
||||
args = {
|
||||
'baseName': baseName,
|
||||
'derivedTrait': name + 'Derived',
|
||||
'methodName': 'is_' + name.lower(),
|
||||
'parentName': config.getDescriptor(baseName).getParentName(),
|
||||
}
|
||||
allprotos.append(CGGeneric("""\
|
||||
impl %(derivedTrait)s for %(baseName)s {
|
||||
#[inline]
|
||||
fn %(methodName)s(&self) -> bool {
|
||||
%(parentName)sCast::from_ref(self).%(methodName)s()
|
||||
}
|
||||
}
|
||||
|
||||
""" % args))
|
||||
|
||||
typeIdCode = []
|
||||
topTypeVariants = [
|
||||
|
|
|
@ -33,7 +33,6 @@
|
|||
//! | union types | `T` |
|
||||
|
||||
use core::nonzero::NonZero;
|
||||
use dom::bindings::codegen::PrototypeList;
|
||||
use dom::bindings::error::throw_type_error;
|
||||
use dom::bindings::js::Root;
|
||||
use dom::bindings::num::Finite;
|
||||
|
@ -56,6 +55,7 @@ use libc;
|
|||
use num::Float;
|
||||
use num::traits::{Bounded, Zero};
|
||||
use std::borrow::ToOwned;
|
||||
use std::mem;
|
||||
use std::rc::Rc;
|
||||
use std::{char, ptr, slice};
|
||||
use util::str::DOMString;
|
||||
|
@ -101,16 +101,42 @@ impl_as!(u32, u32);
|
|||
impl_as!(i64, i64);
|
||||
impl_as!(u64, u64);
|
||||
|
||||
/// A trait to retrieve the constants necessary to check if a `JSObject`
|
||||
/// implements a given interface.
|
||||
/// A trait to check whether a given `JSObject` implements an IDL interface.
|
||||
pub trait IDLInterface {
|
||||
/// Returns the prototype ID.
|
||||
fn get_prototype_id() -> PrototypeList::ID;
|
||||
/// Returns the prototype depth, i.e., the number of interfaces this
|
||||
/// interface inherits from.
|
||||
fn get_prototype_depth() -> usize;
|
||||
/// Returns whether the given DOM class derives that interface.
|
||||
fn derives(&'static DOMClass) -> bool;
|
||||
}
|
||||
|
||||
/// A trait to hold the cast functions of IDL interfaces that either derive
|
||||
/// or are derived from other interfaces.
|
||||
pub trait Castable: IDLInterface + Reflectable + Sized {
|
||||
/// Check whether a DOM object implements one of its deriving interfaces.
|
||||
fn is<T>(&self) -> bool where T: DerivedFrom<Self> {
|
||||
let class = unsafe {
|
||||
get_dom_class(self.reflector().get_jsobject().get()).unwrap()
|
||||
};
|
||||
T::derives(class)
|
||||
}
|
||||
|
||||
/// Cast a DOM object upwards to one of the interfaces it derives from.
|
||||
fn upcast<T>(&self) -> &T where T: Castable, Self: DerivedFrom<T> {
|
||||
unsafe { mem::transmute(self) }
|
||||
}
|
||||
|
||||
/// Cast a DOM object downwards to one of the interfaces it might implement.
|
||||
fn downcast<T>(&self) -> Option<&T> where T: DerivedFrom<Self> {
|
||||
if self.is::<T>() {
|
||||
Some(unsafe { mem::transmute(self) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait to mark an IDL interface as deriving from another one.
|
||||
#[rustc_on_unimplemented = "The IDL interface `{Self}` is not derived from `{T}`."]
|
||||
pub trait DerivedFrom<T: Castable>: Castable {}
|
||||
|
||||
/// A trait to convert Rust types to `JSVal`s.
|
||||
pub trait ToJSValConvertible {
|
||||
/// Convert `self` to a `JSVal`. JSAPI failure causes a task failure.
|
||||
|
@ -696,9 +722,10 @@ pub unsafe fn get_dom_class(obj: *mut JSObject) -> Result<&'static DOMClass, ()>
|
|||
/// Returns Err(()) if `obj` is an opaque security wrapper or if the object is
|
||||
/// not an object for a DOM object of the given type (as defined by the
|
||||
/// proto_id and proto_depth).
|
||||
pub unsafe fn private_from_proto_chain(mut obj: *mut JSObject,
|
||||
proto_id: u16, proto_depth: u16)
|
||||
-> Result<*const libc::c_void, ()> {
|
||||
#[inline]
|
||||
pub unsafe fn private_from_proto_check<F>(mut obj: *mut JSObject, proto_check: F)
|
||||
-> Result<*const libc::c_void, ()>
|
||||
where F: Fn(&'static DOMClass) -> bool {
|
||||
let dom_class = try!(get_dom_class(obj).or_else(|_| {
|
||||
if IsWrapper(obj) {
|
||||
debug!("found wrapper");
|
||||
|
@ -717,7 +744,7 @@ pub unsafe fn private_from_proto_chain(mut obj: *mut JSObject,
|
|||
}
|
||||
}));
|
||||
|
||||
if dom_class.interface_chain[proto_depth as usize] as u16 == proto_id {
|
||||
if proto_check(dom_class) {
|
||||
debug!("good prototype");
|
||||
Ok(private_from_reflector(obj))
|
||||
} else {
|
||||
|
@ -735,10 +762,8 @@ pub unsafe fn private_from_proto_chain(mut obj: *mut JSObject,
|
|||
pub fn native_from_reflector_jsmanaged<T>(obj: *mut JSObject) -> Result<Root<T>, ()>
|
||||
where T: Reflectable + IDLInterface
|
||||
{
|
||||
let proto_id = <T as IDLInterface>::get_prototype_id() as u16;
|
||||
let proto_depth = <T as IDLInterface>::get_prototype_depth() as u16;
|
||||
unsafe {
|
||||
private_from_proto_chain(obj, proto_id, proto_depth).map(|obj| {
|
||||
private_from_proto_check(obj, T::derives).map(|obj| {
|
||||
Root::new(NonZero::new(obj as *const T))
|
||||
})
|
||||
}
|
||||
|
|
|
@ -24,6 +24,7 @@
|
|||
//!
|
||||
|
||||
use core::nonzero::NonZero;
|
||||
use dom::bindings::conversions::{Castable, DerivedFrom};
|
||||
use dom::bindings::trace::JSTraceable;
|
||||
use dom::bindings::trace::trace_reflector;
|
||||
use dom::bindings::utils::{Reflectable, Reflector};
|
||||
|
@ -34,6 +35,7 @@ use layout_interface::TrustedNodeAddress;
|
|||
use script_task::STACK_ROOTS;
|
||||
use std::cell::UnsafeCell;
|
||||
use std::default::Default;
|
||||
use std::mem;
|
||||
use std::ops::Deref;
|
||||
use std::ptr;
|
||||
use util::mem::HeapSizeOf;
|
||||
|
@ -112,6 +114,24 @@ pub struct LayoutJS<T> {
|
|||
ptr: NonZero<*const T>
|
||||
}
|
||||
|
||||
impl<T: Castable> LayoutJS<T> {
|
||||
/// Cast a DOM object root upwards to one of the interfaces it derives from.
|
||||
pub fn upcast<U>(&self) -> LayoutJS<U> where U: Castable, T: DerivedFrom<U> {
|
||||
unsafe { mem::transmute_copy(self) }
|
||||
}
|
||||
|
||||
/// Cast a DOM object downwards to one of the interfaces it might implement.
|
||||
pub fn downcast<U>(&self) -> Option<LayoutJS<U>> where U: DerivedFrom<T> {
|
||||
unsafe {
|
||||
if (*self.unsafe_get()).is::<U>() {
|
||||
Some(mem::transmute_copy(self))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Reflectable> LayoutJS<T> {
|
||||
/// Get the reflector.
|
||||
pub unsafe fn get_jsobject(&self) -> *mut JSObject {
|
||||
|
@ -440,6 +460,22 @@ pub struct Root<T: Reflectable> {
|
|||
root_list: *const RootCollection,
|
||||
}
|
||||
|
||||
impl<T: Castable> Root<T> {
|
||||
/// Cast a DOM object root upwards to one of the interfaces it derives from.
|
||||
pub fn upcast<U>(root: Root<T>) -> Root<U> where U: Castable, T: DerivedFrom<U> {
|
||||
unsafe { mem::transmute(root) }
|
||||
}
|
||||
|
||||
/// Cast a DOM object root downwards to one of the interfaces it might implement.
|
||||
pub fn downcast<U>(root: Root<T>) -> Option<Root<U>> where U: DerivedFrom<T> {
|
||||
if root.is::<U>() {
|
||||
Some(unsafe { mem::transmute(root) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Reflectable> Root<T> {
|
||||
/// Create a new stack-bounded root for the provided JS-owned value.
|
||||
/// It cannot not outlive its associated `RootCollection`, and it gives
|
||||
|
|
|
@ -8,7 +8,7 @@ use dom::bindings::codegen::InheritTypes::TopTypeId;
|
|||
use dom::bindings::codegen::PrototypeList;
|
||||
use dom::bindings::codegen::PrototypeList::MAX_PROTO_CHAIN_LENGTH;
|
||||
use dom::bindings::conversions::native_from_handleobject;
|
||||
use dom::bindings::conversions::private_from_proto_chain;
|
||||
use dom::bindings::conversions::private_from_proto_check;
|
||||
use dom::bindings::conversions::{is_dom_class, jsstring_to_str};
|
||||
use dom::bindings::error::throw_type_error;
|
||||
use dom::bindings::error::{Error, ErrorResult, Fallible, throw_invalid_this};
|
||||
|
@ -755,7 +755,10 @@ unsafe fn generic_call(cx: *mut JSContext, argc: libc::c_uint, vp: *mut JSVal,
|
|||
let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));
|
||||
let proto_id = (*info).protoID;
|
||||
let depth = (*info).depth;
|
||||
let this = match private_from_proto_chain(obj.ptr, proto_id, depth) {
|
||||
let proto_check = |class: &'static DOMClass| {
|
||||
class.interface_chain[depth as usize] as u16 == proto_id
|
||||
};
|
||||
let this = match private_from_proto_check(obj.ptr, proto_check) {
|
||||
Ok(val) => val,
|
||||
Err(()) => {
|
||||
if is_lenient {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue