1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use html5ever::{local_name, namespace_url, ns, LocalName, Prefix, QualName};
use js::rust::HandleObject;
use servo_config::pref;

use crate::dom::bindings::error::{report_pending_exception, throw_dom_exception};
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::DomRoot;
use crate::dom::customelementregistry::{
    is_valid_custom_element_name, upgrade_element, CustomElementState,
};
use crate::dom::document::Document;
use crate::dom::element::{CustomElementCreationMode, Element, ElementCreator};
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlanchorelement::HTMLAnchorElement;
use crate::dom::htmlareaelement::HTMLAreaElement;
use crate::dom::htmlaudioelement::HTMLAudioElement;
use crate::dom::htmlbaseelement::HTMLBaseElement;
use crate::dom::htmlbodyelement::HTMLBodyElement;
use crate::dom::htmlbrelement::HTMLBRElement;
use crate::dom::htmlbuttonelement::HTMLButtonElement;
use crate::dom::htmlcanvaselement::HTMLCanvasElement;
use crate::dom::htmldataelement::HTMLDataElement;
use crate::dom::htmldatalistelement::HTMLDataListElement;
use crate::dom::htmldetailselement::HTMLDetailsElement;
use crate::dom::htmldialogelement::HTMLDialogElement;
use crate::dom::htmldirectoryelement::HTMLDirectoryElement;
use crate::dom::htmldivelement::HTMLDivElement;
use crate::dom::htmldlistelement::HTMLDListElement;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::htmlembedelement::HTMLEmbedElement;
use crate::dom::htmlfieldsetelement::HTMLFieldSetElement;
use crate::dom::htmlfontelement::HTMLFontElement;
use crate::dom::htmlformelement::HTMLFormElement;
use crate::dom::htmlframeelement::HTMLFrameElement;
use crate::dom::htmlframesetelement::HTMLFrameSetElement;
use crate::dom::htmlheadelement::HTMLHeadElement;
use crate::dom::htmlheadingelement::{HTMLHeadingElement, HeadingLevel};
use crate::dom::htmlhrelement::HTMLHRElement;
use crate::dom::htmlhtmlelement::HTMLHtmlElement;
use crate::dom::htmliframeelement::HTMLIFrameElement;
use crate::dom::htmlimageelement::HTMLImageElement;
use crate::dom::htmlinputelement::HTMLInputElement;
use crate::dom::htmllabelelement::HTMLLabelElement;
use crate::dom::htmllegendelement::HTMLLegendElement;
use crate::dom::htmllielement::HTMLLIElement;
use crate::dom::htmllinkelement::HTMLLinkElement;
use crate::dom::htmlmapelement::HTMLMapElement;
use crate::dom::htmlmenuelement::HTMLMenuElement;
use crate::dom::htmlmetaelement::HTMLMetaElement;
use crate::dom::htmlmeterelement::HTMLMeterElement;
use crate::dom::htmlmodelement::HTMLModElement;
use crate::dom::htmlobjectelement::HTMLObjectElement;
use crate::dom::htmlolistelement::HTMLOListElement;
use crate::dom::htmloptgroupelement::HTMLOptGroupElement;
use crate::dom::htmloptionelement::HTMLOptionElement;
use crate::dom::htmloutputelement::HTMLOutputElement;
use crate::dom::htmlparagraphelement::HTMLParagraphElement;
use crate::dom::htmlparamelement::HTMLParamElement;
use crate::dom::htmlpictureelement::HTMLPictureElement;
use crate::dom::htmlpreelement::HTMLPreElement;
use crate::dom::htmlprogresselement::HTMLProgressElement;
use crate::dom::htmlquoteelement::HTMLQuoteElement;
use crate::dom::htmlscriptelement::HTMLScriptElement;
use crate::dom::htmlselectelement::HTMLSelectElement;
use crate::dom::htmlsourceelement::HTMLSourceElement;
use crate::dom::htmlspanelement::HTMLSpanElement;
use crate::dom::htmlstyleelement::HTMLStyleElement;
use crate::dom::htmltablecaptionelement::HTMLTableCaptionElement;
use crate::dom::htmltablecellelement::HTMLTableCellElement;
use crate::dom::htmltablecolelement::HTMLTableColElement;
use crate::dom::htmltableelement::HTMLTableElement;
use crate::dom::htmltablerowelement::HTMLTableRowElement;
use crate::dom::htmltablesectionelement::HTMLTableSectionElement;
use crate::dom::htmltemplateelement::HTMLTemplateElement;
use crate::dom::htmltextareaelement::HTMLTextAreaElement;
use crate::dom::htmltimeelement::HTMLTimeElement;
use crate::dom::htmltitleelement::HTMLTitleElement;
use crate::dom::htmltrackelement::HTMLTrackElement;
use crate::dom::htmlulistelement::HTMLUListElement;
use crate::dom::htmlunknownelement::HTMLUnknownElement;
use crate::dom::htmlvideoelement::HTMLVideoElement;
use crate::dom::svgelement::SVGElement;
use crate::dom::svgsvgelement::SVGSVGElement;
use crate::realms::{enter_realm, InRealm};
use crate::script_runtime::CanGc;
use crate::script_thread::ScriptThread;

fn create_svg_element(
    name: QualName,
    prefix: Option<Prefix>,
    document: &Document,
    proto: Option<HandleObject>,
) -> DomRoot<Element> {
    assert_eq!(name.ns, ns!(svg));

    macro_rules! make(
        ($ctor:ident) => ({
            let obj = $ctor::new(name.local, prefix, document, proto, CanGc::note());
            DomRoot::upcast(obj)
        });
        ($ctor:ident, $($arg:expr),+) => ({
            let obj = $ctor::new(name.local, prefix, document, proto, $($arg),+, CanGc::note());
            DomRoot::upcast(obj)
        })
    );

    if !pref!(dom.svg.enabled) {
        return Element::new(name.local, name.ns, prefix, document, proto, CanGc::note());
    }

    match name.local {
        local_name!("svg") => make!(SVGSVGElement),
        _ => make!(SVGElement),
    }
}

// https://dom.spec.whatwg.org/#concept-create-element
#[allow(unsafe_code)]
#[allow(clippy::too_many_arguments)]
fn create_html_element(
    name: QualName,
    prefix: Option<Prefix>,
    is: Option<LocalName>,
    document: &Document,
    creator: ElementCreator,
    mode: CustomElementCreationMode,
    proto: Option<HandleObject>,
    can_gc: CanGc,
) -> DomRoot<Element> {
    assert_eq!(name.ns, ns!(html));

    // Step 4
    let definition = document.lookup_custom_element_definition(&name.ns, &name.local, is.as_ref());

    if let Some(definition) = definition {
        if definition.is_autonomous() {
            match mode {
                CustomElementCreationMode::Asynchronous => {
                    let result = DomRoot::upcast::<Element>(HTMLElement::new(
                        name.local.clone(),
                        prefix.clone(),
                        document,
                        proto,
                        can_gc,
                    ));
                    result.set_custom_element_state(CustomElementState::Undefined);
                    ScriptThread::enqueue_upgrade_reaction(&result, definition);
                    return result;
                },
                CustomElementCreationMode::Synchronous => {
                    let local_name = name.local.clone();
                    //TODO(jdm) Pass proto to create_element?
                    return match definition.create_element(document, prefix.clone(), can_gc) {
                        Ok(element) => {
                            element.set_custom_element_definition(definition.clone());
                            element
                        },
                        Err(error) => {
                            // Step 6. Recovering from exception.
                            let global =
                                GlobalScope::current().unwrap_or_else(|| document.global());
                            let cx = GlobalScope::get_cx();

                            // Step 6.1.1
                            unsafe {
                                let ar = enter_realm(&*global);
                                throw_dom_exception(cx, &global, error);
                                report_pending_exception(*cx, true, InRealm::Entered(&ar), can_gc);
                            }

                            // Step 6.1.2
                            let element = DomRoot::upcast::<Element>(HTMLUnknownElement::new(
                                local_name, prefix, document, proto, can_gc,
                            ));
                            element.set_custom_element_state(CustomElementState::Failed);
                            element
                        },
                    };
                },
            }
        } else {
            // Steps 5.1-5.2
            let element = create_native_html_element(name, prefix, document, creator, proto);
            element.set_is(definition.name.clone());
            element.set_custom_element_state(CustomElementState::Undefined);
            match mode {
                // Step 5.3
                CustomElementCreationMode::Synchronous => {
                    upgrade_element(definition, &element, can_gc)
                },
                // Step 5.4
                CustomElementCreationMode::Asynchronous => {
                    ScriptThread::enqueue_upgrade_reaction(&element, definition)
                },
            }
            return element;
        }
    }

    // Steps 7.1-7.3
    let result = create_native_html_element(name.clone(), prefix, document, creator, proto);
    match is {
        Some(is) => {
            result.set_is(is);
            result.set_custom_element_state(CustomElementState::Undefined);
        },
        None => {
            if is_valid_custom_element_name(&name.local) {
                result.set_custom_element_state(CustomElementState::Undefined);
            } else {
                result.set_custom_element_state(CustomElementState::Uncustomized);
            }
        },
    };

    // Step 8
    result
}

pub fn create_native_html_element(
    name: QualName,
    prefix: Option<Prefix>,
    document: &Document,
    creator: ElementCreator,
    proto: Option<HandleObject>,
) -> DomRoot<Element> {
    assert_eq!(name.ns, ns!(html));

    macro_rules! make(
        ($ctor:ident) => ({
            let obj = $ctor::new(name.local, prefix, document, proto, CanGc::note());
            DomRoot::upcast(obj)
        });
        ($ctor:ident, $($arg:expr),+) => ({
            let obj = $ctor::new(name.local, prefix, document, proto, $($arg),+, CanGc::note());
            DomRoot::upcast(obj)
        })
    );

    // This is a big match, and the IDs for inline-interned atoms are not very structured.
    // Perhaps we should build a perfect hash from those IDs instead.
    // https://html.spec.whatwg.org/multipage/#elements-in-the-dom
    match name.local {
        local_name!("a") => make!(HTMLAnchorElement),
        local_name!("abbr") => make!(HTMLElement),
        local_name!("acronym") => make!(HTMLElement),
        local_name!("address") => make!(HTMLElement),
        local_name!("area") => make!(HTMLAreaElement),
        local_name!("article") => make!(HTMLElement),
        local_name!("aside") => make!(HTMLElement),
        local_name!("audio") => make!(HTMLAudioElement),
        local_name!("b") => make!(HTMLElement),
        local_name!("base") => make!(HTMLBaseElement),
        local_name!("bdi") => make!(HTMLElement),
        local_name!("bdo") => make!(HTMLElement),
        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:bgsound
        local_name!("bgsound") => make!(HTMLUnknownElement),
        local_name!("big") => make!(HTMLElement),
        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:blink
        local_name!("blink") => make!(HTMLUnknownElement),
        // https://html.spec.whatwg.org/multipage/#the-blockquote-element
        local_name!("blockquote") => make!(HTMLQuoteElement),
        local_name!("body") => make!(HTMLBodyElement),
        local_name!("br") => make!(HTMLBRElement),
        local_name!("button") => make!(HTMLButtonElement),
        local_name!("canvas") => make!(HTMLCanvasElement),
        local_name!("caption") => make!(HTMLTableCaptionElement),
        local_name!("center") => make!(HTMLElement),
        local_name!("cite") => make!(HTMLElement),
        local_name!("code") => make!(HTMLElement),
        local_name!("col") => make!(HTMLTableColElement),
        local_name!("colgroup") => make!(HTMLTableColElement),
        local_name!("data") => make!(HTMLDataElement),
        local_name!("datalist") => make!(HTMLDataListElement),
        local_name!("dd") => make!(HTMLElement),
        local_name!("del") => make!(HTMLModElement),
        local_name!("details") => make!(HTMLDetailsElement),
        local_name!("dfn") => make!(HTMLElement),
        local_name!("dialog") => make!(HTMLDialogElement),
        local_name!("dir") => make!(HTMLDirectoryElement),
        local_name!("div") => make!(HTMLDivElement),
        local_name!("dl") => make!(HTMLDListElement),
        local_name!("dt") => make!(HTMLElement),
        local_name!("em") => make!(HTMLElement),
        local_name!("embed") => make!(HTMLEmbedElement),
        local_name!("fieldset") => make!(HTMLFieldSetElement),
        local_name!("figcaption") => make!(HTMLElement),
        local_name!("figure") => make!(HTMLElement),
        local_name!("font") => make!(HTMLFontElement),
        local_name!("footer") => make!(HTMLElement),
        local_name!("form") => make!(HTMLFormElement),
        local_name!("frame") => make!(HTMLFrameElement),
        local_name!("frameset") => make!(HTMLFrameSetElement),
        local_name!("h1") => make!(HTMLHeadingElement, HeadingLevel::Heading1),
        local_name!("h2") => make!(HTMLHeadingElement, HeadingLevel::Heading2),
        local_name!("h3") => make!(HTMLHeadingElement, HeadingLevel::Heading3),
        local_name!("h4") => make!(HTMLHeadingElement, HeadingLevel::Heading4),
        local_name!("h5") => make!(HTMLHeadingElement, HeadingLevel::Heading5),
        local_name!("h6") => make!(HTMLHeadingElement, HeadingLevel::Heading6),
        local_name!("head") => make!(HTMLHeadElement),
        local_name!("header") => make!(HTMLElement),
        local_name!("hgroup") => make!(HTMLElement),
        local_name!("hr") => make!(HTMLHRElement),
        local_name!("html") => make!(HTMLHtmlElement),
        local_name!("i") => make!(HTMLElement),
        local_name!("iframe") => make!(HTMLIFrameElement),
        local_name!("img") => make!(HTMLImageElement),
        local_name!("input") => make!(HTMLInputElement),
        local_name!("ins") => make!(HTMLModElement),
        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:isindex-2
        local_name!("isindex") => make!(HTMLUnknownElement),
        local_name!("kbd") => make!(HTMLElement),
        // https://html.spec.whatwg.org/multipage/#keygen
        local_name!("keygen") => make!(HTMLUnknownElement),
        local_name!("label") => make!(HTMLLabelElement),
        local_name!("legend") => make!(HTMLLegendElement),
        local_name!("li") => make!(HTMLLIElement),
        local_name!("link") => make!(HTMLLinkElement, creator),
        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:listing
        local_name!("listing") => make!(HTMLPreElement),
        local_name!("main") => make!(HTMLElement),
        local_name!("map") => make!(HTMLMapElement),
        local_name!("mark") => make!(HTMLElement),
        local_name!("marquee") => make!(HTMLElement),
        local_name!("menu") => make!(HTMLMenuElement),
        local_name!("meta") => make!(HTMLMetaElement),
        local_name!("meter") => make!(HTMLMeterElement),
        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:multicol
        local_name!("multicol") => make!(HTMLUnknownElement),
        local_name!("nav") => make!(HTMLElement),
        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:nextid
        local_name!("nextid") => make!(HTMLUnknownElement),
        local_name!("nobr") => make!(HTMLElement),
        local_name!("noframes") => make!(HTMLElement),
        local_name!("noscript") => make!(HTMLElement),
        local_name!("object") => make!(HTMLObjectElement),
        local_name!("ol") => make!(HTMLOListElement),
        local_name!("optgroup") => make!(HTMLOptGroupElement),
        local_name!("option") => make!(HTMLOptionElement),
        local_name!("output") => make!(HTMLOutputElement),
        local_name!("p") => make!(HTMLParagraphElement),
        local_name!("param") => make!(HTMLParamElement),
        local_name!("picture") => make!(HTMLPictureElement),
        local_name!("plaintext") => make!(HTMLPreElement),
        local_name!("pre") => make!(HTMLPreElement),
        local_name!("progress") => make!(HTMLProgressElement),
        local_name!("q") => make!(HTMLQuoteElement),
        local_name!("rp") => make!(HTMLElement),
        local_name!("rt") => make!(HTMLElement),
        local_name!("ruby") => make!(HTMLElement),
        local_name!("s") => make!(HTMLElement),
        local_name!("samp") => make!(HTMLElement),
        local_name!("script") => make!(HTMLScriptElement, creator),
        local_name!("section") => make!(HTMLElement),
        local_name!("select") => make!(HTMLSelectElement),
        local_name!("small") => make!(HTMLElement),
        local_name!("source") => make!(HTMLSourceElement),
        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:spacer
        local_name!("spacer") => make!(HTMLUnknownElement),
        local_name!("span") => make!(HTMLSpanElement),
        local_name!("strike") => make!(HTMLElement),
        local_name!("strong") => make!(HTMLElement),
        local_name!("style") => make!(HTMLStyleElement, creator),
        local_name!("sub") => make!(HTMLElement),
        local_name!("summary") => make!(HTMLElement),
        local_name!("sup") => make!(HTMLElement),
        local_name!("table") => make!(HTMLTableElement),
        local_name!("tbody") => make!(HTMLTableSectionElement),
        local_name!("td") => make!(HTMLTableCellElement),
        local_name!("template") => make!(HTMLTemplateElement),
        local_name!("textarea") => make!(HTMLTextAreaElement),
        // https://html.spec.whatwg.org/multipage/#the-tfoot-element:concept-element-dom
        local_name!("tfoot") => make!(HTMLTableSectionElement),
        local_name!("th") => make!(HTMLTableCellElement),
        // https://html.spec.whatwg.org/multipage/#the-thead-element:concept-element-dom
        local_name!("thead") => make!(HTMLTableSectionElement),
        local_name!("time") => make!(HTMLTimeElement),
        local_name!("title") => make!(HTMLTitleElement),
        local_name!("tr") => make!(HTMLTableRowElement),
        local_name!("tt") => make!(HTMLElement),
        local_name!("track") => make!(HTMLTrackElement),
        local_name!("u") => make!(HTMLElement),
        local_name!("ul") => make!(HTMLUListElement),
        local_name!("var") => make!(HTMLElement),
        local_name!("video") => make!(HTMLVideoElement),
        local_name!("wbr") => make!(HTMLElement),
        local_name!("xmp") => make!(HTMLPreElement),
        _ if is_valid_custom_element_name(&name.local) => make!(HTMLElement),
        _ => make!(HTMLUnknownElement),
    }
}

pub fn create_element(
    name: QualName,
    is: Option<LocalName>,
    document: &Document,
    creator: ElementCreator,
    mode: CustomElementCreationMode,
    proto: Option<HandleObject>,
    can_gc: CanGc,
) -> DomRoot<Element> {
    let prefix = name.prefix.clone();
    match name.ns {
        ns!(html) => create_html_element(name, prefix, is, document, creator, mode, proto, can_gc),
        ns!(svg) => create_svg_element(name, prefix, document, proto),
        _ => Element::new(name.local, name.ns, prefix, document, proto, can_gc),
    }
}