Implement HTMLConstructor

This commit is contained in:
Connor Brewster 2017-06-07 13:55:42 -06:00
parent d883f55d0c
commit 2333b39569
7 changed files with 204 additions and 83 deletions

View file

@ -5301,11 +5301,79 @@ class CGClassConstructHook(CGAbstractExternMethod):
preamble += "let global = Root::downcast::<dom::types::%s>(global).unwrap();\n" % list(self.exposureSet)[0] preamble += "let global = Root::downcast::<dom::types::%s>(global).unwrap();\n" % list(self.exposureSet)[0]
preamble += """let args = CallArgs::from_vp(vp, argc);\n""" preamble += """let args = CallArgs::from_vp(vp, argc);\n"""
preamble = CGGeneric(preamble) preamble = CGGeneric(preamble)
name = self.constructor.identifier.name if self.constructor.isHTMLConstructor():
nativeName = MakeNativeName(self.descriptor.binaryNameFor(name)) signatures = self.constructor.signatures()
callGenerator = CGMethodCall(["&global"], nativeName, True, assert len(signatures) == 1
self.descriptor, self.constructor) constructorCall = CGGeneric("""\
return CGList([preamble, callGenerator]) // Step 2 https://html.spec.whatwg.org/multipage/#htmlconstructor
// The custom element definition cannot use an element interface as its constructor
// The new_target might be a cross-compartment wrapper. Get the underlying object
// 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::<GlobalScope>(), Error::Type("new.target is null".to_owned()));
return false;
}
if args.callee() == new_target.get() {
throw_dom_exception(cx, global.upcast::<GlobalScope>(),
Error::Type("new.target must not be the active function object".to_owned()));
return false;
}
// Step 6
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()) {
return false;
}
if !proto_val.is_object() {
// Step 7 of https://html.spec.whatwg.org/multipage/#htmlconstructor.
// This fallback behavior is designed to match analogous behavior for the
// JavaScript built-ins. So we enter the compartment of our underlying
// newTarget object and fall back to the prototype object from that global.
// XXX The spec says to use GetFunctionRealm(), which is not actually
// the same thing as what we have here (e.g. in the case of scripted callable proxies
// 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));
GetProtoObject(cx, global_object.handle(), prototype.handle_mut());
} else {
// Step 6
prototype.set(proto_val.to_object());
};
}
// Wrap prototype in this context since it is from the newTarget compartment
if !JS_WrapObject(cx, prototype.handle_mut()) {
return false;
}
let result: Result<Root<%s>, Error> = html_constructor(&global, &args);
let result = match result {
Ok(result) => result,
Err(e) => {
throw_dom_exception(cx, global.upcast::<GlobalScope>(), e);
return false;
},
};
JS_SetPrototype(cx, result.reflector().get_jsobject(), prototype.handle());
(result).to_jsval(cx, args.rval());
return true;
""" % self.descriptor.name)
else:
name = self.constructor.identifier.name
nativeName = MakeNativeName(self.descriptor.binaryNameFor(name))
constructorCall = CGMethodCall(["&global"], nativeName, True,
self.descriptor, self.constructor)
return CGList([preamble, constructorCall])
class CGClassFinalizeHook(CGAbstractClassHook): class CGClassFinalizeHook(CGAbstractClassHook):
@ -5517,9 +5585,11 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries
'js::jsapi::JS_ObjectIsDate', 'js::jsapi::JS_ObjectIsDate',
'js::jsapi::JS_SetImmutablePrototype', 'js::jsapi::JS_SetImmutablePrototype',
'js::jsapi::JS_SetProperty', 'js::jsapi::JS_SetProperty',
'js::jsapi::JS_SetPrototype',
'js::jsapi::JS_SetReservedSlot', 'js::jsapi::JS_SetReservedSlot',
'js::jsapi::JS_SplicePrototype', 'js::jsapi::JS_SplicePrototype',
'js::jsapi::JS_WrapValue', 'js::jsapi::JS_WrapValue',
'js::jsapi::JS_WrapObject',
'js::jsapi::MutableHandle', 'js::jsapi::MutableHandle',
'js::jsapi::MutableHandleObject', 'js::jsapi::MutableHandleObject',
'js::jsapi::MutableHandleValue', 'js::jsapi::MutableHandleValue',
@ -5547,6 +5617,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries
'js::glue::RUST_JSID_IS_STRING', 'js::glue::RUST_JSID_IS_STRING',
'js::glue::RUST_SYMBOL_TO_JSID', 'js::glue::RUST_SYMBOL_TO_JSID',
'js::glue::int_to_jsid', 'js::glue::int_to_jsid',
'js::glue::UnwrapObject',
'js::panic::maybe_resume_unwind', 'js::panic::maybe_resume_unwind',
'js::panic::wrap_panic', 'js::panic::wrap_panic',
'js::rust::GCMethods', 'js::rust::GCMethods',
@ -5561,14 +5632,15 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries
'dom::bindings::interface::ConstructorClassHook', 'dom::bindings::interface::ConstructorClassHook',
'dom::bindings::interface::InterfaceConstructorBehavior', 'dom::bindings::interface::InterfaceConstructorBehavior',
'dom::bindings::interface::NonCallbackInterfaceObjectClass', 'dom::bindings::interface::NonCallbackInterfaceObjectClass',
'dom::bindings::interface::create_callback_interface_object',
'dom::bindings::interface::create_global_object', 'dom::bindings::interface::create_global_object',
'dom::bindings::interface::create_callback_interface_object',
'dom::bindings::interface::create_interface_prototype_object', 'dom::bindings::interface::create_interface_prototype_object',
'dom::bindings::interface::create_named_constructors', 'dom::bindings::interface::create_named_constructors',
'dom::bindings::interface::create_noncallback_interface_object', 'dom::bindings::interface::create_noncallback_interface_object',
'dom::bindings::interface::define_guarded_constants', 'dom::bindings::interface::define_guarded_constants',
'dom::bindings::interface::define_guarded_methods', 'dom::bindings::interface::define_guarded_methods',
'dom::bindings::interface::define_guarded_properties', 'dom::bindings::interface::define_guarded_properties',
'dom::bindings::interface::html_constructor',
'dom::bindings::interface::is_exposed_in', 'dom::bindings::interface::is_exposed_in',
'dom::bindings::iterable::Iterable', 'dom::bindings::iterable::Iterable',
'dom::bindings::iterable::IteratorType', 'dom::bindings::iterable::IteratorType',

View file

@ -70,18 +70,26 @@ use dom::bindings::codegen::Bindings::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTrackElementBinding; use dom::bindings::codegen::Bindings::HTMLTrackElementBinding;
use dom::bindings::codegen::Bindings::HTMLUListElementBinding; use dom::bindings::codegen::Bindings::HTMLUListElementBinding;
use dom::bindings::codegen::Bindings::HTMLVideoElementBinding; use dom::bindings::codegen::Bindings::HTMLVideoElementBinding;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InterfaceObjectMap::Globals; use dom::bindings::codegen::InterfaceObjectMap::Globals;
use dom::bindings::codegen::PrototypeList; use dom::bindings::codegen::PrototypeList;
use dom::bindings::constant::{ConstantSpec, define_constants}; use dom::bindings::constant::{ConstantSpec, define_constants};
use dom::bindings::conversions::{DOM_OBJECT_SLOT, get_dom_class}; use dom::bindings::conversions::{DOM_OBJECT_SLOT, DerivedFrom, get_dom_class};
use dom::bindings::error::{Error, Fallible};
use dom::bindings::guard::Guard; use dom::bindings::guard::Guard;
use dom::bindings::js::Root;
use dom::bindings::utils::{DOM_PROTOTYPE_SLOT, ProtoOrIfaceArray, get_proto_or_iface_array}; use dom::bindings::utils::{DOM_PROTOTYPE_SLOT, ProtoOrIfaceArray, get_proto_or_iface_array};
use dom::create::create_native_html_element;
use dom::element::{Element, ElementCreator};
use dom::htmlelement::HTMLElement;
use dom::window::Window;
use html5ever::LocalName; use html5ever::LocalName;
use html5ever::interface::QualName;
use js::error::throw_type_error; use js::error::throw_type_error;
use js::glue::{RUST_SYMBOL_TO_JSID, UncheckedUnwrapObject}; use js::glue::{RUST_SYMBOL_TO_JSID, UncheckedUnwrapObject, UnwrapObject};
use js::jsapi::{Class, ClassOps, CompartmentOptions, GetGlobalForObjectCrossCompartment}; use js::jsapi::{CallArgs, Class, ClassOps, CompartmentOptions, CurrentGlobalOrNull};
use js::jsapi::{GetWellKnownSymbol, HandleObject, HandleValue, JSAutoCompartment}; use js::jsapi::{GetGlobalForObjectCrossCompartment, GetWellKnownSymbol, HandleObject, HandleValue};
use js::jsapi::{JSClass, JSContext, JSFUN_CONSTRUCTOR, JSFunctionSpec, JSObject}; use js::jsapi::{JSAutoCompartment, JSClass, JSContext, JSFUN_CONSTRUCTOR, JSFunctionSpec, JSObject};
use js::jsapi::{JSPROP_PERMANENT, JSPROP_READONLY, JSPROP_RESOLVING}; use js::jsapi::{JSPROP_PERMANENT, JSPROP_READONLY, JSPROP_RESOLVING};
use js::jsapi::{JSPropertySpec, JSString, JSTracer, JSVersion, JS_AtomizeAndPinString}; use js::jsapi::{JSPropertySpec, JSString, JSTracer, JSVersion, JS_AtomizeAndPinString};
use js::jsapi::{JS_DefineProperty, JS_DefineProperty1, JS_DefineProperty2}; use js::jsapi::{JS_DefineProperty, JS_DefineProperty1, JS_DefineProperty2};
@ -225,6 +233,69 @@ pub unsafe fn create_global_object(
JS_FireOnNewGlobalObject(cx, rval.handle()); JS_FireOnNewGlobalObject(cx, rval.handle());
} }
// https://html.spec.whatwg.org/multipage/#htmlconstructor
pub unsafe fn html_constructor<T>(window: &Window, call_args: &CallArgs) -> Fallible<Root<T>>
where T: DerivedFrom<Element> {
let document = window.Document();
// Step 1
let registry = window.CustomElements();
// Step 2 is checked in the generated caller code
// Step 3
rooted!(in(window.get_cx()) let new_target = call_args.new_target().to_object());
let definition = match registry.lookup_definition_by_constructor(new_target.handle()) {
Some(definition) => definition,
None => return Err(Error::Type("No custom element definition found for new.target".to_owned())),
};
rooted!(in(window.get_cx()) let callee = UnwrapObject(call_args.callee(), 1));
if callee.is_null() {
return Err(Error::Security);
}
{
let _ac = JSAutoCompartment::new(window.get_cx(), callee.get());
if definition.is_autonomous() {
// Step 4
// Since this element is autonomous, its active function object must be the HTMLElement
// Retrieve the constructor object for HTMLElement
rooted!(in(window.get_cx()) let mut constructor = ptr::null_mut());
rooted!(in(window.get_cx()) let global_object = CurrentGlobalOrNull(window.get_cx()));
HTMLElementBinding::GetConstructorObject(window.get_cx(), global_object.handle(), constructor.handle_mut());
// Callee must be the same constructor object as HTMLElement
if constructor.get() != callee.get() {
return Err(Error::Type("Active function object is not HTMLElement".to_owned()));
}
} else {
// TODO: Step 5
}
}
// Step 8.1
let name = QualName::new(None, ns!(html), definition.local_name.clone());
let element = if definition.is_autonomous() {
Root::upcast(HTMLElement::new(name.local, None, &*document))
} else {
create_native_html_element(name, None, &*document, ElementCreator::ScriptCreated)
};
// Step 8.2 is performed in the generated caller code.
// TODO: Step 8.3 - 8.4
// Set the element's custom element state and definition.
// Step 8.5
Root::downcast(element).ok_or(Error::InvalidState)
// TODO: Steps 9-13
// Custom element upgrades are not implemented yet, so these steps are unnecessary.
}
/// Create and define the interface object of a callback interface. /// Create and define the interface object of a callback interface.
pub unsafe fn create_callback_interface_object( pub unsafe fn create_callback_interface_object(
cx: *mut JSContext, cx: *mut JSContext,

View file

@ -107,10 +107,18 @@ fn create_svg_element(name: QualName,
} }
fn create_html_element(name: QualName, fn create_html_element(name: QualName,
prefix: Option<Prefix>, prefix: Option<Prefix>,
document: &Document, document: &Document,
creator: ElementCreator) creator: ElementCreator)
-> Root<Element> { -> Root<Element> {
create_native_html_element(name, prefix, document, creator)
}
pub fn create_native_html_element(name: QualName,
prefix: Option<Prefix>,
document: &Document,
creator: ElementCreator)
-> Root<Element> {
assert!(name.ns == ns!(html)); assert!(name.ns == ns!(html));
macro_rules! make( macro_rules! make(

View file

@ -18,6 +18,7 @@ use dom::globalscope::GlobalScope;
use dom::promise::Promise; use dom::promise::Promise;
use dom::window::Window; use dom::window::Window;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use html5ever::LocalName;
use js::conversions::ToJSValConvertible; use js::conversions::ToJSValConvertible;
use js::jsapi::{IsConstructor, HandleObject, JS_GetProperty, JSAutoCompartment, JSContext}; use js::jsapi::{IsConstructor, HandleObject, JS_GetProperty, JSAutoCompartment, JSContext};
use js::jsval::{JSVal, UndefinedValue}; use js::jsval::{JSVal, UndefinedValue};
@ -25,7 +26,7 @@ use std::cell::Cell;
use std::collections::HashMap; use std::collections::HashMap;
use std::rc::Rc; use std::rc::Rc;
// https://html.spec.whatwg.org/multipage/#customelementregistry /// https://html.spec.whatwg.org/multipage/#customelementregistry
#[dom_struct] #[dom_struct]
pub struct CustomElementRegistry { pub struct CustomElementRegistry {
reflector_: Reflector, reflector_: Reflector,
@ -37,7 +38,8 @@ pub struct CustomElementRegistry {
element_definition_is_running: Cell<bool>, element_definition_is_running: Cell<bool>,
definitions: DOMRefCell<HashMap<DOMString, CustomElementDefinition>>, #[ignore_heap_size_of = "Rc"]
definitions: DOMRefCell<HashMap<DOMString, Rc<CustomElementDefinition>>>,
} }
impl CustomElementRegistry { impl CustomElementRegistry {
@ -57,14 +59,20 @@ impl CustomElementRegistry {
CustomElementRegistryBinding::Wrap) CustomElementRegistryBinding::Wrap)
} }
// Cleans up any active promises /// Cleans up any active promises
// https://github.com/servo/servo/issues/15318 /// https://github.com/servo/servo/issues/15318
pub fn teardown(&self) { pub fn teardown(&self) {
self.when_defined.borrow_mut().clear() self.when_defined.borrow_mut().clear()
} }
// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define pub fn lookup_definition_by_constructor(&self, constructor: HandleObject) -> Option<Rc<CustomElementDefinition>> {
// Steps 10.1, 10.2 self.definitions.borrow().values().find(|definition| {
definition.constructor.callback() == constructor.get()
}).cloned()
}
/// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define
/// Steps 10.1, 10.2
#[allow(unsafe_code)] #[allow(unsafe_code)]
fn check_prototype(&self, constructor: HandleObject) -> ErrorResult { fn check_prototype(&self, constructor: HandleObject) -> ErrorResult {
let global_scope = self.window.upcast::<GlobalScope>(); let global_scope = self.window.upcast::<GlobalScope>();
@ -89,7 +97,7 @@ impl CustomElementRegistry {
impl CustomElementRegistryMethods for CustomElementRegistry { impl CustomElementRegistryMethods for CustomElementRegistry {
#[allow(unsafe_code, unrooted_must_root)] #[allow(unsafe_code, unrooted_must_root)]
// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define /// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define
fn Define(&self, name: DOMString, constructor_: Rc<Function>, options: &ElementDefinitionOptions) -> ErrorResult { fn Define(&self, name: DOMString, constructor_: Rc<Function>, options: &ElementDefinitionOptions) -> ErrorResult {
let global_scope = self.window.upcast::<GlobalScope>(); let global_scope = self.window.upcast::<GlobalScope>();
rooted!(in(global_scope.get_cx()) let constructor = constructor_.callback()); rooted!(in(global_scope.get_cx()) let constructor = constructor_.callback());
@ -129,10 +137,10 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
return Err(Error::NotSupported) return Err(Error::NotSupported)
} }
extended_name.clone() extended_name
} else { } else {
// Step 7.3 // Step 7.3
name.clone() &name
}; };
// Step 8 // Step 8
@ -157,10 +165,12 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
result?; result?;
// Step 11 // Step 11
let definition = CustomElementDefinition::new(name.clone(), local_name, constructor_); let definition = CustomElementDefinition::new(LocalName::from(&*name),
LocalName::from(&**local_name),
constructor_);
// Step 12 // Step 12
self.definitions.borrow_mut().insert(name.clone(), definition); self.definitions.borrow_mut().insert(name.clone(), Rc::new(definition));
// TODO: Step 13, 14, 15 // TODO: Step 13, 14, 15
// Handle custom element upgrades // Handle custom element upgrades
@ -175,7 +185,7 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
Ok(()) Ok(())
} }
// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-get /// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-get
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn Get(&self, cx: *mut JSContext, name: DOMString) -> JSVal { unsafe fn Get(&self, cx: *mut JSContext, name: DOMString) -> JSVal {
match self.definitions.borrow().get(&name) { match self.definitions.borrow().get(&name) {
@ -188,7 +198,7 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
} }
} }
// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-whendefined /// https://html.spec.whatwg.org/multipage/#dom-customelementregistry-whendefined
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
fn WhenDefined(&self, name: DOMString) -> Rc<Promise> { fn WhenDefined(&self, name: DOMString) -> Rc<Promise> {
let global_scope = self.window.upcast::<GlobalScope>(); let global_scope = self.window.upcast::<GlobalScope>();
@ -222,27 +232,33 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
} }
} }
#[derive(HeapSizeOf, JSTraceable)] /// https://html.spec.whatwg.org/multipage/#custom-element-definition
struct CustomElementDefinition { #[derive(HeapSizeOf, JSTraceable, Clone)]
name: DOMString, pub struct CustomElementDefinition {
pub name: LocalName,
local_name: DOMString, pub local_name: LocalName,
#[ignore_heap_size_of = "Rc"] #[ignore_heap_size_of = "Rc"]
constructor: Rc<Function>, pub constructor: Rc<Function>,
} }
impl CustomElementDefinition { impl CustomElementDefinition {
fn new(name: DOMString, local_name: DOMString, constructor: Rc<Function>) -> CustomElementDefinition { fn new(name: LocalName, local_name: LocalName, constructor: Rc<Function>) -> CustomElementDefinition {
CustomElementDefinition { CustomElementDefinition {
name: name, name: name,
local_name: local_name, local_name: local_name,
constructor: constructor, constructor: constructor,
} }
} }
/// https://html.spec.whatwg.org/multipage/#autonomous-custom-element
pub fn is_autonomous(&self) -> bool {
self.name == self.local_name
}
} }
// https://html.spec.whatwg.org/multipage/#valid-custom-element-name /// https://html.spec.whatwg.org/multipage/#valid-custom-element-name
fn is_valid_custom_element_name(name: &str) -> bool { fn is_valid_custom_element_name(name: &str) -> bool {
// Custom elment names must match: // Custom elment names must match:
// PotentialCustomElementName ::= [a-z] (PCENChar)* '-' (PCENChar)* // PotentialCustomElementName ::= [a-z] (PCENChar)* '-' (PCENChar)*
@ -284,8 +300,8 @@ fn is_valid_custom_element_name(name: &str) -> bool {
true true
} }
// Check if this character is a PCENChar /// Check if this character is a PCENChar
// https://html.spec.whatwg.org/multipage/#prod-pcenchar /// https://html.spec.whatwg.org/multipage/#prod-pcenchar
fn is_potential_custom_element_char(c: char) -> bool { fn is_potential_custom_element_char(c: char) -> bool {
c == '-' || c == '.' || c == '_' || c == '\u{B7}' || c == '-' || c == '.' || c == '_' || c == '\u{B7}' ||
(c >= '0' && c <= '9') || (c >= '0' && c <= '9') ||

View file

@ -27,9 +27,6 @@
[customElements.define must rethrow an exception thrown while retrieving Symbol.iterator on observedAttributes] [customElements.define must rethrow an exception thrown while retrieving Symbol.iterator on observedAttributes]
expected: FAIL expected: FAIL
[customElements.define must define an instantiatable custom element]
expected: FAIL
[customElements.define must upgrade elements in the shadow-including tree order] [customElements.define must upgrade elements in the shadow-including tree order]
expected: FAIL expected: FAIL

View file

@ -1,11 +0,0 @@
[HTMLElement-constructor.html]
type: testharness
[HTMLElement constructor must infer the tag name from the element interface]
expected: FAIL
[HTMLElement constructor must allow subclassing a custom element]
expected: FAIL
[HTMLElement constructor must allow subclassing an user-defined subclass of HTMLElement]
expected: FAIL

View file

@ -1,32 +0,0 @@
[newtarget.html]
type: testharness
[Use NewTarget's prototype, not the one stored at definition time]
expected: FAIL
[Rethrow any exceptions thrown while getting the prototype]
expected: FAIL
[If prototype is not object (null), derives the fallback from NewTarget's realm (autonomous custom elements)]
expected: FAIL
[If prototype is not object (undefined), derives the fallback from NewTarget's realm (autonomous custom elements)]
expected: FAIL
[If prototype is not object (5), derives the fallback from NewTarget's realm (autonomous custom elements)]
expected: FAIL
[If prototype is not object (string), derives the fallback from NewTarget's realm (autonomous custom elements)]
expected: FAIL
[If prototype is not object (null), derives the fallback from NewTarget's realm (customized built-in elements)]
expected: FAIL
[If prototype is not object (undefined), derives the fallback from NewTarget's realm (customized built-in elements)]
expected: FAIL
[If prototype is not object (5), derives the fallback from NewTarget's realm (customized built-in elements)]
expected: FAIL
[If prototype is not object (string), derives the fallback from NewTarget's realm (customized built-in elements)]
expected: FAIL