Skip to content

Parsing HTML

Parsing turns a string of HTML into a Document. For a page that’s still bytes, parse_bytes finds its encoding first. Parsec has four entry points for text: parse for a whole page, parse_with for a whole page with Options and errors instead of panics, parse_fragment for markup that belongs inside an element, as innerHTML does, and parse_fragment_with, which is to parse_fragment what parse_with is to parse. All four live at the crate root and are defined in crates/parsec/src/tree.rs.

None of them reports parse errors. The tokenizer and tree builder recover from every mistake the way the HTML Standard says to, silently.

pub fn parse(html: &str, scripting: bool) -> Document

Parses a whole document.

  • html: the page, already decoded to UTF-8. See Input below.
  • scripting: true parses as a browser with JavaScript on, false as one with it off. See What scripting changes.
  • Returns the document. Its root, node 0, is a Kind::Document node.
  • Panics if html.len() is over MAX_INPUT bytes, with the message {len} bytes of HTML is over the 536870912 byte limit.
  • Has no time budget.
let doc = parsec::parse("<p>one<p>two", false);
assert_eq!(doc.inner_html(doc.root()), "<html><head></head><body><p>one</p><p>two</p></body></html>");
pub fn parse_with(html: &str, options: Options) -> Result<Document, ParseError>
#[derive(Debug, Clone, Copy, Default)]
pub struct Options {
pub scripting: bool,
pub budget: Option<std::time::Duration>,
pub max_depth: Option<usize>,
}

parse_with parses a whole document with the options you give and returns an error instead of panicking.

  • Options::scripting is the same flag parse takes. Default: false.
  • Options::budget is how long the parse may take. Default: None, no limit. A budget so large that adding it to the start time overflows the clock (Duration::MAX, say) also means no limit.
  • Options::max_depth is how deep the tree may grow. Past it, a new node goes beside the current element instead of inside it, as Chromium does at 512. Default: None, no limit. Limits and hostile input has the details.

Here’s every way a call can end:

What parse_with does: input over MAX_INPUT returns TooLarge; otherwise it starts the clock if a budget is set, tokenizes and builds the tree, checks the deadline every 4,096 steps, returns Timeout and drops the partial tree if it passed, or returns the document when the input is finished.

Options derives Default, so you can set just the field you care about:

use parsec::{Options, ParseError, parse_with};
use std::time::Duration;
let options = Options {
budget: Some(Duration::from_millis(250)),
..Options::default()
};
match parse_with("<p>fine</p>", options) {
Ok(doc) => assert!(doc.text(doc.root()).contains("fine")),
Err(ParseError::Timeout { parsed, .. }) => println!("gave up after {parsed} bytes"),
Err(ParseError::TooLarge { len }) => println!("{len} bytes is too much"),
}

The clock starts when parse_with is called, after the size check. The tokenizer compares the time with the deadline once every 4,096 turns of its main loop, and tree building happens inside that loop, so the budget covers both. Two consequences worth knowing:

  • The budget is approximate. A parse can run a little past it, and a short input can finish even with a budget of zero, because it never reaches its first check.
  • On timeout the partly built document is dropped. You get the error, not a partial tree.

Limits and hostile input says when you’d want a budget and how big.

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
TooLarge { len: usize },
Timeout { budget: std::time::Duration, parsed: usize },
}

Why parse_with returned no document. It implements std::error::Error and Display.

Variant When Display
TooLarge { len } html.len() is over MAX_INPUT. len is the input’s length in bytes. {len} bytes of HTML is over the 536870912 byte limit
Timeout { budget, parsed } The budget ran out. budget is the one you set; parsed is how many bytes the tokenizer had read. parsing took longer than {budget:?} (gave up after {parsed} bytes)

parsed counts bytes of the input after preprocessing (see Input). If your input had \r\n line endings, each one counts as one byte there, so parsed can be smaller than the matching offset in your original string.

use parsec::{Options, ParseError, parse_with};
use std::time::Duration;
let html = "<div><b>x</b> y</div>".repeat(200_000);
let tight = Options { budget: Some(Duration::from_nanos(1)), ..Options::default() };
match parse_with(&html, tight) {
Err(ParseError::Timeout { parsed, .. }) => assert!(parsed < html.len()),
other => panic!("expected a timeout, got {:?}", other.map(|d| d.len())),
}
pub const MAX_INPUT: usize = 1 << 29; // 536,870,912 bytes, 512 MiB

The most input a document can hold. Parsec stores strings as offsets with a few flag bits on top (see Architecture), and this cap keeps every offset in range. The check is on html.len() in bytes, before anything else happens.

  • parse and parse_fragment panic over the limit.
  • parse_with and parse_fragment_with return ParseError::TooLarge.
use parsec::{MAX_INPUT, Options, ParseError, parse_with};
let too_big = "a".repeat(MAX_INPUT + 1);
assert_eq!(
parse_with(&too_big, Options::default()).err(),
Some(ParseError::TooLarge { len: MAX_INPUT + 1 })
);
pub fn parse_fragment(html: &str, ns: Ns, context: &str, scripting: bool) -> Document

Parses html as the contents of an element named context in namespace ns, the HTML Standard’s fragment parsing algorithm, which is what setting innerHTML runs.

  • html: the markup.
  • ns: the context element’s namespace, Ns::Html, Ns::Svg or Ns::MathMl. Ns::Xml is accepted but means nothing to the HTML parser; don’t use it.
  • context: the context element’s name, such as "div", "tr", "textarea", "svg" or "foreignObject". Known HTML tags are recognised in any case: "TR" and "tr" behave the same.
  • scripting: as for parse.
  • Returns a document whose root, node 0, is a Kind::Fragment node. The parsed nodes are the root’s children.
  • Panics as parse does, over MAX_INPUT bytes.
  • Has no time budget. parse_fragment_with has one.
use parsec::{Kind, Ns, parse_fragment};
// A row's worth of cells only makes sense inside a <tr>.
let doc = parse_fragment("<td>a<td>b", Ns::Html, "tr", false);
assert_eq!(doc.kind(doc.root()), Kind::Fragment);
assert_eq!(doc.inner_html(doc.root()), "<td>a</td><td>b</td>");
// Parsed in a <div> instead, the cells are dropped and only text is left.
let doc = parse_fragment("<td>a<td>b", Ns::Html, "div", false);
assert_eq!(doc.inner_html(doc.root()), "ab");
pub fn parse_fragment_with(html: &str, ns: Ns, context: &str, options: Options) -> Result<Document, ParseError>

parse_fragment with Options: a time budget, a depth limit and the scripting flag, and an error instead of a panic, just as parse_with gives a whole page. Over MAX_INPUT it returns ParseError::TooLarge; past the budget, ParseError::Timeout.

use parsec::{Ns, Options, ParseError, parse_fragment_with};
use std::time::Duration;
let options = Options { budget: Some(Duration::from_millis(250)), ..Options::default() };
let doc = parse_fragment_with("<td>a<td>b", Ns::Html, "tr", options).unwrap();
assert_eq!(doc.inner_html(doc.root()), "<td>a</td><td>b</td>");
let html = "<div><b>x</b> y</div>".repeat(200_000);
let tight = Options { budget: Some(Duration::from_nanos(1)), ..Options::default() };
assert!(matches!(
parse_fragment_with(&html, Ns::Html, "div", tight),
Err(ParseError::Timeout { .. })
));

The context element sets things up exactly as the spec’s fragment case does:

  • The tokenizer’s starting state. For an HTML context, title and textarea start in RCDATA, so tags are text and references are decoded; style, xmp, iframe, noembed and noframes start in RAWTEXT; script in script data; plaintext in PLAINTEXT; and noscript in RAWTEXT when scripting is on. Any other context starts in the data state.
  • The insertion mode, through the spec’s “reset the insertion mode appropriately”: a tr context parses as in a row, table as in a table, select as in a select, html as before the head, and so on.
  • A template context parses as template contents.
  • A form context sets the form element pointer, so a nested <form> is ignored.
  • An SVG or MathML context parses in foreign content.
use parsec::{Ns, parse_fragment};
// RCDATA: the tags are text.
let doc = parse_fragment("a<b>x</b>&amp;", Ns::Html, "textarea", false);
assert_eq!(doc.inner_html(doc.root()), "a&lt;b&gt;x&lt;/b&gt;&amp;");
// SVG: names get SVG's case, and <b> breaks back out into HTML.
let doc = parse_fragment("<clippath/><b>x</b>", Ns::Svg, "svg", false);
assert_eq!(doc.inner_html(doc.root()), "<clipPath></clipPath><b>x</b>");
// An html context gets a head and a body.
let doc = parse_fragment("<p>x", Ns::Html, "html", false);
assert_eq!(doc.inner_html(doc.root()), "<head></head><body><p>x</p></body>");
  • quirks() is always Quirks::No. A fragment never sees a doctype, and Parsec has no outer document whose mode it could borrow, so <p><table> and selector case rules behave as in a no-quirks page.
  • The context element and the <html> element the algorithm uses internally stay in the document’s arena, detached. doc.len() counts them, so an empty fragment has len() == 3. They aren’t reachable from the root.
  • :root never matches in a fragment, because no element’s parent is a Document node. See Selectors.

A whole-document parse decides the document’s mode from its doctype, as the spec’s initial insertion mode does, and Document::quirks() reports it as a Quirks value:

  • Quirks::Quirks when there’s no doctype at all, when the doctype has force-quirks set or a name other than html, or when its public or system identifier is on the spec’s list of legacy ones (-//W3C//DTD HTML 4.01 Transitional// without a system identifier, for example).
  • Quirks::Limited for the XHTML 1.0 Frameset and Transitional public identifiers, and for HTML 4.01 Frameset and Transitional when a system identifier is present.
  • Quirks::No otherwise, including <!DOCTYPE html>.

The mode changes the tree in the places the spec says (in quirks mode a <table> doesn’t close an open <p>), and it changes selector matching: in Quirks::Quirks documents, ids and class names compare without ASCII case. Quirks::Limited doesn’t change either.

use parsec::{Quirks, parse};
assert_eq!(parse("<p>", false).quirks(), Quirks::Quirks);
assert_eq!(parse("<!DOCTYPE html><p>", false).quirks(), Quirks::No);
assert_eq!(
parse(r#"<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"><p>"#, false).quirks(),
Quirks::Limited
);
// In quirks mode the table goes inside the paragraph.
assert_eq!(
parse("<p><table>", false).inner_html(0),
"<html><head></head><body><p><table></table></p></body></html>"
);
assert_eq!(
parse("<!DOCTYPE html><p><table>", false).inner_html(0),
"<!DOCTYPE html><html><head></head><body><p></p><table></table></body></html>"
);

Parsec never runs scripts. The flag says which browser to imitate, one with JavaScript on or one with it off, and the HTML Standard only lets that change one element, <noscript>:

  • Scripting off: <noscript> content is parsed as markup. In the <head>, only <link>, <meta>, <style> and the like stay inside it; anything else closes it.
  • Scripting on: <noscript> content is raw text, like <style>. Its child is one text node holding the markup as written.

The document remembers the flag, and the serializer writes a <noscript>’s text without escaping when it was parsed with scripting on, so the markup round-trips. A fragment with a noscript context follows the same rule.

use parsec::parse;
let html = "<body><noscript><b>x</b></noscript>";
// Off: <b> is an element.
let off = parse(html, false);
assert_eq!(off.text(0), "x");
// On: the whole thing is one text node, written back unescaped.
let on = parse(html, true);
assert_eq!(on.text(0), "<b>x</b>");
assert_eq!(on.inner_html(0), "<html><head></head><body><noscript><b>x</b></noscript></body></html>");

If you’re extracting content, false is usually what you want: <noscript> fallbacks then become real elements your selectors can see.

Parsec takes text, not bytes. Here’s what that means in practice.

  • Decode first. html is a &str, so it’s valid UTF-8 by construction, and these four functions don’t look for a BOM or <meta charset>. If you have bytes, use parse_bytes, which does.
  • A leading byte order mark is dropped from a whole page, as a browser drops it while decoding. A fragment keeps it, as innerHTML would.
  • Line endings. The spec’s input preprocessing turns every \r\n and every lone \r into \n, and Parsec does that before tokenizing. Text you read back has \n only. An input with no \r at all skips the rewrite.
  • NUL characters follow the spec: dropped from text in the body, turned into U+FFFD in foreign content, attribute values and comments.
use parsec::{Quirks, parse};
let raw = "\u{FEFF}<!DOCTYPE html><p>a\r\nb</p>";
// The BOM is dropped, so the doctype comes first, as in a browser.
let doc = parse(raw, false);
assert_eq!(doc.quirks(), Quirks::No);
assert_eq!(doc.text(doc.root()), "a\nb");

parsec_encoding::parse_bytes, in the parsec-web-encoding package, takes the page as bytes, finds its encoding as a browser does, decodes it and calls parse_with:

use parsec_encoding::{Options, parse_bytes};
let page = b"<meta charset=windows-1251><title>\xcf\xf0\xe8\xe2\xe5\xf2</title>";
let parsed = parse_bytes(page, Options::default()).unwrap();
assert_eq!(parsed.encoding.name(), "windows-1251");
assert_eq!(parsed.document.text(parsed.document.root()), "Привет");

The order is the HTML Standard’s: a byte order mark, then the charset from HTTP if you pass it in Options::transport, then the <meta> prescan of the first 1,024 bytes, then the fallback, windows-1252 unless you pick another. If the parser meets a <meta> naming a different encoding than a guess, the page is decoded and parsed once more in that encoding. You get the document, the encoding and its confidence. For bytes that arrive in pieces, parsec_encoding::ByteParser does the same a piece at a time, with the same result (Encoding). Encoding has the details, the options and the conformance counts.

Parser parses a page as it arrives: feed each piece as it comes in, then finish. The tree is exactly the one the whole page would give, whatever the pieces are.

use parsec::{Options, Parser};
let mut parser = Parser::new(Options::default());
for chunk in ["<ul><li>one<l", "i>two</u", "l>"] {
parser.feed(chunk);
}
let doc = parser.finish().unwrap();

Parser::fragment(ns, context, options) does the same for markup inside an element. The tokenizer keeps its place mid-token, as offsets into the source so far, and waits only where what comes next decides what it reads; a CR at the end of a piece waits for the next one, in case an LF follows. parse_with is a Parser fed once. A budget counts only the time spent inside feed and finish, not the time spent waiting for input. Pieces are &str: bytes, with their encoding still to be found, go through parsec_encoding::ByteParser (Encoding).

The guarantee is tested, not just designed for: tests/chunks.rs cuts every html5lib tokenizer and tree-construction input in two at every character boundary, 205,527 cuts, and in random pieces 86,000 more times, and compares the nodes, links, attributes, spans and errors with a one-shot parse. None differ. Feeding 4 KB pieces runs at about 93% of a one-shot parse’s speed.

The parser recovers from every error the way a browser does, so a page always gives a tree. Ask for Options { errors: true, .. } and it also tells you what it recovered from: doc.errors() lists each one as a SyntaxError with its code, the name the HTML Standard and html5lib use, its byte offset in the string you passed, and its 1-based line and column.

use parsec::Options;
let html = "<p>one\n<p>two</b>\0";
let doc = parsec::parse_with(html, Options { errors: true, ..Options::default() }).unwrap();
for e in doc.errors() {
println!("{}:{} {} (byte {})", e.line, e.column, e.code, e.offset);
}
// 1:1 expected-doctype-but-got-start-tag (byte 0)
// 2:7 unexpected-end-tag (byte 13)
// 2:11 unexpected-null-character (byte 17)
// 2:11 invalid-codepoint-in-body (byte 17)

Tokenizer errors carry the spec’s names and sit on the character that caused them; tree-construction errors sit at the start of the token. They’re off by default: with them on, the 8.6 MB of the bench pages parse in about 19.6 ms instead of 13.6. html5lib’s tokenizer error cases run in cargo test and all 7,042 match exactly, code, line and column; for tree construction the suite only lists counts, and those match on 1,802 of 1,967 cases (Conformance). Lexbor reports errors as pointers into its own buffer, with no line or column.

Ask for them with Options { spans: true, .. } and every node and attribute the parser read from your input knows where it was. They’re off by default, so a plain parse costs what it always did; with them on, the 8.6 MB of the bench pages parse in 15.2 ms instead of 13.5.

use parsec::{Options, css::SelectorList};
let html = "<p class=intro>Hi\r\n<b>there</b></p>";
let doc = parsec::parse_with(html, Options { spans: true, ..Options::default() }).unwrap();
let first = |s: &str| SelectorList::parse(s).unwrap().select_first(&doc, doc.root()).unwrap();
let p = first("p");
assert_eq!(&html[doc.span(p).unwrap()], "<p class=intro>");
assert_eq!(&html[doc.attr_span(p, 0).unwrap()], "class=intro");
let b = first("b");
assert_eq!(&html[doc.end_span(b).unwrap()], "</b>");
assert_eq!(doc.line_col(doc.span(b).unwrap().start), (2, 1));
  • span(node) is an element’s start tag, or the whole of a text node, comment, doctype or processing instruction. Text the tree builder joined from several runs spans the first run’s start to the last one’s end.
  • end_span(node) is the end tag that closed an element by name, </body> and </html> included.
  • attr_span(node, i) runs from an attribute’s name to the end of its value, closing quote and all.
  • line_col(offset) gives a 1-based line and a 1-based column counted in characters; a line ends at LF, CRLF or a lone CR.

Offsets are bytes into the string you passed, not the preprocessed buffer: the document remembers where each CRLF became an LF, and a dropped byte order mark, and maps back. Nodes the parser makes up have no span: an implied <html>, <head>, <body> or <tbody>, and the copies of formatting elements it reopens or moves. Lexbor’s nodes carry no positions at all (lexbor#374, lexbor#388); PHP carries a patch for them.

Document owns its data. It keeps its own copy of the preprocessed input, and text and attribute values that needed no decoding point into that copy rather than being copied again. Nothing in the returned document borrows from your html string, so you can drop the string straight after parsing. Architecture explains the layout.