---
title: "The incremental parser"
url: https://recursiveai.org/onehtml/docs/incremental-parser/
description: "IncrementalParser (namespace RecursiveAI.OneHtml.Parsing) is the HTML parser of HTML 13.2 for a host that runs scripts: it reads input as it arrives…"
version: "1.8.0"
source: https://github.com/recursive-ai-oss/onehtml-csharp/blob/9213d47aed47f691bf05853759fd8e328a6a980e/docs/incremental-parser.md
---

# The incremental parser

`IncrementalParser` (namespace `RecursiveAI.OneHtml.Parsing`) is the HTML parser of HTML 13.2 for a host that runs scripts: it reads input as it arrives, builds into a [`MutableDocument`](https://recursiveai.org/onehtml/docs/mutable-document/), stops at each script so the host can prepare and run it, and takes `document.write` input at the insertion point (HTML 8.4.3). `Document.Parse` is unchanged and stays the way to parse a complete input.

This page is normative for the behaviour the standard leaves open, so that another implementation can reproduce it.

## 1. Use

```csharp
var parser = new IncrementalParser(new IncrementalParserOptions { ContentType = "text/html; charset=utf-8" });
ParserResult r = parser.Feed(bytes);                  // or Feed(ReadOnlySpan<char>)
while (r.Status is ParserStatus.ScriptReady or ParserStatus.Yielded)
{
    if (r.Status == ParserStatus.ScriptReady) { /* prepare and run r.Script; it may call parser.Write(...) */ }
    r = parser.Resume();
}
r = parser.End();                                      // then the same loop, until EndOfDocument
parser.Document.Commit();                              // the host commits; the parser never does
```

| Member | Meaning |
|---|---|
| `Feed(bytes)`, `Feed(chars)` | Give input. A parser takes bytes or characters, not both. |
| `End()` | The input has ended. |
| `Resume()` | Go on after `Yielded`, or after the script of the last `ScriptReady` has run. |
| `Write(text)`, `Writeln(text)` | `document.write` / `writeln` for a waiting script. |
| `ScriptNestingLevel` | Scripts waiting for `Resume` (HTML 13.2.6.4.8). |
| `PendingParsingBlockingScript` | Set by the host while a prepared script is the document's pending parsing-blocking script. |
| `Document` | The `MutableDocument` being built. |

Results:

- `NeedMoreInput`: everything given is used up. Inside a script, "given" means what the script wrote.
- `Yielded`: a budget ended the call (`YieldAfterTokens`, `YieldAfterTime`, checked every 64 tokens). `Resume()` continues.
- `ScriptReady(script)`: at the end tag of a script element in the "text" insertion mode (HTML 13.2.6.4.8), or of an SVG `script` in foreign content (13.2.6.5), after the element was popped and the insertion mode restored, and before "prepare the script element". The text after the end tag has not been parsed. The host runs the microtask checkpoint the standard asks for (when its JavaScript execution context stack is empty), prepares the script and runs it if it is ready, then calls `Resume()`; if the script is a pending parsing-blocking script, the host sets `PendingParsingBlockingScript` and calls `Resume()` when the script and the style sheets that block scripts are ready.
- `EndOfDocument`: the end of the input was reached and every open element closed. The host runs "the end" steps. A script element still open at the end of the input is popped without being reported, so the host must treat such a script as "already started".
- `EncodingChange(encoding)`: see 4.

A call can throw `HtmlLimitExceededException` (input, nesting, write limits, the parse limits of `ParseLimits`), `DomException` (a limit of the working document), `InvalidOperationException` (a call in a state that cannot take it) and `OperationCanceledException` (the parser stays usable). After any other exception the parser is failed and every later call throws `InvalidOperationException`.

## 2. Script nesting, the insertion point and `Write`

The tokenizer reads from a buffer, `0 .. limit`. With no script waiting the limit is the end of everything given. `ScriptReady` increments the nesting level and pushes the limit, then sets the limit to the tokenizer's position: the **insertion point** is "just before the next input character" and nothing after it is read. `Write` puts the text in front of the insertion point, parses it at once and stops where the written text ends: the result is `NeedMoreInput`, or `ScriptReady` for a script inside the written text, which increments the level again and moves the insertion point to after that script's end tag, so what the nested script writes goes before the rest of the earlier write. `Resume()` pops the level and restores the previous limit ("let the insertion point have the value of the old insertion point"), and parsing goes on with what is left, a half-read token included. Calls to `Feed` while a script waits are held and read after the last `Resume`.

Rules:

- `Write` with no script waiting (nesting level zero) throws `InvalidOperationException`: the insertion point would be undefined, so `document.write` would call `document.open`, which this parser does not do. The same after `EndOfDocument`.
- While `PendingParsingBlockingScript` is true `Write` inserts and does not parse (HTML 8.4.3, `document.write` step 8); `Resume()` clears it.
- Written text is preprocessed like the input (CR LF and CR become LF); a CR that ends one `Write` does not swallow an LF that starts the next (the input stream of `Feed` does swallow it).
- Cost: inserting `k` characters moves only what the tokenizer had read but not used (a half-read token) and the `k` characters, into the space the tokenizer has already read; text after the insertion point is not moved, so a loop of small writes is linear. Reallocation, when the read space is too small, makes room in proportion to the buffer, so it is amortized.
- Limits (all typed `HtmlLimitExceededException`): `MaxScriptNesting` (default 64, checked before `ScriptReady` is returned), `MaxWrittenCharacters` (default 16,777,216, over the whole parse), and `ParseLimits.MaxInputLength` over every character fed or written. Nothing recurses on nesting or markup depth.

## 3. Streaming tokenization

The tokenizer is the batch tokenizer reading from the buffer. When the input is not final, a token, or a decision between tokens, that depends on characters not yet there is **not made**: the tokenizer goes back to where it was and reports that it needs more. So the tokens are the same for every way of splitting the input (tested: the html5lib tokenizer suite at five splittings, tree construction at five splittings). The cases:

- a tag, comment, DOCTYPE, processing instruction or CDATA marker that the buffer ends inside (every case where the batch tokenizer reports end of file);
- a `<` or `</` at the end of the buffer in a text state; the letters of an end tag name that match the "appropriate end tag" so far, with the character after the name still missing; in script data, `<!`, `<!-` and the escape states' look-ahead (HTML 13.2.5.15–13.2.5.31);
- a character reference that the buffer ends inside: `&` at the end; a named reference whose longest match has no semicolon with fewer than 33 characters after the ampersand; an alphanumeric run reaching the end; a numeric reference whose digits (or semicolon) reach the end. (Inside a tag, the tag is incomplete anyway.)
- in a CDATA section, a trailing `]` or `]]`.

Plain text up to the end of the buffer is emitted as it is and does not wait. The tree builder joins adjacent character tokens (they were always joined in the batch parser, which produced one token per reference).

Cost: a token that is still incomplete is read again when more input arrives. For an incomplete token longer than 4096 characters the tokenizer waits until the buffer has grown by one eighth before it looks again (or until the input ends), so a very long comment fed a character at a time costs `O(n log n)`-ish work, not `O(n²)`; the only effect is a later `ScriptReady` when the token is an end tag with a very long attribute list.

## 4. Bytes and encodings

`Feed(bytes)` waits for `PrescanLimit` bytes (default 1024) or `End()`, then sniffs (HTML 13.2.3.2): a byte order mark (certain), `OverrideEncoding` (certain, a byte order mark still wins), the transport `Content-Type` charset (certain), the `<meta>` prescan (tentative), `DefaultEncoding` (windows-1252, tentative). The bytes are then decoded as they come. Every decoder of the Encoding Standard works one character at a time, so the last four bytes are held back (they may be the start of a character) and everything before is decoded from the first byte of a character; ISO-2022-JP and `replacement` are decoded when the input ends. A CR at the end of a decoded piece is the same LF as a CR LF whose LF comes next; that LF is dropped. Newlines are normalized by the decoder as in `Document.Parse`.

"Change the encoding" (HTML 13.2.3.5), when a `<meta>` names an encoding while the encoding is tentative: UTF-16 labels become UTF-8 and x-user-defined becomes windows-1252; the same encoding only makes the confidence certain. If every byte decoded so far was ASCII and both encodings are ASCII-compatible the decoder switches at once (no restart; the standard lets the user agent do this). Otherwise the parser stops and returns `EncodingChange(encoding)`; the host starts a new parse of the same bytes with that encoding as `OverrideEncoding`. Character input has no encoding.

## 5. The tree

- The parser builds the working document's nodes in the order the standard gives and links them through the same steps a script's `insertBefore` goes through, except that the pre-insertion validity checks are not run (the tree construction rules decide the places) and a text node grows in place. So `MutationHooks` fire (insertion steps, post-connection steps, children changed, attribute change for each token attribute before the element is linked) and `MutationObserver` records are queued (child list per insert, character data per added piece of text) exactly as for other changes; the parser itself never commits, never notifies and never releases.
- A parser-made element is created when it is first linked into the tree (HTML "create an element for a token" followed at once by "insert an element"). When the document has custom element definitions the element is made by `CustomElementRegistry.CreateElementForToken` (with "will execute script": the microtask checkpoint hook, the throw-on-dynamic-markup-insertion counter, a synchronous constructor, then the token's attributes), before the element is linked, at the insertion location computed before the constructor ran; the link itself runs inside a pushed and popped custom element reactions queue (13.2.6.1 "insert an element at the adjusted insertion location"), so `connected` and attribute reactions run right after the insert. The parser holds no registry state across `ScriptReady`. `Write` called while the counter is above zero (from inside such a constructor) throws `DomException` `InvalidStateError`, before the insertion point is looked at. Without definitions the parser creates elements directly.
- What scripts did between two calls is what the parser sees: parents, previous siblings and the document's element children are read from the working tree each time. A node a script moved is found where it is; text goes into the text node before the insertion location only if it is really there; an element is not inserted into a document that already has an element child (HTML 13.2.6.1: it is created and pushed but not inserted). Handling of the last-table-or-template foster parent, the adoption agency algorithm and "reconstruct the active formatting elements" use the same rules. The open elements and the active formatting elements keep the attributes the token gave them (the standard says the token), and the "Noah's Ark" comparison uses those too.
- A declarative shadow root (`<template shadowrootmode>`) is attached to the host when the template start tag is read, as in the batch parser, and what follows is inserted into the root. The root's slot assignment is the document's.
- A node the host released while the parser still has it open makes the next call throw `DomException(StaleNode)`.

## 6. Differences from `Document.Parse`

- Not built: source ranges, parse errors, fragment parsing, the lossless writer (a working document has no source).
- `selectedcontent`: both parsers fill `selectedcontent` from the selected `option` of a select without `multiple`. The batch parser does it inside the tree builder; the incremental parser leaves it to the working document's DOM steps (section 9), which also serve scripts' edits.
- The scripting flag defaults to true (`IncrementalParserOptions.ScriptingEnabled`), since a host that runs scripts has it on.
- A processing instruction's data keeps U+0000 as the batch parser does.

## 7. Tests

- html5lib tree construction (all non-fragment cases, scripting on and off where the case does not say) through the parser at five splittings (whole, one character, three, two random): 100%, except the six `scripted_*` cases, which are translated to the DOM calls their scripts make (`ScriptedTreeConstructionTests`) and pass at all five splittings.
- html5lib tokenizer suite through the streaming tokenizer at the same splittings: 100% of the cases the batch run takes.
- web-platform-tests `html/webappapis/dynamic-markup-insertion/document-write/` and `html/syntax/parsing/` at `ffc4686d117de150daf1287809302e3edea82dc6` (fetched by `tools/wpt/fetch_document_write.py`): each page is parsed as a stream, each script is run by a small interpreter of the subset of JavaScript those pages use (`document.write`, assertions, string and loop statements, node properties), and every assertion must hold. 46 pages pass at two splittings (a page counts only if at least one assertion ran); the rest are listed with their reason in `testdata/wpt/document-write/expectations.txt` (external scripts, module scripts, a second browsing context or `document.open`, closures and event handlers). `html5lib_write*.html` of the parsing directory exercise `document.open` and are in that list; the same cases are covered by the tree construction run above at "whole" and "one character" splittings.
- Script stops and ordering, nested write, budgets, encoding changes, declarative shadow roots, hooks and observer records, limits, cancellation, linear cost of loops of small writes and of very long unfinished tokens: `IncrementalScriptTests`.
- A fuzz target (`incremental`) cuts the input at random, runs a host that writes, adds and removes at each script, and checks that the tree does not depend on the cut and equals the batch tree when no script ran.

## 8. `document.open()`, `document.close()` and `document.write()` with no active parser

`DocumentInput` (one per `MutableDocument`) is the document-level state and the algorithms of HTML 8.4. `DocumentInput(parser)` makes the navigation parser the document's active parser; `DocumentInput(document)` is for a document that has none (an `about:blank` document).

| Member | Standard |
|---|---|
| `Open()` | the document open steps (8.4.2). Returns the new script-created parser, or `null` where a step says "return document". |
| `Close()` | the `close()` steps (8.4.3). |
| `Write(text)`, `Writeln(text)` | the document write steps (8.4.3), including the implicit open. |
| `AbortDocument()` | sets "active parser was aborted" and aborts the active parser. |
| `ActiveParser`, `InsertionPointDefined` | "active parser"; "insertion point is undefined" is `!InsertionPointDefined`. |
| `ActiveParserWasAborted`, `IgnoreOpensDuringUnloadCounter`, `IgnoreDestructiveWritesCounter`, `ThrowOnDynamicMarkupInsertionCounter` | the Document's flag and counters. The last one is the custom element registry's, which raises it around a constructor the parser runs. |
| `IncrementalParser.Abort()`, `IsAborted`, `IsScriptCreated`, `IsEnded` | "abort a parser"; the parser kind. |
| `MutableDocument.Mode` | the compatibility mode (`document.compatMode`). |

Order of `Open()`: (1) `DocumentOpenHost.IsXmlDocument` then `InvalidStateError`; (2) the throw-on-dynamic-markup-insertion counter, `InvalidStateError`; (3, 4) `CheckSameOrigin` (the host throws its `SecurityError`); (5) an active parser whose script nesting level is above zero: return; (6) the unload counter above zero (the standard's present name for the counter its tests call "ignore-opens-during-unload"): return; (7) "active parser was aborted": return; (8) `StopLoading`; (9, 10) `EraseEventListeners`; (11) the active parser, if any, is aborted (`IncrementalParser.Abort`) and `ParserAborted` is called; the document's children are replaced with nothing (12); (13) `UpdateUrlAndHistory`; (14, 15) `ClearInitialAboutBlank`; (16) no-quirks mode; (17) the script-created parser is made, the insertion point is the end of its (empty) input; (19) `Opened` (readiness "loading"). Replacing the children goes through the ordinary removal steps (hooks run for the removed nodes, mutation observers get one record per child with the document as target; the "suppress observers" detail of "replace all" for descendants applies as it does for every replace-all), so live ranges, when they exist, are adjusted by the same steps.

`Write` is the document write steps: the XML and counter checks throw `InvalidStateError`; with "active parser was aborted" set it returns; when the insertion point is undefined it returns if the unload counter or the ignore-destructive-writes counter is above zero, otherwise it runs `Open()` (and returns if that does); then it inserts the text at the insertion point and parses it (the script-created parser takes the text at the end of its input; a parser running a script takes it before the rest, as in section 2). `Close()` returns at once without a script-created parser; otherwise the input is ended (`IncrementalParser.End`) and, unless the host set `PendingParsingBlockingScript`, the parser runs to the end or to a script.

**The host's steps** (virtual members of `DocumentOpenHost`, which do nothing by default): whether the document is an XML document; the same-origin check; stopping the navigation; erasing event listeners and handlers of the document's shadow-including tree and of the window (the library has no "erase all listeners" call; the host removes what it added through `EventTarget`); the readiness changes and the remainder of "abort a parser"; the URL and history update; the "initial about:blank" and iframe mute flags; "abort a document" beyond the parser (unloading, stopping loads, readiness); running scripts, deferred scripts and the load events after `EndOfDocument`; `document.open(url, name, features)` (that is `window.open`). The counters other than the registry's are plain properties the host raises and lowers around its own unload events.

Choices the standard leaves open: the parser `Open()` makes copies the options of the `DocumentInput` (only the parse flags and limits matter, it reads characters); an aborted parser answers every later call with `EndOfDocument`; a CR that ends one `Write` does not swallow an LF that begins the next, but a script-created parser's input stream does swallow it (its writes are one stream); after `Close()` the parser is no longer the active parser once it reached `EndOfDocument`, and a script running when `Close()` is called defers the end to `Resume` (the input is ended, the insertion point stays); `Write` with `PendingParsingBlockingScript` set inserts without parsing, as for a parser running a script.

Tested: `DocumentOpenTests` (the steps, the host calls in order, the counters, quirks, mutation records, removal steps, custom element constructor, pending script, and every html5lib tree construction case written after `open()` as one write and as one write per character, then closed: the standard's `html5lib_write.html` and `html5lib_write_single.html`) and `WptDocumentWriteTests`, whose `expectations.txt` lists every page of `opening-the-input-stream/` and `closing-the-input-stream/` (WPT at the pin) with the C# test that translates its DOM-level assertions, or the reason it needs a browsing context, navigation, URL, history or the test harness.

## 9. `selectedcontent`

The DOM steps live in the working document (`MutableDocument`), not the tree builder: they run from the primitives that link and unlink nodes and change attributes (so a script's edits and a parse behave the same), and from the parser when an `option` is popped (the "option HTML element children parsed steps"). They serve selects without the `multiple` attribute: the element's content is the clones of the children of the select's selected option (the last option with `selected`, else the first option that is not disabled when the display size is 1; the display size is `size` when it parses as a non-negative integer, else 1), left empty when none is selected, with `script`, SVG `script`, `frame`, `iframe`, `embed` and `object` left out of the copy. A `selectedcontent` is disabled (and not filled) inside another `select`, an `option` or a `selectedcontent`. The updates run when: a `select`, `option` or `selectedcontent` is inserted; a node holding an option is removed; the attributes `selected`, `disabled` (on an option or optgroup), `size` or `multiple` change; the parser pops the selected option. The standard's "queue a microtask" runs at once after the mutation, and a replace-all of children runs it once after the last child. Appending options one by one is constant time per option: the selection is cached and only a change that can alter it recomputes. The work is skipped entirely while the document has never held a `selectedcontent`.

Not done: a `select` with `multiple` is not given clones of its options (the standard's "clone multiple options"); changes to an option's children after it was copied are not mirrored until the next update, as the standard says; moves are treated as a removal and an insertion.
