script/dom/bindings/
constructor.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::ptr;
6
7use html5ever::interface::QualName;
8use html5ever::{LocalName, local_name, ns};
9use js::glue::{UnwrapObjectDynamic, UnwrapObjectStatic};
10use js::jsapi::{CallArgs, JSObject};
11use js::realm::AutoRealm;
12use js::rust::wrappers2::{JS_SetPrototype, JS_WrapObject};
13use js::rust::{HandleObject, MutableHandleObject, MutableHandleValue};
14use script_bindings::conversions::SafeToJSValConvertible;
15use script_bindings::interface::get_desired_proto;
16
17use super::utils::ProtoOrIfaceArray;
18use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
19use crate::dom::bindings::codegen::Bindings::{
20    HTMLAnchorElementBinding, HTMLAreaElementBinding, HTMLAudioElementBinding,
21    HTMLBRElementBinding, HTMLBaseElementBinding, HTMLBodyElementBinding, HTMLButtonElementBinding,
22    HTMLCanvasElementBinding, HTMLDListElementBinding, HTMLDataElementBinding,
23    HTMLDataListElementBinding, HTMLDetailsElementBinding, HTMLDialogElementBinding,
24    HTMLDirectoryElementBinding, HTMLDivElementBinding, HTMLElementBinding,
25    HTMLEmbedElementBinding, HTMLFieldSetElementBinding, HTMLFontElementBinding,
26    HTMLFormElementBinding, HTMLFrameElementBinding, HTMLFrameSetElementBinding,
27    HTMLHRElementBinding, HTMLHeadElementBinding, HTMLHeadingElementBinding,
28    HTMLHtmlElementBinding, HTMLIFrameElementBinding, HTMLImageElementBinding,
29    HTMLInputElementBinding, HTMLLIElementBinding, HTMLLabelElementBinding,
30    HTMLLegendElementBinding, HTMLLinkElementBinding, HTMLMapElementBinding,
31    HTMLMarqueeElementBinding, HTMLMenuElementBinding, HTMLMetaElementBinding,
32    HTMLMeterElementBinding, HTMLModElementBinding, HTMLOListElementBinding,
33    HTMLObjectElementBinding, HTMLOptGroupElementBinding, HTMLOptionElementBinding,
34    HTMLOutputElementBinding, HTMLParagraphElementBinding, HTMLParamElementBinding,
35    HTMLPictureElementBinding, HTMLPreElementBinding, HTMLProgressElementBinding,
36    HTMLQuoteElementBinding, HTMLScriptElementBinding, HTMLSelectElementBinding,
37    HTMLSlotElementBinding, HTMLSourceElementBinding, HTMLSpanElementBinding,
38    HTMLStyleElementBinding, HTMLTableCaptionElementBinding, HTMLTableCellElementBinding,
39    HTMLTableColElementBinding, HTMLTableElementBinding, HTMLTableRowElementBinding,
40    HTMLTableSectionElementBinding, HTMLTemplateElementBinding, HTMLTextAreaElementBinding,
41    HTMLTimeElementBinding, HTMLTitleElementBinding, HTMLTrackElementBinding,
42    HTMLUListElementBinding, HTMLVideoElementBinding,
43};
44use crate::dom::bindings::codegen::PrototypeList;
45use crate::dom::bindings::conversions::DerivedFrom;
46use crate::dom::bindings::error::{Error, throw_dom_exception};
47use crate::dom::bindings::inheritance::Castable;
48use crate::dom::bindings::reflector::DomObject;
49use crate::dom::bindings::root::DomRoot;
50use crate::dom::create::create_native_html_element;
51use crate::dom::customelementregistry::{ConstructionStackEntry, CustomElementState};
52use crate::dom::element::{Element, ElementCreator};
53use crate::dom::globalscope::GlobalScope;
54use crate::dom::html::htmlelement::HTMLElement;
55use crate::dom::window::Window;
56use crate::script_runtime::CanGc;
57
58/// <https://html.spec.whatwg.org/multipage/#htmlconstructor>
59fn html_constructor(
60    cx: &mut js::context::JSContext,
61    global: &GlobalScope,
62    call_args: &CallArgs,
63    check_type: fn(&Element) -> bool,
64    proto_id: PrototypeList::ID,
65    creator: unsafe fn(&mut js::context::JSContext, HandleObject, *mut ProtoOrIfaceArray),
66) -> Result<(), ()> {
67    let window = global.downcast::<Window>().unwrap();
68    let document = window.Document();
69
70    // Step 1. Let registry be current global object's custom element registry.
71    let registry = window.CustomElements();
72
73    // Step 2 https://html.spec.whatwg.org/multipage/#htmlconstructor
74    // The custom element definition cannot use an element interface as its constructor
75
76    // The new_target might be a cross-compartment wrapper. Get the underlying object
77    // so we can do the spec's object-identity checks.
78    rooted!(&in(cx) let new_target_unwrapped = unsafe {
79        UnwrapObjectDynamic(call_args.new_target().to_object(), cx.raw_cx(), true)
80    });
81    if new_target_unwrapped.is_null() {
82        throw_dom_exception(
83            cx.into(),
84            global,
85            Error::Type(c"new.target is null".to_owned()),
86            CanGc::from_cx(cx),
87        );
88        return Err(());
89    }
90    if call_args.callee() == new_target_unwrapped.get() {
91        throw_dom_exception(
92            cx.into(),
93            global,
94            Error::Type(c"Illegal constructor.".to_owned()),
95            CanGc::from_cx(cx),
96        );
97        return Err(());
98    }
99
100    // Step 3. Let definition be the item in registry's custom element definition set with constructor
101    // equal to NewTarget. If there is no such item, then throw a TypeError.
102    rooted!(&in(cx) let new_target = call_args.new_target().to_object());
103    let definition = match registry.lookup_definition_by_constructor(new_target.handle()) {
104        Some(definition) => definition,
105        None => {
106            throw_dom_exception(
107                cx.into(),
108                global,
109                Error::Type(c"No custom element definition found for new.target".to_owned()),
110                CanGc::from_cx(cx),
111            );
112            return Err(());
113        },
114    };
115
116    // Step 4. Let isValue be null.
117    let mut is_value = None;
118
119    rooted!(&in(cx) let callee = unsafe { UnwrapObjectStatic(call_args.callee()) });
120    if callee.is_null() {
121        throw_dom_exception(cx.into(), global, Error::Security(None), CanGc::from_cx(cx));
122        return Err(());
123    }
124
125    {
126        let mut realm = AutoRealm::new_from_handle(cx, callee.handle());
127        let (global_object, cx) = realm.global_and_reborrow();
128        rooted!(&in(cx) let mut constructor = ptr::null_mut::<JSObject>());
129
130        // Step 5. If definition's local name is equal to definition's name
131        // (i.e., definition is for an autonomous custom element):
132        if definition.is_autonomous() {
133            // Since this element is autonomous, its active function object must be the HTMLElement
134            // Retrieve the constructor object for HTMLElement
135            HTMLElementBinding::GetConstructorObject(cx, global_object, constructor.handle_mut());
136        }
137        // Step 6. Otherwise (i.e., if definition is for a customized built-in element):
138        else {
139            get_constructor_object_from_local_name(
140                definition.local_name.clone(),
141                cx,
142                global_object,
143                constructor.handle_mut(),
144            );
145
146            // Step 6.3 Set isValue to definition's name.
147            is_value = Some(definition.name.clone());
148        }
149        // Callee must be the same as the element interface's constructor object.
150        if constructor.get() != callee.get() {
151            throw_dom_exception(
152                cx.into(),
153                global,
154                Error::Type(c"Custom element does not extend the proper interface".to_owned()),
155                CanGc::from_cx(cx),
156            );
157            return Err(());
158        }
159    }
160
161    // Step 6
162    rooted!(&in(cx) let mut prototype = ptr::null_mut::<JSObject>());
163    get_desired_proto(cx, call_args, proto_id, creator, prototype.handle_mut())?;
164
165    let entry = definition.construction_stack.borrow().last().cloned();
166    let result = match entry {
167        // Step 7. If definition's construction stack is empty:
168        None => {
169            // Step 7.1
170            let name = QualName::new(None, ns!(html), definition.local_name.clone());
171            // Any prototype used to create these elements will be overwritten before returning
172            // from this function, so we don't bother overwriting the defaults here.
173            let element = if definition.is_autonomous() {
174                DomRoot::upcast(HTMLElement::new(cx, name.local, None, &document, None))
175            } else {
176                create_native_html_element(
177                    cx,
178                    name,
179                    None,
180                    &document,
181                    ElementCreator::ScriptCreated,
182                    None,
183                )
184            };
185
186            // Step 7.2-7.5 are performed in the generated caller code.
187
188            // Step 7.6 Set element's custom element state to "custom".
189            element.set_custom_element_state(CustomElementState::Custom);
190
191            // Step 7.7 Set element's custom element definition to definition.
192            element.set_custom_element_definition(definition);
193
194            // Step 7.8 Set element's is value to isValue.
195            if let Some(is_value) = is_value {
196                element.set_is(is_value);
197            }
198
199            if !check_type(&element) {
200                throw_dom_exception(
201                    cx.into(),
202                    global,
203                    Error::InvalidState(None),
204                    CanGc::from_cx(cx),
205                );
206                return Err(());
207            } else {
208                // Step 7.9 Return element.
209                element
210            }
211        },
212        // Step 9
213        Some(ConstructionStackEntry::Element(element)) => {
214            // Step 11 is performed in the generated caller code.
215
216            // Step 12
217            let mut construction_stack = definition.construction_stack.borrow_mut();
218            construction_stack.pop();
219            construction_stack.push(ConstructionStackEntry::AlreadyConstructedMarker);
220
221            // Step 13
222            if !check_type(&element) {
223                throw_dom_exception(
224                    cx.into(),
225                    global,
226                    Error::InvalidState(None),
227                    CanGc::from_cx(cx),
228                );
229                return Err(());
230            } else {
231                element
232            }
233        },
234        // Step 10
235        Some(ConstructionStackEntry::AlreadyConstructedMarker) => {
236            let s = c"Top of construction stack marked AlreadyConstructed due to \
237                     a custom element constructor constructing itself after super()"
238                .to_owned();
239            throw_dom_exception(cx.into(), global, Error::Type(s), CanGc::from_cx(cx));
240            return Err(());
241        },
242    };
243
244    rooted!(&in(cx) let mut element = result.reflector().get_jsobject().get());
245    unsafe {
246        if !JS_WrapObject(cx, element.handle_mut()) {
247            return Err(());
248        }
249
250        JS_SetPrototype(cx, element.handle(), prototype.handle());
251
252        result.safe_to_jsval(
253            cx.into(),
254            MutableHandleValue::from_raw(call_args.rval()),
255            CanGc::from_cx(cx),
256        );
257    }
258    Ok(())
259}
260
261/// Returns the constructor object for the element associated with the
262/// given local name. This list should only include elements marked with the
263/// [HTMLConstructor](https://html.spec.whatwg.org/multipage/#htmlconstructor)
264/// extended attribute.
265fn get_constructor_object_from_local_name(
266    name: LocalName,
267    cx: &mut js::context::JSContext,
268    global: HandleObject,
269    rval: MutableHandleObject,
270) -> bool {
271    let constructor_fn = match name {
272        local_name!("a") => HTMLAnchorElementBinding::GetConstructorObject,
273        local_name!("abbr") => HTMLElementBinding::GetConstructorObject,
274        local_name!("acronym") => HTMLElementBinding::GetConstructorObject,
275        local_name!("address") => HTMLElementBinding::GetConstructorObject,
276        local_name!("area") => HTMLAreaElementBinding::GetConstructorObject,
277        local_name!("article") => HTMLElementBinding::GetConstructorObject,
278        local_name!("aside") => HTMLElementBinding::GetConstructorObject,
279        local_name!("audio") => HTMLAudioElementBinding::GetConstructorObject,
280        local_name!("b") => HTMLElementBinding::GetConstructorObject,
281        local_name!("base") => HTMLBaseElementBinding::GetConstructorObject,
282        local_name!("bdi") => HTMLElementBinding::GetConstructorObject,
283        local_name!("bdo") => HTMLElementBinding::GetConstructorObject,
284        local_name!("big") => HTMLElementBinding::GetConstructorObject,
285        local_name!("blockquote") => HTMLQuoteElementBinding::GetConstructorObject,
286        local_name!("body") => HTMLBodyElementBinding::GetConstructorObject,
287        local_name!("br") => HTMLBRElementBinding::GetConstructorObject,
288        local_name!("button") => HTMLButtonElementBinding::GetConstructorObject,
289        local_name!("canvas") => HTMLCanvasElementBinding::GetConstructorObject,
290        local_name!("caption") => HTMLTableCaptionElementBinding::GetConstructorObject,
291        local_name!("center") => HTMLElementBinding::GetConstructorObject,
292        local_name!("cite") => HTMLElementBinding::GetConstructorObject,
293        local_name!("code") => HTMLElementBinding::GetConstructorObject,
294        local_name!("col") => HTMLTableColElementBinding::GetConstructorObject,
295        local_name!("colgroup") => HTMLTableColElementBinding::GetConstructorObject,
296        local_name!("data") => HTMLDataElementBinding::GetConstructorObject,
297        local_name!("datalist") => HTMLDataListElementBinding::GetConstructorObject,
298        local_name!("dd") => HTMLElementBinding::GetConstructorObject,
299        local_name!("del") => HTMLModElementBinding::GetConstructorObject,
300        local_name!("details") => HTMLDetailsElementBinding::GetConstructorObject,
301        local_name!("dfn") => HTMLElementBinding::GetConstructorObject,
302        local_name!("dialog") => HTMLDialogElementBinding::GetConstructorObject,
303        local_name!("dir") => HTMLDirectoryElementBinding::GetConstructorObject,
304        local_name!("div") => HTMLDivElementBinding::GetConstructorObject,
305        local_name!("dl") => HTMLDListElementBinding::GetConstructorObject,
306        local_name!("dt") => HTMLElementBinding::GetConstructorObject,
307        local_name!("em") => HTMLElementBinding::GetConstructorObject,
308        local_name!("embed") => HTMLEmbedElementBinding::GetConstructorObject,
309        local_name!("fieldset") => HTMLFieldSetElementBinding::GetConstructorObject,
310        local_name!("figcaption") => HTMLElementBinding::GetConstructorObject,
311        local_name!("figure") => HTMLElementBinding::GetConstructorObject,
312        local_name!("font") => HTMLFontElementBinding::GetConstructorObject,
313        local_name!("footer") => HTMLElementBinding::GetConstructorObject,
314        local_name!("form") => HTMLFormElementBinding::GetConstructorObject,
315        local_name!("frame") => HTMLFrameElementBinding::GetConstructorObject,
316        local_name!("frameset") => HTMLFrameSetElementBinding::GetConstructorObject,
317        local_name!("h1") => HTMLHeadingElementBinding::GetConstructorObject,
318        local_name!("h2") => HTMLHeadingElementBinding::GetConstructorObject,
319        local_name!("h3") => HTMLHeadingElementBinding::GetConstructorObject,
320        local_name!("h4") => HTMLHeadingElementBinding::GetConstructorObject,
321        local_name!("h5") => HTMLHeadingElementBinding::GetConstructorObject,
322        local_name!("h6") => HTMLHeadingElementBinding::GetConstructorObject,
323        local_name!("head") => HTMLHeadElementBinding::GetConstructorObject,
324        local_name!("header") => HTMLElementBinding::GetConstructorObject,
325        local_name!("hgroup") => HTMLElementBinding::GetConstructorObject,
326        local_name!("hr") => HTMLHRElementBinding::GetConstructorObject,
327        local_name!("html") => HTMLHtmlElementBinding::GetConstructorObject,
328        local_name!("i") => HTMLElementBinding::GetConstructorObject,
329        local_name!("iframe") => HTMLIFrameElementBinding::GetConstructorObject,
330        local_name!("img") => HTMLImageElementBinding::GetConstructorObject,
331        local_name!("input") => HTMLInputElementBinding::GetConstructorObject,
332        local_name!("ins") => HTMLModElementBinding::GetConstructorObject,
333        local_name!("kbd") => HTMLElementBinding::GetConstructorObject,
334        local_name!("label") => HTMLLabelElementBinding::GetConstructorObject,
335        local_name!("legend") => HTMLLegendElementBinding::GetConstructorObject,
336        local_name!("li") => HTMLLIElementBinding::GetConstructorObject,
337        local_name!("link") => HTMLLinkElementBinding::GetConstructorObject,
338        local_name!("listing") => HTMLPreElementBinding::GetConstructorObject,
339        local_name!("main") => HTMLElementBinding::GetConstructorObject,
340        local_name!("map") => HTMLMapElementBinding::GetConstructorObject,
341        local_name!("mark") => HTMLElementBinding::GetConstructorObject,
342        local_name!("marquee") => HTMLMarqueeElementBinding::GetConstructorObject,
343        local_name!("menu") => HTMLMenuElementBinding::GetConstructorObject,
344        local_name!("meta") => HTMLMetaElementBinding::GetConstructorObject,
345        local_name!("meter") => HTMLMeterElementBinding::GetConstructorObject,
346        local_name!("nav") => HTMLElementBinding::GetConstructorObject,
347        local_name!("nobr") => HTMLElementBinding::GetConstructorObject,
348        local_name!("noframes") => HTMLElementBinding::GetConstructorObject,
349        local_name!("noscript") => HTMLElementBinding::GetConstructorObject,
350        local_name!("object") => HTMLObjectElementBinding::GetConstructorObject,
351        local_name!("ol") => HTMLOListElementBinding::GetConstructorObject,
352        local_name!("optgroup") => HTMLOptGroupElementBinding::GetConstructorObject,
353        local_name!("option") => HTMLOptionElementBinding::GetConstructorObject,
354        local_name!("output") => HTMLOutputElementBinding::GetConstructorObject,
355        local_name!("p") => HTMLParagraphElementBinding::GetConstructorObject,
356        local_name!("param") => HTMLParamElementBinding::GetConstructorObject,
357        local_name!("picture") => HTMLPictureElementBinding::GetConstructorObject,
358        local_name!("plaintext") => HTMLPreElementBinding::GetConstructorObject,
359        local_name!("pre") => HTMLPreElementBinding::GetConstructorObject,
360        local_name!("progress") => HTMLProgressElementBinding::GetConstructorObject,
361        local_name!("q") => HTMLQuoteElementBinding::GetConstructorObject,
362        local_name!("rp") => HTMLElementBinding::GetConstructorObject,
363        local_name!("rt") => HTMLElementBinding::GetConstructorObject,
364        local_name!("ruby") => HTMLElementBinding::GetConstructorObject,
365        local_name!("s") => HTMLElementBinding::GetConstructorObject,
366        local_name!("samp") => HTMLElementBinding::GetConstructorObject,
367        local_name!("script") => HTMLScriptElementBinding::GetConstructorObject,
368        local_name!("section") => HTMLElementBinding::GetConstructorObject,
369        local_name!("select") => HTMLSelectElementBinding::GetConstructorObject,
370        local_name!("slot") => HTMLSlotElementBinding::GetConstructorObject,
371        local_name!("small") => HTMLElementBinding::GetConstructorObject,
372        local_name!("source") => HTMLSourceElementBinding::GetConstructorObject,
373        local_name!("span") => HTMLSpanElementBinding::GetConstructorObject,
374        local_name!("strike") => HTMLElementBinding::GetConstructorObject,
375        local_name!("strong") => HTMLElementBinding::GetConstructorObject,
376        local_name!("style") => HTMLStyleElementBinding::GetConstructorObject,
377        local_name!("sub") => HTMLElementBinding::GetConstructorObject,
378        local_name!("summary") => HTMLElementBinding::GetConstructorObject,
379        local_name!("sup") => HTMLElementBinding::GetConstructorObject,
380        local_name!("table") => HTMLTableElementBinding::GetConstructorObject,
381        local_name!("tbody") => HTMLTableSectionElementBinding::GetConstructorObject,
382        local_name!("td") => HTMLTableCellElementBinding::GetConstructorObject,
383        local_name!("template") => HTMLTemplateElementBinding::GetConstructorObject,
384        local_name!("textarea") => HTMLTextAreaElementBinding::GetConstructorObject,
385        local_name!("tfoot") => HTMLTableSectionElementBinding::GetConstructorObject,
386        local_name!("th") => HTMLTableCellElementBinding::GetConstructorObject,
387        local_name!("thead") => HTMLTableSectionElementBinding::GetConstructorObject,
388        local_name!("time") => HTMLTimeElementBinding::GetConstructorObject,
389        local_name!("title") => HTMLTitleElementBinding::GetConstructorObject,
390        local_name!("tr") => HTMLTableRowElementBinding::GetConstructorObject,
391        local_name!("tt") => HTMLElementBinding::GetConstructorObject,
392        local_name!("track") => HTMLTrackElementBinding::GetConstructorObject,
393        local_name!("u") => HTMLElementBinding::GetConstructorObject,
394        local_name!("ul") => HTMLUListElementBinding::GetConstructorObject,
395        local_name!("var") => HTMLElementBinding::GetConstructorObject,
396        local_name!("video") => HTMLVideoElementBinding::GetConstructorObject,
397        local_name!("wbr") => HTMLElementBinding::GetConstructorObject,
398        local_name!("xmp") => HTMLPreElementBinding::GetConstructorObject,
399        _ => return false,
400    };
401    constructor_fn(cx, global, rval);
402    true
403}
404
405pub(crate) fn call_html_constructor<T: DerivedFrom<Element> + DomObject>(
406    cx: &mut js::context::JSContext,
407    args: &CallArgs,
408    global: &GlobalScope,
409    proto_id: PrototypeList::ID,
410    creator: unsafe fn(&mut js::context::JSContext, HandleObject, *mut ProtoOrIfaceArray),
411) -> bool {
412    fn element_derives_interface<T: DerivedFrom<Element>>(element: &Element) -> bool {
413        element.is::<T>()
414    }
415
416    html_constructor(
417        cx,
418        global,
419        args,
420        element_derives_interface::<T>,
421        proto_id,
422        creator,
423    )
424    .is_ok()
425}