domq 0.5.0

Tiny, zero-dependency, forgiving HTML parser: turn messy real-world HTML into a clean DOM tree (and JSON). WASM-first, no_std-friendly.
Documentation
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
//! Static, allocation-free tag classification tables.
//!
//! Everything here is a `const`/`match` over ASCII-lowercased tag names. These
//! tables drive the tokenizer's raw-text handling and the tree builder's
//! void-element and implicit-close behaviour. Names are compared
//! case-insensitively by the callers, which lower-case before lookup.

/// Elements that never have children and never take an end tag.
/// (The HTML "void elements".)
pub(crate) fn is_void(name: &str) -> bool {
    matches!(
        name,
        "area"
            | "base"
            | "br"
            | "col"
            | "embed"
            | "hr"
            | "img"
            | "input"
            | "link"
            | "meta"
            | "param"
            | "source"
            | "track"
            | "wbr"
    )
}

/// Elements whose content is raw text: `<` does not start a tag inside them,
/// and entities are *not* decoded. Scanning runs until the matching end tag
/// (for `<plaintext>`, to the end of the input).
pub(crate) fn is_raw_text(name: &str) -> bool {
    matches!(
        name,
        "script" | "style" | "xmp" | "iframe" | "noembed" | "noframes" | "plaintext"
    )
}

/// Elements the tokenizer reads as text up to their end tag: the raw-text
/// ones plus `title` and `textarea` (whose text is still entity-decoded).
/// Whatever is serialized inside one must not contain that end tag.
pub(crate) fn ends_only_at_end_tag(name: &str) -> bool {
    is_raw_text(name) || matches!(name, "title" | "textarea")
}

/// Whether `name` can be written out as an attribute name as it is: not
/// empty, and none of ASCII whitespace, `"`, `'`, `<`, `>`, `/`, `=` or NUL,
/// which would end the name early or start new markup.
pub(crate) fn is_valid_attr_name(name: &str) -> bool {
    !name.is_empty()
        && !name.bytes().any(|b| {
            b.is_ascii_whitespace() || matches!(b, b'"' | b'\'' | b'<' | b'>' | b'/' | b'=' | 0)
        })
}

/// Whether `name` can be written out as a tag name as it is: a valid
/// attribute name that starts with an ASCII letter. (After `<` anything else
/// is text, and the element's attribute values would be read as markup.)
pub(crate) fn is_valid_tag_name(name: &str) -> bool {
    name.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) && is_valid_attr_name(name)
}

/// Start tags that implicitly close an open `<p>`: every element the WHATWG
/// "optional tags" rules let a `</p>` be omitted before, plus the other start
/// tags tree construction closes a `<p>` for (`center`, `dir`, `li`, `dd`,
/// `dt`, `summary`, `listing`, `plaintext`, `xmp`).
fn closes_p(name: &str) -> bool {
    matches!(
        name,
        "address"
            | "article"
            | "aside"
            | "blockquote"
            | "center"
            | "dd"
            | "details"
            | "dialog"
            | "dir"
            | "div"
            | "dl"
            | "dt"
            | "fieldset"
            | "figcaption"
            | "figure"
            | "footer"
            | "form"
            | "h1"
            | "h2"
            | "h3"
            | "h4"
            | "h5"
            | "h6"
            | "header"
            | "hgroup"
            | "hr"
            | "li"
            | "listing"
            | "main"
            | "menu"
            | "nav"
            | "ol"
            | "p"
            | "plaintext"
            | "pre"
            | "search"
            | "section"
            | "summary"
            | "table"
            | "ul"
            | "xmp"
    )
}

fn is_heading(name: &str) -> bool {
    matches!(name, "h1" | "h2" | "h3" | "h4" | "h5" | "h6")
}

/// Metadata start tags that stay inside an open `<head>`; any other start tag
/// (`<body>`, `<div>`, …) means the `</head>` was omitted.
fn in_head(name: &str) -> bool {
    matches!(
        name,
        "base"
            | "basefont"
            | "bgsound"
            | "link"
            | "meta"
            | "noframes"
            | "noscript"
            | "script"
            | "style"
            | "template"
            | "title"
    )
}

/// Table-structure start tags that end an open cell, row, row group or
/// caption (the WHATWG "in cell" / "in row" / "in table body" / "in caption"
/// rules, minus the scope checks).
fn table_structure(name: &str) -> bool {
    matches!(
        name,
        "caption" | "col" | "colgroup" | "tbody" | "tfoot" | "thead"
    )
}

/// Given a start tag `opening` and the tag name `open` currently on top of the
/// open-element stack, decide whether `open` should be implicitly closed first.
///
/// These are the WHATWG "optional tags" rules (13.1.2.4) — an end tag may be
/// omitted when the element is immediately followed by one of these start
/// tags — together with the tree-construction cases that act on the current
/// node: `<li>`/`<dt>`/`<dd>`/headings closing `<p>`, a heading closing an
/// open heading, `<colgroup>` ending at the first non-`<col>` content, and
/// table sections, rows, cells and captions closing each other. They only ever
/// look at the *top* of the stack, so the builder needs no insertion modes,
/// scopes or active-formatting list.
pub(crate) fn implicitly_closes(opening: &str, open: &str) -> bool {
    match open {
        "p" => closes_p(opening),
        "li" => opening == "li",
        "dt" | "dd" => matches!(opening, "dt" | "dd"),
        "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => is_heading(opening),
        "head" => !in_head(opening),
        "option" => matches!(opening, "option" | "optgroup" | "hr"),
        "optgroup" => matches!(opening, "optgroup" | "hr"),
        "rb" | "rt" | "rp" => matches!(opening, "rb" | "rt" | "rtc" | "rp"),
        "rtc" => matches!(opening, "rb" | "rtc"),
        "td" | "th" => matches!(opening, "td" | "th" | "tr") || table_structure(opening),
        "tr" => opening == "tr" || table_structure(opening),
        "thead" | "tbody" | "tfoot" => table_structure(opening),
        "caption" => matches!(opening, "td" | "th" | "tr") || table_structure(opening),
        "colgroup" => !matches!(opening, "col" | "template"),
        _ => false,
    }
}

/// [`search`] or [`p_search`].
pub(crate) type SearchFn = fn(&str, &str) -> Option<Search>;

/// What a start tag finds at one open element while looking past the
/// current node for an element it closes (see [`search`]).
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Search {
    /// The start tag closes this element (and everything above it).
    Closes,
    /// The search ends here: this element is a scope boundary.
    Stops,
    /// Look further down.
    Continue,
}

/// For the start tags WHATWG lets close an element *below* the current node,
/// what `opening` finds at the open element `open`; `None` for every other
/// start tag ([`implicitly_closes`] only looks at the current node).
///
/// * `<li>`, `<dd>`, `<dt>` close the open list item of their kind, looking
///   past anything but a "special" element (other than `address`, `div` and
///   `p`): `<li><a>One<li>` gives two items.
/// * Table rows, cells and sections close the open cell, row, section or
///   caption they end, looking past anything but `table`, `template` or
///   `html` (table scope): `<td><b>x<td>` gives two cells.
///
/// After that, a start tag that closes a `<p>` closes one in "button scope"
/// ([`p_search`]). The elements above the one closed are closed with it;
/// browsers would reopen formatting elements among them (`<b>`, `<i>`, …)
/// inside the new element, which domq does not.
pub(crate) fn search(opening: &str, open: &str) -> Option<Search> {
    let found = |closes: bool, stops: bool| {
        Some(if closes {
            Search::Closes
        } else if stops {
            Search::Stops
        } else {
            Search::Continue
        })
    };
    match opening {
        "li" => found(
            open == "li",
            is_special(open) && !matches!(open, "address" | "div" | "p"),
        ),
        "dd" | "dt" => found(
            matches!(open, "dd" | "dt"),
            is_special(open) && !matches!(open, "address" | "div" | "p"),
        ),
        "td" | "th" | "tr" => found(
            implicitly_closes(opening, open),
            matches!(open, "table" | "template" | "html"),
        ),
        o if table_structure(o) => found(
            implicitly_closes(opening, open),
            matches!(open, "table" | "template" | "html"),
        ),
        _ => None,
    }
}

/// [`search`] for the `<p>` that `opening` closes, if it closes one: in
/// "button scope", past inline elements but not past a table, cell, caption,
/// button, object, applet, marquee, template, SVG or MathML.
pub(crate) fn p_search(opening: &str, open: &str) -> Option<Search> {
    if !closes_p(opening) {
        return None;
    }
    Some(if open == "p" {
        Search::Closes
    } else if matches!(
        open,
        "applet"
            | "button"
            | "caption"
            | "html"
            | "marquee"
            | "math"
            | "object"
            | "svg"
            | "table"
            | "td"
            | "template"
            | "th"
    ) {
        Search::Stops
    } else {
        Search::Continue
    })
}

/// WHATWG's "special" elements (13.2.4.2), which end the search of
/// [`search`] for list items.
fn is_special(name: &str) -> bool {
    matches!(
        name,
        "address"
            | "applet"
            | "area"
            | "article"
            | "aside"
            | "base"
            | "basefont"
            | "bgsound"
            | "blockquote"
            | "body"
            | "br"
            | "button"
            | "caption"
            | "center"
            | "col"
            | "colgroup"
            | "dd"
            | "details"
            | "dialog"
            | "dir"
            | "div"
            | "dl"
            | "dt"
            | "embed"
            | "fieldset"
            | "figcaption"
            | "figure"
            | "footer"
            | "form"
            | "frame"
            | "frameset"
            | "h1"
            | "h2"
            | "h3"
            | "h4"
            | "h5"
            | "h6"
            | "head"
            | "header"
            | "hgroup"
            | "hr"
            | "html"
            | "iframe"
            | "img"
            | "input"
            | "keygen"
            | "li"
            | "link"
            | "listing"
            | "main"
            | "marquee"
            | "menu"
            | "meta"
            | "nav"
            | "noembed"
            | "noframes"
            | "noscript"
            | "object"
            | "ol"
            | "p"
            | "param"
            | "plaintext"
            | "pre"
            | "script"
            | "search"
            | "section"
            | "select"
            | "source"
            | "style"
            | "summary"
            | "table"
            | "tbody"
            | "td"
            | "template"
            | "textarea"
            | "tfoot"
            | "th"
            | "thead"
            | "title"
            | "tr"
            | "track"
            | "ul"
            | "wbr"
            | "xmp"
            | "svg"
            | "math"
    )
}

/// Whether non-whitespace text implicitly closes the open element `open`:
/// text never belongs in a `<head>` or a `<colgroup>`.
/// Elements an ancestor's end tag may close without a parse error, because
/// their own end tag is optional (WHATWG "generate implied end tags
/// thoroughly", plus `html`/`head`/`body`): `</ul>` closing an open `<li>` is
/// valid HTML.
pub(crate) fn end_tag_optional(name: &str) -> bool {
    matches!(
        name,
        "body"
            | "caption"
            | "colgroup"
            | "dd"
            | "dt"
            | "head"
            | "html"
            | "li"
            | "optgroup"
            | "option"
            | "p"
            | "rb"
            | "rp"
            | "rt"
            | "rtc"
            | "tbody"
            | "td"
            | "tfoot"
            | "th"
            | "thead"
            | "tr"
    )
}

pub(crate) fn text_closes(open: &str) -> bool {
    matches!(open, "head" | "colgroup")
}

/// How the readable-output serializers (`to_text`, `to_markdown`) lay an
/// element out: a rough stand-in for the CSS `display` of the browser's default
/// stylesheet. Unknown and custom elements are inline.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Display {
    /// Never rendered: metadata, scripts, templates, embedded objects.
    Hidden,
    /// Flows with the surrounding text.
    Inline,
    /// Starts on a new line.
    Block,
    /// Separated from its neighbours by a blank line.
    Paragraph,
}

/// The [`Display`] of an element, by lower-cased tag name.
pub(crate) fn display(name: &str) -> Display {
    match name {
        "head" | "title" | "script" | "style" | "template" | "noscript" | "noembed" | "iframe"
        | "object" | "svg" | "datalist" => Display::Hidden,
        "p" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "blockquote" | "pre" | "ul" | "ol"
        | "menu" | "dl" | "table" | "hr" => Display::Paragraph,
        "address" | "article" | "aside" | "body" | "caption" | "center" | "dd" | "details"
        | "dialog" | "div" | "dt" | "fieldset" | "figcaption" | "figure" | "footer" | "form"
        | "header" | "hgroup" | "html" | "legend" | "li" | "main" | "nav" | "optgroup"
        | "option" | "search" | "section" | "summary" | "tbody" | "textarea" | "tfoot"
        | "thead" | "tr" => Display::Block,
        _ => Display::Inline,
    }
}