-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
mod.rs
8569 lines (7984 loc) · 385 KB
/
mod.rs
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{cell::RefCell, mem, rc::Rc};
use active_formatting_element_stack::*;
use doctypes::*;
use node::*;
use open_elements_stack::*;
use swc_atoms::Atom;
use swc_common::{Span, DUMMY_SP};
use swc_html_ast::*;
use self::input::{Buffer, ParserInput};
use crate::{
error::{Error, ErrorKind},
lexer::State,
};
#[macro_use]
mod macros;
mod active_formatting_element_stack;
mod doctypes;
pub mod input;
mod node;
mod open_elements_stack;
pub type PResult<T> = Result<T, Error>;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ParserConfig {
pub scripting_enabled: bool,
pub iframe_srcdoc: bool,
}
enum Bookmark<RcNode> {
Replace(RcNode),
InsertAfter(RcNode),
}
enum AdjustAttributes {
MathML,
Svg,
}
#[derive(Debug, Clone)]
enum InsertionMode {
Initial,
BeforeHtml,
BeforeHead,
InHead,
InHeadNoScript,
AfterHead,
InBody,
Text,
InTable,
InTableText,
InCaption,
InColumnGroup,
InTableBody,
InRow,
InCell,
InSelect,
InSelectInTable,
InTemplate,
AfterBody,
InFrameset,
AfterFrameset,
AfterAfterBody,
AfterAfterFrameset,
}
impl Default for InsertionMode {
fn default() -> Self {
InsertionMode::Initial
}
}
enum InsertionPosition {
LastChild(RcNode),
BeforeSibling(RcNode),
}
pub struct Parser<I>
where
I: ParserInput,
{
#[allow(dead_code)]
config: ParserConfig,
input: Buffer<I>,
stopped: bool,
is_fragment_case: bool,
context_element: Option<RcNode>,
insertion_mode: InsertionMode,
original_insertion_mode: InsertionMode,
template_insertion_mode_stack: Vec<InsertionMode>,
document: Option<RcNode>,
head_element_pointer: Option<RcNode>,
form_element_pointer: Option<RcNode>,
open_elements_stack: OpenElementsStack,
active_formatting_elements: ActiveFormattingElementStack,
pending_character_tokens: Vec<TokenAndInfo>,
frameset_ok: bool,
foster_parenting_enabled: bool,
errors: Vec<Error>,
}
impl<I> Parser<I>
where
I: ParserInput,
{
pub fn new(input: I, config: ParserConfig) -> Self {
Parser {
config,
input: Buffer::new(input),
stopped: false,
is_fragment_case: false,
context_element: None,
insertion_mode: Default::default(),
original_insertion_mode: Default::default(),
template_insertion_mode_stack: Vec::with_capacity(16),
document: None,
head_element_pointer: None,
form_element_pointer: None,
open_elements_stack: OpenElementsStack::new(),
active_formatting_elements: ActiveFormattingElementStack::new(),
pending_character_tokens: Vec::with_capacity(16),
frameset_ok: true,
foster_parenting_enabled: false,
errors: Default::default(),
}
}
pub fn dump_cur(&mut self) -> String {
format!("{:?}", self.input.cur())
}
pub fn take_errors(&mut self) -> Vec<Error> {
mem::take(&mut self.errors)
}
pub fn parse_document(&mut self) -> PResult<Document> {
let start = self.input.cur_span()?;
self.document = Some(self.create_document(None));
self.run()?;
let document = &mut self.document.take().unwrap();
let nodes = document.children.take();
let mut children = Vec::with_capacity(nodes.len());
for node in nodes {
children.push(self.node_to_child(node));
}
let last = self.input.last_pos()?;
let mode = match &document.data {
Data::Document { mode, .. } => *mode.borrow(),
_ => {
unreachable!();
}
};
Ok(Document {
span: Span::new(start.lo(), last, Default::default()),
mode,
children,
})
}
// The following steps form the HTML fragment parsing algorithm. The algorithm
// takes as input an Element node, referred to as the context element, which
// gives the context for the parser, as well as input, a string to parse, and
// returns a list of zero or more nodes.
//
// Parts marked fragment case in algorithms in the parser section are parts that
// only occur if the parser was created for the purposes of this algorithm. The
// algorithms have been annotated with such markings for informational purposes
// only; such markings have no normative weight. If it is possible for a
// condition described as a fragment case to occur even when the parser wasn't
// created for the purposes of handling this algorithm, then that is an error in
// the specification.
//
// 1. Create a new Document node, and mark it as being an HTML document.
//
// 2. If the node document of the context element is in quirks mode, then let
// the Document be in quirks mode. Otherwise, the node document of the
// context element is in limited-quirks mode, then let the Document be in
// limited-quirks mode. Otherwise, leave the Document in no-quirks mode.
//
// 3. Create a new HTML parser, and associate it with the just created Document
// node.
//
// 4. Set the state of the HTML parser's tokenization stage as follows,
// switching on the context element:
//
// title
// textarea
//
// Switch the tokenizer to the RCDATA state.
//
// style
// xmp
// iframe
// noembed
// noframes
//
// Switch the tokenizer to the RAWTEXT state.
//
// script
//
// Switch the tokenizer to the script data state.
//
// noscript
//
// If the scripting flag is enabled, switch the tokenizer to the RAWTEXT state.
// Otherwise, leave the tokenizer in the data state. plaintext
//
// Switch the tokenizer to the PLAINTEXT state.
//
// Any other element
//
// Leave the tokenizer in the data state.
//
// For performance reasons, an implementation that does not report errors and
// that uses the actual state machine described in this specification directly
// could use the PLAINTEXT state instead of the RAWTEXT and script data states
// where those are mentioned in the list above. Except for rules regarding parse
// errors, they are equivalent, since there is no appropriate end tag token in
// the fragment case, yet they involve far fewer state transitions.
//
// 5. Let root be a new html element with no attributes.
//
// 6. Append the element root to the Document node created above.
//
// 7. Set up the parser's stack of open elements so that it contains just the
// single element root.
//
// 8. If the context element is a template element, push "in template" onto the
// stack of template insertion modes so that it is the new current template
// insertion mode.
//
// 9. Create a start tag token whose name is the local name of context and whose
// attributes are the attributes of context.
//
// Let this start tag token be the start tag token of the context node, e.g. for
// the purposes of determining if it is an HTML integration point.
//
// 10. Reset the parser's insertion mode appropriately.
//
// The parser will reference the context element as part of that algorithm.
//
// 11. Set the parser's form element pointer to the nearest node to the context
// element that is a form element (going straight up the ancestor chain, and
// including the element itself, if it is a form element), if any. (If there is
// no such form element, the form element pointer keeps its initial value,
// null.)
//
// 12. Place the input into the input stream for the HTML parser just created.
// The encoding confidence is irrelevant.
//
// 13. Start the parser and let it run until it has consumed all the characters
// just inserted into the input stream.
//
// 14. Return the child nodes of root, in tree order.
pub fn parse_document_fragment(
&mut self,
context_element: Element,
mode: DocumentMode,
form_element: Option<Element>,
) -> PResult<DocumentFragment> {
// 1.
// 2.
self.document = Some(self.create_document(Some(mode)));
// 3.
// Parser already created
let context_node = Node::new(
Data::Element {
namespace: context_element.namespace,
tag_name: context_element.tag_name,
attributes: RefCell::new(context_element.attributes),
is_self_closing: context_element.is_self_closing,
},
DUMMY_SP,
);
// 4.
match get_tag_name!(context_node) {
"title" | "textarea" if get_namespace!(context_node) == Namespace::HTML => {
self.input.set_input_state(State::Rcdata);
}
"style" | "xmp" | "iframe" | "noembed" | "noframes"
if get_namespace!(context_node) == Namespace::HTML =>
{
self.input.set_input_state(State::Rawtext);
}
"script" if get_namespace!(context_node) == Namespace::HTML => {
self.input.set_input_state(State::ScriptData);
}
"noscript" if get_namespace!(context_node) == Namespace::HTML => {
if self.config.scripting_enabled {
self.input.set_input_state(State::Rawtext);
} else {
self.input.set_input_state(State::Data)
}
}
"plaintext" if get_namespace!(context_node) == Namespace::HTML => {
self.input.set_input_state(State::PlainText)
}
_ => self.input.set_input_state(State::Data),
}
// 5.
let root = self.create_fake_html_element();
// 6.
self.append_node(self.document.as_ref().unwrap(), root.clone());
// 7.
self.open_elements_stack.push(root.clone());
// 8.
if is_html_element!(context_node, "template") {
self.template_insertion_mode_stack
.push(InsertionMode::InTemplate);
}
// 9.
self.context_element = Some(context_node.clone());
self.is_fragment_case = true;
// 10.
self.reset_insertion_mode();
// 11.
if is_html_element!(context_node, "form") {
self.form_element_pointer = Some(context_node);
} else if let Some(form_element) = form_element {
self.form_element_pointer = Some(Node::new(
Data::Element {
namespace: form_element.namespace,
tag_name: form_element.tag_name,
attributes: RefCell::new(form_element.attributes),
is_self_closing: form_element.is_self_closing,
},
DUMMY_SP,
));
}
// 12.
// We do preprocess input stream inside lexer
// 13.
let start = self.input.cur_span()?;
self.run()?;
let nodes = root.children.take();
let mut children = Vec::with_capacity(nodes.len());
for node in nodes {
children.push(self.node_to_child(node));
}
let last = self.input.last_pos()?;
Ok(DocumentFragment {
span: Span::new(start.lo(), last, Default::default()),
children,
})
}
fn create_document(&self, mode: Option<DocumentMode>) -> RcNode {
Node::new(
Data::Document {
mode: RefCell::new(mode.unwrap_or(DocumentMode::NoQuirks)),
},
DUMMY_SP,
)
}
#[allow(clippy::only_used_in_recursion)]
fn get_deep_end_span(&mut self, children: &[Child]) -> Option<Span> {
match children.last() {
Some(Child::DocumentType(DocumentType { span, .. })) => Some(*span),
Some(Child::Element(Element { span, children, .. })) => {
if span.is_dummy() {
return self.get_deep_end_span(children);
}
Some(*span)
}
Some(Child::Comment(Comment { span, .. })) => Some(*span),
Some(Child::Text(Text { span, .. })) => Some(*span),
_ => None,
}
}
fn node_to_child(&mut self, node: RcNode) -> Child {
let start_span = node.start_span.take();
match node.data.clone() {
Data::DocumentType {
name,
public_id,
system_id,
raw,
} => Child::DocumentType(DocumentType {
span: start_span,
name,
public_id,
system_id,
raw,
}),
Data::Element {
namespace,
tag_name,
attributes,
is_self_closing,
} => {
let nodes = node.children.take();
let mut new_children = Vec::with_capacity(nodes.len());
for node in nodes {
new_children.push(self.node_to_child(node));
}
let attributes = attributes.take();
match &*tag_name {
"html" | "body" if namespace == Namespace::HTML => {
// Elements and text after `</html>` are moving into `<body>`
// Elements and text after `</body>` are moving into `<body>`
let span = if start_span.is_dummy() {
start_span
} else {
let end_body = match node.end_span.take() {
Some(end_tag_span) => end_tag_span,
_ => start_span,
};
let end_children = match self.get_deep_end_span(&new_children) {
Some(end_span) => end_span,
_ => start_span,
};
let end = if end_body.hi() >= end_children.hi() {
end_body
} else {
end_children
};
Span::new(start_span.lo(), end.hi(), Default::default())
};
Child::Element(Element {
span,
namespace,
tag_name,
attributes,
is_self_closing,
children: new_children,
content: None,
})
}
_ => {
let span = if start_span.is_dummy() {
start_span
} else {
let end_span = match node.end_span.take() {
Some(end_span) if !end_span.is_dummy() => end_span,
_ => match self.get_deep_end_span(&new_children) {
Some(end_span) => end_span,
_ => start_span,
},
};
Span::new(start_span.lo(), end_span.hi(), Default::default())
};
let (children, content) =
if namespace == Namespace::HTML && &tag_name == "template" {
(
vec![],
Some(DocumentFragment {
span,
children: new_children,
}),
)
} else {
(new_children, None)
};
Child::Element(Element {
span,
namespace,
tag_name,
attributes,
is_self_closing,
children,
content,
})
}
}
}
Data::Text { data, raw } => {
let span = if let Some(end_span) = node.end_span.take() {
Span::new(start_span.lo(), end_span.hi(), Default::default())
} else {
start_span
};
Child::Text(Text {
span,
data: data.take().into(),
raw: Some(raw.take().into()),
})
}
Data::Comment { data, raw } => Child::Comment(Comment {
span: start_span,
data,
raw,
}),
_ => {
unreachable!();
}
}
}
fn run(&mut self) -> PResult<()> {
while !self.stopped {
let adjusted_current_node = self.get_adjusted_current_node();
let is_element_in_html_namespace = is_element_in_html_namespace(adjusted_current_node);
self.input
.set_adjusted_current_node_to_html_namespace(is_element_in_html_namespace);
let mut token_and_info = match self.input.cur()? {
Some(_) => {
let span = self.input.cur_span()?;
let token = bump!(self);
TokenAndInfo {
span: span!(self, span.lo()),
acknowledged: false,
token,
}
}
None => {
let start_pos = self.input.start_pos()?;
let last_pos = self.input.last_pos()?;
TokenAndInfo {
span: Span::new(start_pos, last_pos, Default::default()),
acknowledged: false,
token: Token::Eof,
}
}
};
// Re-emit errors from tokenizer
for error in self.input.take_errors() {
let (span, kind) = *error.into_inner();
self.errors.push(Error::new(span, kind));
}
self.tree_construction_dispatcher(&mut token_and_info)?;
// When a start tag token is emitted with its self-closing flag set,
// if the flag is not acknowledged when it is processed by the tree
// construction stage, that is a parse error.
if let Token::StartTag {
is_self_closing, ..
} = &token_and_info.token
{
if *is_self_closing && !token_and_info.acknowledged {
self.errors.push(Error::new(
token_and_info.span,
ErrorKind::NonVoidHtmlElementStartTagWithTrailingSolidus,
));
}
}
}
Ok(())
}
fn tree_construction_dispatcher(&mut self, token_and_info: &mut TokenAndInfo) -> PResult<()> {
// As each token is emitted from the tokenizer, the user agent must follow the
// appropriate steps from the following list, known as the tree construction
// dispatcher:
//
// If the stack of open elements is empty
//
// If the adjusted current node is an element in the HTML namespace
//
// If the adjusted current node is a MathML text integration point and the token
// is a start tag whose tag name is neither "mglyph" nor "malignmark"
//
// If the adjusted current node is a MathML text integration point and the token
// is a character token
//
// If the adjusted current node is a MathML annotation-xml element and the token
// is a start tag whose tag name is "svg"
//
// If the adjusted current node is an HTML integration point and the token is a
// start tag
//
// If the adjusted current node is an HTML integration point and the token is a
// character token
//
// If the token is an end-of-file token
//
// Process the token according to the rules given in the section corresponding
// to the current insertion mode in HTML content.
let adjusted_current_node = self.get_adjusted_current_node();
let is_element_in_html_namespace = is_element_in_html_namespace(adjusted_current_node);
let is_mathml_text_integration_point =
is_mathml_text_integration_point(adjusted_current_node);
let is_mathml_annotation_xml = is_mathml_annotation_xml(adjusted_current_node);
let is_html_integration_point = is_html_integration_point(adjusted_current_node);
if self.open_elements_stack.items.is_empty()
|| is_element_in_html_namespace
|| (is_mathml_text_integration_point
&& matches!(&token_and_info.token, Token::StartTag { tag_name, .. } if *tag_name != "mglyph" && *tag_name != "malignmark"))
|| (is_mathml_text_integration_point
&& matches!(&token_and_info.token, Token::Character { .. }))
|| (is_mathml_annotation_xml
&& matches!(&token_and_info.token, Token::StartTag { tag_name, .. } if tag_name == "svg"))
|| (is_html_integration_point
&& matches!(&token_and_info.token, Token::StartTag { .. }))
|| (is_html_integration_point
&& matches!(&token_and_info.token, Token::Character { .. }))
|| matches!(&token_and_info.token, Token::Eof)
{
self.process_token(token_and_info, None)?;
}
// Otherwise
// Process the token according to the rules given in the section for parsing tokens in
// foreign content.
else {
self.process_token_in_foreign_content(token_and_info)?;
}
Ok(())
}
// The adjusted current node is the context element if the parser was created as
// part of the HTML fragment parsing algorithm and the stack of open elements
// has only one element in it (fragment case); otherwise, the adjusted current
// node is the current node.
fn get_adjusted_current_node(&self) -> Option<&RcNode> {
if self.is_fragment_case && self.open_elements_stack.items.len() == 1 {
return self.context_element.as_ref();
}
self.open_elements_stack.items.last()
}
fn process_token_in_foreign_content(
&mut self,
token_and_info: &mut TokenAndInfo,
) -> PResult<()> {
let TokenAndInfo { token, .. } = &token_and_info;
match token {
// A character token that is U+0000 NULL
//
// Parse error. Insert a U+FFFD REPLACEMENT CHARACTER character.
Token::Character { value, .. } if *value == '\x00' => {
self.errors.push(Error::new(
token_and_info.span,
ErrorKind::UnexpectedNullCharacter,
));
token_and_info.token = Token::Character {
value: '\u{FFFD}',
raw: Some(Raw::Atom(Atom::new(String::from('\x00')))),
};
println!("{:?}", token_and_info.token);
self.insert_character(token_and_info)?;
}
// A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF),
// U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
//
// Insert the token's character.
Token::Character {
value: '\x09' | '\x0A' | '\x0C' | '\x0D' | '\x20',
..
} => {
self.insert_character(token_and_info)?;
}
// Any other character token
//
// Insert the token's character.
//
// Set the frameset-ok flag to "not ok".
Token::Character { .. } => {
self.insert_character(token_and_info)?;
self.frameset_ok = false;
}
// A comment token
//
// Insert a comment.
Token::Comment { .. } => {
self.insert_comment(token_and_info)?;
}
// A DOCTYPE token
// Parse error. Ignore the token.
Token::Doctype { .. } => {
self.errors
.push(Error::new(token_and_info.span, ErrorKind::StrayDoctype));
}
// A start tag whose tag name is one of: "b", "big", "blockquote", "body", "br",
// "center", "code", "dd", "div", "dl", "dt", "em", "embed", "h1", "h2", "h3", "h4",
// "h5", "h6", "head", "hr", "i", "img", "li", "listing", "menu", "meta", "nobr", "ol",
// "p", "pre", "ruby", "s", "small", "span", "strong", "strike", "sub", "sup", "table",
// "tt", "u", "ul", "var"
//
// A start tag whose tag name is "font", if the token has any attributes named "color",
// "face", or "size"
//
// An end tag whose tag name is "br", "p"
//
// Parse error.
//
// While the current node is not a MathML text integration point, an HTML integration
// point, or an element in the HTML namespace, pop elements from the stack of open
// elements.
//
// Reprocess the token according to the rules given in the section corresponding to the
// current insertion mode in HTML content.
Token::StartTag { tag_name, .. }
if matches!(
&**tag_name,
"b" | "big"
| "blockquote"
| "body"
| "br"
| "center"
| "code"
| "dd"
| "div"
| "dl"
| "dt"
| "em"
| "embed"
| "h1"
| "h2"
| "h3"
| "h4"
| "h5"
| "h6"
| "head"
| "hr"
| "i"
| "img"
| "li"
| "listing"
| "menu"
| "meta"
| "nobr"
| "ol"
| "p"
| "pre"
| "ruby"
| "s"
| "small"
| "span"
| "strong"
| "strike"
| "sub"
| "sup"
| "table"
| "tt"
| "u"
| "ul"
| "var"
) =>
{
self.errors.push(Error::new(
token_and_info.span,
ErrorKind::HtmlStartTagInForeignContext(tag_name.clone()),
));
self.open_elements_stack.pop_until_in_foreign();
self.process_token(token_and_info, None)?;
}
Token::StartTag {
tag_name,
attributes,
..
} if tag_name == "font"
&& attributes
.iter()
.any(|attribute| matches!(&*attribute.name, "color" | "face" | "size")) =>
{
self.errors.push(Error::new(
token_and_info.span,
ErrorKind::HtmlStartTagInForeignContext(tag_name.clone()),
));
self.open_elements_stack.pop_until_in_foreign();
self.process_token(token_and_info, None)?;
}
Token::EndTag { tag_name, .. } if matches!(&**tag_name, "br" | "p") => {
let last = get_tag_name!(self.open_elements_stack.items.last().unwrap());
self.errors.push(Error::new(
token_and_info.span,
ErrorKind::EndTagDidNotMatchCurrentOpenElement(tag_name.clone(), last.into()),
));
self.open_elements_stack.pop_until_in_foreign();
self.process_token(token_and_info, None)?;
}
// Any other start tag
//
// If the adjusted current node is an element in the MathML namespace, adjust MathML
// attributes for the token. (This fixes the case of MathML attributes that are not all
// lowercase.)
//
// If the adjusted current node is an element in the SVG namespace, and the token's tag
// name is one of the ones in the first column of the following table, change the tag
// name to the name given in the corresponding cell in the second column. (This fixes
// the case of SVG elements that are not all lowercase.)
//
// Tag name Element name
// altglyph altGlyph
// altglyphdef altGlyphDef
// altglyphitem altGlyphItem
// animatecolor animateColor
// animatemotion animateMotion
// animatetransform animateTransform
// clippath clipPath
// feblend feBlend
// fecolormatrix feColorMatrix
// fecomponenttransfer feComponentTransfer
// fecomposite feComposite
// feconvolvematrix feConvolveMatrix
// fediffuselighting feDiffuseLighting
// fedisplacementmap feDisplacementMap
// fedistantlight feDistantLight
// fedropshadow feDropShadow
// feflood feFlood
// fefunca feFuncA
// fefuncb feFuncB
// fefuncg feFuncG
// fefuncr feFuncR
// fegaussianblur feGaussianBlur
// feimage feImage
// femerge feMerge
// femergenode feMergeNode
// femorphology feMorphology
// feoffset feOffset
// fepointlight fePointLight
// fespecularlighting feSpecularLighting
// fespotlight feSpotLight
// fetile feTile
// feturbulence feTurbulence
// foreignobject foreignObject
// glyphref glyphRef
// lineargradient linearGradient
// radialgradient radialGradient
// textpath textPath
//
// If the adjusted current node is an element in the SVG namespace, adjust SVG
// attributes for the token. (This fixes the case of SVG attributes that are not all
// lowercase.)
//
// Adjust foreign attributes for the token. (This fixes the use of namespaced
// attributes, in particular XLink in SVG.)
//
// Insert a foreign element for the token, in the same namespace as the adjusted current
// node.
//
// If the token has its self-closing flag set, then run the appropriate steps from the
// following list:
//
// If the token's tag name is "script", and the new current node is in the SVG
// namespace
//
// Acknowledge the token's self-closing flag, and then act as
// described in the steps for a "script" end tag below.
//
// Otherwise
// Pop the current node off the stack of open elements and acknowledge the token's
// self-closing flag.
Token::StartTag {
tag_name,
raw_tag_name,
is_self_closing,
attributes,
} => {
let is_self_closing = *is_self_closing;
let is_script = tag_name == "script";
let adjusted_current_node = self.get_adjusted_current_node();
let namespace = match adjusted_current_node {
Some(node) => {
get_namespace!(node)
}
_ => {
unreachable!();
}
};
let adjust_attributes = match namespace {
Namespace::MATHML => Some(AdjustAttributes::MathML),
Namespace::SVG => Some(AdjustAttributes::Svg),
_ => None,
};
if namespace == Namespace::SVG {
let new_tag_name = match &**tag_name {
"altglyph" => Some("altGlyph"),
"altglyphdef" => Some("altGlyphDef"),
"altglyphitem" => Some("altGlyphItem"),
"animatecolor" => Some("animateColor"),
"animatemotion" => Some("animateMotion"),
"animatetransform" => Some("animateTransform"),
"clippath" => Some("clipPath"),
"feblend" => Some("feBlend"),
"fecolormatrix" => Some("feColorMatrix"),
"fecomponenttransfer" => Some("feComponentTransfer"),
"fecomposite" => Some("feComposite"),
"feconvolvematrix" => Some("feConvolveMatrix"),
"fediffuselighting" => Some("feDiffuseLighting"),
"fedisplacementmap" => Some("feDisplacementMap"),
"fedistantlight" => Some("feDistantLight"),
"fedropshadow" => Some("feDropShadow"),
"feflood" => Some("feFlood"),
"fefunca" => Some("feFuncA"),
"fefuncb" => Some("feFuncB"),
"fefuncg" => Some("feFuncG"),
"fefuncr" => Some("feFuncR"),
"fegaussianblur" => Some("feGaussianBlur"),
"feimage" => Some("feImage"),
"femerge" => Some("feMerge"),
"femergenode" => Some("feMergeNode"),
"femorphology" => Some("feMorphology"),
"feoffset" => Some("feOffset"),
"fepointlight" => Some("fePointLight"),
"fespecularlighting" => Some("feSpecularLighting"),
"fespotlight" => Some("feSpotLight"),
"fetile" => Some("feTile"),
"feturbulence" => Some("feTurbulence"),
"foreignobject" => Some("foreignObject"),
"glyphref" => Some("glyphRef"),
"lineargradient" => Some("linearGradient"),
"radialgradient" => Some("radialGradient"),
"textpath" => Some("textPath"),
_ => None,
};
if let Some(new_tag_name) = new_tag_name {
token_and_info.token = Token::StartTag {
tag_name: new_tag_name.into(),
raw_tag_name: raw_tag_name.clone(),
is_self_closing,
attributes: attributes.clone(),
}
}
}
self.insert_foreign_element(token_and_info, namespace, adjust_attributes)?;
if is_self_closing {
if is_script
&& match self.open_elements_stack.items.last() {
Some(node) => get_namespace!(node) == Namespace::SVG,
_ => false,
}
{
token_and_info.acknowledged = true;
self.open_elements_stack.pop();
} else {
self.open_elements_stack.pop();
token_and_info.acknowledged = true;
}
}
}
// An end tag whose tag name is "script", if the current node is an SVG script element
//
// Pop the current node off the stack of open elements.
//
// Let the old insertion point have the same value as the current insertion point. Let
// the insertion point be just before the next input character.
//
// Increment the parser's script nesting level by one. Set the parser pause flag to
// true.
//
// If the active speculative HTML parser is null and the user agent supports SVG, then
// Process the SVG script element according to the SVG rules. [SVG]
//
// Even if this causes new characters to be inserted into the tokenizer, the parser will
// not be executed reentrantly, since the parser pause flag is true.
//
// Decrement the parser's script nesting level by one. If the parser's script nesting
// level is zero, then set the parser pause flag to false.