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
use crate::node::{
Node, NodeFlags, NodeKind, comment, fragment, new_doctype, new_element, raw_text, text,
};
use crate::tokenizer::{self, Attribute, Tag, TagKind, TokenKind, Tokenizer};
use std::sync::Arc;
struct Parser {
tokenizer: Tokenizer,
root: Node,
open_elements: Vec<(usize, Node)>,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
pub(crate) enum Namespace {
#[default]
Html,
Foreign,
}
pub(crate) const VOID_ELEMENT_NAMES: [&str; 13] = [
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track",
"wbr",
];
/// Parses the given HTML fragment.
///
/// Parsing is done in two phases: tokenization and tree construction:
/// - The tokenization phase is spec compliant, so it does not fail hard, instead errors are recovered from in a spec-compliant way.
/// The input will still be converted to tokens and emitted to the next phase.
/// - The tree construction phase implements a very small subset of the spec, and fails at the first [`ParserError`], which is returned to the caller.
pub fn parse(html: &str) -> Result<Node, ParserError> {
let parser = Parser {
root: fragment([]),
tokenizer: Tokenizer::new(html),
open_elements: Vec::new(),
};
parser.parse()
}
impl Parser {
fn parse(mut self) -> Result<Node, ParserError> {
loop {
let current_token = self.tokenizer.next_token();
match current_token.kind {
TokenKind::Text(t) => {
let node = if let Some((_, el)) = self.open_elements.last() {
// When parsing markup, we mark text nodes that should be serialized verbtim as such.
// This makes the serializtion algorithm much easier.
// See: https://html.spec.whatwg.org/multipage/parsing.html#serialising-html-fragments
if matches!(
&*el.name(),
"style"
| "script"
| "xmp"
| "iframe"
| "noembed"
| "noframes"
| "plaintext"
) {
raw_text(&t)
} else {
text(&t)
}
} else {
text(&t)
};
self.insert_comment_text_or_doctype(node);
}
TokenKind::Comment(c) => {
self.insert_comment_text_or_doctype(comment(&c));
}
TokenKind::Doctype(doctype) => {
self.insert_comment_text_or_doctype(new_doctype(
&doctype.name.unwrap_or_default(),
));
}
TokenKind::Eof => {
if let Some((token_offset, _)) = self.open_elements.last() {
return Err(ParserError {
offset: *token_offset,
code: ErrorCode::UnclosedStartTag,
source: self.tokenizer.get_input(),
});
};
// We are done parsing when there are no more tokens AND the stack of open elements is empty.
return Ok(self.root);
}
TokenKind::Tag(
tag @ Tag {
kind: TagKind::Start,
..
},
) => {
let attrs = tag
.attributes
.into_iter()
.map(|Attribute { name, value }| (name, value));
let namespace = if tag.name == "svg" || tag.name == "math" {
Namespace::Foreign
} else {
self.current_namespace()
};
let el = new_element(
&tag.name,
namespace,
if tag.self_closing {
NodeFlags::new(NodeFlags::SELF_CLOSING)
} else {
NodeFlags::new(NodeFlags::NONE)
},
attrs,
[],
);
self.insert_element(current_token.span.start, el.clone());
if namespace == Namespace::Html && VOID_ELEMENT_NAMES.contains(&&*el.name()) {
self.open_elements.pop();
} else if tag.self_closing {
if namespace == Namespace::Foreign {
self.open_elements.pop();
} else {
return Err(ParserError {
code: ErrorCode::NonVoidElementStartTagWithTrailingSolidus,
offset: current_token.span.start,
source: self.tokenizer.get_input(),
});
}
}
match &*el.name() {
"title" | "textarea" => {
self.tokenizer.switch_to(tokenizer::state_rc_data);
}
"noscript" | "style" | "xmp" | "iframe" | "noembed" | "noframes" => {
self.tokenizer.switch_to(tokenizer::state_raw_text);
}
"script" => {
self.tokenizer.switch_to(tokenizer::state_script_data);
}
_ => {}
}
}
TokenKind::Tag(
tag @ Tag {
kind: TagKind::End, ..
},
) => {
if self.current_namespace() == Namespace::Html
&& VOID_ELEMENT_NAMES.contains(&tag.name.as_str())
{
return Err(ParserError {
code: ErrorCode::VoidElementAsEndTag,
offset: current_token.span.start,
source: self.tokenizer.get_input(),
});
}
let Some((token_offset, node)) = self.open_elements.pop() else {
return Err(ParserError {
code: ErrorCode::EndTagWithoutCorrespondingStartTag,
offset: current_token.span.start,
source: self.tokenizer.get_input(),
});
};
if *node.name() != tag.name {
return Err(ParserError {
code: ErrorCode::UnclosedStartTag,
offset: token_offset,
source: self.tokenizer.get_input(),
});
}
}
}
}
}
fn insert_comment_text_or_doctype(&mut self, n: Node) {
debug_assert!(matches!(
n.kind(),
NodeKind::Text | NodeKind::Comment | NodeKind::Doctype
));
if let Some((_, parent)) = self.open_elements.last() {
parent.append(n);
} else {
self.root.append(n);
};
}
fn insert_element(&mut self, token_offset: usize, el: Node) {
if let Some((_, parent)) = self.open_elements.last() {
parent.append(el.clone());
} else {
self.root.append(el.clone());
}
self.open_elements.push((token_offset, el));
}
fn current_namespace(&self) -> Namespace {
let Some((_, el)) = self.open_elements.last() else {
return Namespace::Html;
};
el.namespace()
}
}
/// An error that occurs while constructing an HTML tree.
///
/// The error object has all the pieces necessary to build a user-facing report with at crate like `annotate_snippets`.
/// The built-in `Display` implementation simply displays the error code and the byte offset at which it occurred.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParserError {
/// The error code.
pub code: ErrorCode,
/// The byte offset at which the error occurred.
/// This offset refers to [`ParserError::source`].
pub offset: usize,
/// The markup in which the error occurred.
/// This might be different from what was passed in due to input normalization required by the html tokenization spec.
pub source: Arc<String>,
}
impl std::error::Error for ParserError {}
impl std::fmt::Display for ParserError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} at byte offset {}", self.code, self.offset)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum ErrorCode {
EndTagWithoutCorrespondingStartTag,
UnclosedStartTag,
VoidElementAsEndTag,
NonVoidElementStartTagWithTrailingSolidus,
}
impl std::fmt::Display for ErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let code = match self {
ErrorCode::EndTagWithoutCorrespondingStartTag => "no-matching-start-tag",
ErrorCode::UnclosedStartTag => "unclosed-start-tag",
ErrorCode::VoidElementAsEndTag => "void-element-as-end-tag",
ErrorCode::NonVoidElementStartTagWithTrailingSolidus => {
"non-void-element-with-trailing-solidus"
}
};
write!(f, "{}", code)
}
}
#[cfg(test)]
mod tree_structure_tests {
use super::*;
fn print_node(sink: &mut String, node: Node) {
use std::fmt::Write;
match &node.kind() {
NodeKind::Comment => {
write!(sink, "#comment({})", node.text_content()).unwrap();
}
NodeKind::Text => {
write!(sink, "#text({})", node.text_content()).unwrap();
}
NodeKind::Doctype => {
write!(sink, "#doctype({})", node.name()).unwrap();
}
NodeKind::Fragment => {
for c in node.children() {
print_node(sink, c);
}
}
NodeKind::Element => {
write!(sink, "{}", node.name()).unwrap();
let attrs: Vec<_> = node.get_attributes();
if !attrs.is_empty() {
write!(sink, "[").unwrap();
for (i, (k, v)) in attrs.iter().enumerate() {
if i != 0 {
write!(sink, ",").unwrap();
}
write!(sink, "{}={}", k, v).unwrap();
}
write!(sink, "]").unwrap();
}
write!(sink, "(").unwrap();
for c in node.children() {
print_node(sink, c);
}
write!(sink, ")").unwrap();
}
}
}
#[track_caller]
fn check(input: &str, expected: &str) {
let result = parse(input);
let mut actual_output = String::new();
match result {
Ok(root) => {
print_node(&mut actual_output, root);
}
Err(err) => {
use std::fmt::Write;
write!(actual_output, "error @ {}: {}", err.offset, err.code).unwrap();
}
}
assert_eq!(actual_output, expected);
}
#[test]
fn test_cases() {
check("", "");
check(" ", "#text( )");
check("just some text", "#text(just some text)");
check("<!--a comment-->", "#comment(a comment)");
check("<!doctype html>", "#doctype(html)");
check("<div></div>", "div()");
// element casing is not relevant
check("<DIV></DIV>", "div()");
// element with attributes
check("<div a='b'></div>", "div[a=b]()");
// attribute name casing is not relevant
check("<div A='b'></div>", "div[a=b]()");
// void element
check("<link><div></div>", "link()div()");
// void element with trailing solidus
check("<link/><div></div>", "link()div()");
// trailing solidus on non-void elements causes an error
check(
"<div />",
"error @ 0: non-void-element-with-trailing-solidus",
);
// trailing solidus on foreign elements is ok (svg)
check("<svg />", "svg()");
// trailing solidus on foreign elements is ok (svg descendants)
check("<svg><p /></svg>", "svg(p())");
// trailing solidus on foreign elements is ok (math)
check("<math />", "math()");
// trailing solidus on foreign elements is ok (math descendants)
check("<math><variable /></math>", "math(variable())");
// parsing switches states upon encountering certain elements
check(
"<title><tag></title><textarea><tag></textarea><noscript><tag></noscript><style><tag></style><xmp><tag></xmp><iframe><tag></iframe><noembed><tag></noembed><noframes><tag></noframes><script><tag></script>",
"title(#text(<tag>))textarea(#text(<tag>))noscript(#text(<tag>))style(#text(<tag>))xmp(#text(<tag>))iframe(#text(<tag>))noembed(#text(<tag>))noframes(#text(<tag>))script(#text(<tag>))",
);
// unclosed start tag
check("<title>", "error @ 0: unclosed-start-tag");
// unopened end tag
check("</span>", "error @ 0: no-matching-start-tag");
// leading solidus on void elements
check("<link></link>", "error @ 6: void-element-as-end-tag");
// closing tag without matching start tag
check("<div></span>", "error @ 0: unclosed-start-tag");
// end tag with no open element
check("<div></div></span>", "error @ 11: no-matching-start-tag");
}
}