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