Skip to main content

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