Skip to content
James Conway edited this page Nov 20, 2026 · 4 revisions

Parsec's C API is a shared or static library, libparsec, with one header, parsec.h. It covers what bindings to Lexbor use most: parsing a document or a fragment, selectors, walking the tree, attributes, text, editing and serializing. It also has what Lexbor's C API doesn't: XPath 1.0, where each node and attribute was written, parse errors with line and column, and pages as bytes in any encoding, sniffed as a browser sniffs them, whole or as they arrive. The code is in crates/parsec-capi, and the header is generated from it by cbindgen and checked in.

On this page: Getting it · A first program · Linking · The rules · Parsing · Bytes in any encoding · The tree · Attributes · Text and markup · Selectors · XPath · Source positions · Parse errors · Editing · Status codes · Threads · What isn't in it yet · How it's tested

Note

Parsec isn't released, so the API can still change before 0.1.0. Coming from Lexbor? Moving from Lexbor has each Lexbor call next to this API's.

Getting it

From a release. Each release attaches a package per platform, built by .github/workflows/release-capi.yml and smoke-tested there before it's attached:

Archive Platform
parsec-capi-VERSION-x86_64-unknown-linux-gnu.tar.gz Linux x86-64, glibc 2.35 or newer
parsec-capi-VERSION-aarch64-unknown-linux-gnu.tar.gz Linux ARM64, glibc 2.35 or newer
parsec-capi-VERSION-universal-apple-darwin.tar.gz macOS, one library for Apple silicon and Intel
parsec-capi-VERSION-x86_64-pc-windows-msvc.zip Windows x86-64
parsec-capi-VERSION-aarch64-pc-windows-msvc.zip Windows ARM64

Each archive comes with a build provenance attestation, which you can check with gh attestation verify FILE --repo parsec-html/parsec, and parsec-capi-SHA256SUMS lists their hashes. There's no release yet, so for now you build it yourself.

From a checkout, with Rust 1.88 or newer:

git clone https://github.com/parsec-html/parsec
cd parsec
crates/parsec-capi/package.sh "$HOME/.local/parsec"

The script builds in release mode and lays the package out the same way a release does:

include/parsec.h
lib/libparsec.a, and lib/libparsec.so or lib/libparsec.dylib
    (Windows: lib/parsec.lib, the static library; lib/parsec.dll.lib and bin/parsec.dll, the DLL)
lib/pkgconfig/parsec.pc
lib/cmake/parsec/parsec-config.cmake, parsec-config-version.cmake
LICENSE, NOTICE

A second argument picks a Rust target, such as aarch64-unknown-linux-gnu; universal-apple-darwin builds both macOS architectures and joins them with lipo. On Windows, run it from Git Bash.

A first program

#include <parsec.h>
#include <stdio.h>

static int on_match(parsec_node node, void *ctx) {
    const parsec_document *doc = ctx;
    size_t len;
    char *text = parsec_text(doc, node, &len);
    printf("match: %.*s\n", (int) len, text);
    parsec_string_free(text);
    return 0; /* nonzero stops */
}

int main(void) {
    static const char html[] = "<ul><li class=hit>one<li>two<li class=hit>three</ul>";
    parsec_document *doc;
    if (parsec_parse(html, sizeof(html) - 1, 0, &doc) != PARSEC_OK) return 1;

    parsec_selector *sel;
    char *why;
    if (parsec_selector_compile("li.hit", 6, &sel, &why) != PARSEC_OK) {
        fprintf(stderr, "bad selector: %s\n", why);
        parsec_string_free(why);
        return 1;
    }

    parsec_select(doc, sel, parsec_root(), on_match, doc);

    parsec_node first = parsec_select_first(doc, sel, parsec_root());
    size_t len;
    char *outer = parsec_outer_html(doc, first, &len);
    printf("outer: %.*s\n", (int) len, outer);
    parsec_string_free(outer);

    parsec_selector_free(sel);
    parsec_document_free(doc);
    return 0;
}

It prints:

match: one
match: three
outer: <li class="hit">one</li>

Linking

CMake. Point CMAKE_PREFIX_PATH at the package and link one of its two targets:

find_package(parsec 0.1 REQUIRED CONFIG)
target_link_libraries(app PRIVATE parsec::parsec)          # the shared library
# or
target_link_libraries(app PRIVATE parsec::parsec_static)   # the static one

parsec::parsec_static brings the system libraries Rust's standard library needs along with it. Before 1.0, find_package(parsec 0.1) accepts any 0.1.x at or above what you ask for, and no 0.2.

pkg-config. Point PKG_CONFIG_PATH at the package's lib/pkgconfig:

cc app.c $(pkg-config --cflags --libs parsec) -o app

Libs.private has the system libraries for a static link.

By hand, against the static library: add the package's include to the include path and link lib/libparsec.a (or lib/parsec.lib), plus what Libs.private in parsec.pc lists for your platform. That's -lSystem -lc -lm on macOS, for example.

On macOS the shared library's install name is @rpath/libparsec.dylib, so give your program an rpath (CMake does this for you). On Windows, put parsec.dll next to your program or on PATH.

The rules

These hold for every function, and the top of parsec.h says them too.

Handles are opaque. A parsec_document comes from parsec_parse, parsec_parse_with or parsec_parse_fragment, and goes back with parsec_document_free. A parsec_selector comes from parsec_selector_compile and goes back with parsec_selector_free. A parsec_xpath comes from parsec_xpath_compile and goes back with parsec_xpath_free, and a parsec_xpath_result from parsec_xpath_evaluate goes back with parsec_xpath_result_free. A parsec_byte_parser comes from parsec_byte_parser_new and goes back with parsec_byte_parser_free, finished or not. No handle's layout is part of the API; the one struct you see inside is parsec_syntax_error.

NULL is safe. Pass NULL for a handle and you get PARSEC_ERR_NULL, or NULL, PARSEC_NO_NODE, 0 or false, whichever the function returns. The free functions ignore NULL.

Nodes are numbers. A parsec_node is a uint32_t, the node's index in its document; the document itself is node 0, which parsec_root() returns. A number stays valid, and means the same node, for as long as the document lives, so there's nothing to dangle: the class of use-after-free you get with Lexbor's lxb_dom_node_t * after lxb_dom_node_destroy can't happen. And once parsec_remove has taken a node out, a number you kept for it, or for anything inside it, reads as nothing instead of quietly reading the old node (see Removed and detached nodes). Every function checks the number against the document, and one that isn't a node of it is refused with PARSEC_ERR_NO_SUCH_NODE (or PARSEC_NO_NODE, NULL or 0), never read. A node number from one document means nothing in another; nothing stops you passing it, but you get a different node or an error, never a crash.

Strings in are a pointer and a length in bytes, UTF-8, with no NUL needed. NULL with a length of 0 is the empty string. Bytes that aren't UTF-8 become U+FFFD, as decoding a page as UTF-8 would make them. The exception is a page given to parsec_parse_bytes or a parsec_byte_parser, which is decoded in whatever encoding it's in (Bytes in any encoding). A length over PTRDIFF_MAX is refused.

Strings out come in two kinds, and the type says which:

Returned as From Ends with a NUL Valid until Free with
const char * with *len parsec_node_name, parsec_node_value, parsec_doctype_public_id, parsec_doctype_system_id, parsec_attr_get, parsec_attr_at no the document is next changed or freed nothing; it belongs to the document
const char * with *len parsec_xpath_result_string no the result is freed nothing; it belongs to the result
const char * with code_len a parsec_syntax_error's code no always: it's static nothing
const char * parsec_document_encoding, and *encoding from parsec_parse_bytes yes the document is freed nothing; it belongs to the document
char * with *len parsec_inner_html, parsec_outer_html, parsec_text, and the message from parsec_selector_compile, parsec_xpath_compile or parsec_xpath_evaluate yes, after *len bytes you free it parsec_string_free

A borrowed string's len pointer is required, since there's no NUL to find its end by; with a NULL len you get NULL. An owned string's len may be NULL. Free an owned string with parsec_string_free only, not free(): the library has its own allocator, and on Windows a different C runtime too.

Errors come back as a parsec_status, an int32_t, from every function that can fail for a reason worth telling; PARSEC_OK is 0. parsec_status_message names any of them. Functions that return a node, a string or a count signal failure with PARSEC_NO_NODE, NULL or 0 instead.

Nothing unwinds into C. Every function catches a Rust panic and returns PARSEC_ERR_PANIC, or the function's failure value. A panic is a bug in Parsec; please report it. If it happened while changing a document, the document may be half-changed, so free it.

Parsing

Function Does
parsec_status parsec_parse(const char *html, size_t len, uint32_t flags, parsec_document **out) Parses a whole document. flags is 0, or any of PARSEC_SCRIPTING, PARSEC_SPANS and PARSEC_ERRORS or'd together.
parsec_status parsec_parse_with(const char *html, size_t len, uint32_t flags, uint64_t budget_us, uint32_t max_depth, parsec_document **out) The same, with a time budget in microseconds and a tree depth limit; 0 is none for either.
parsec_status parsec_parse_fragment(const char *html, size_t len, parsec_ns ns, const char *context, size_t context_len, uint32_t flags, parsec_document **out) Parses as the contents of an element named context in ns, as innerHTML does.
void parsec_document_free(parsec_document *doc) Frees the document, every node in it, and every string borrowed from it.
size_t parsec_node_count(const parsec_document *doc) How many nodes it holds, removed ones included. Every number below this is a node.

Bad markup never fails a parse; the parser repairs it as a browser does. What fails is input over 512 MiB (PARSEC_ERR_TOO_LARGE), a budget running out (PARSEC_ERR_TIMEOUT), and bad arguments. On any error *out is set to NULL.

PARSEC_SCRIPTING parses as a browser with JavaScript on, where <noscript> holds raw text. PARSEC_SPANS records where each node and attribute was written (Source positions), and PARSEC_ERRORS keeps the parse errors (Parse errors); the fragment parser takes both too. Any other bit is PARSEC_ERR_INVALID. The budget's clock is read every 4,096 tokenizer steps, so a small input finishes whatever the budget; it's there to bound slow parses. Past max_depth open elements a new node goes beside the current one instead of inside it, as Chromium does at 512. Limits and hostile input explains both.

A fragment is a document of its own. Its root, node 0, is a fragment node (PARSEC_NODE_FRAGMENT) whose children are what was parsed:

static const char rows[] = "<tr><td>1<td>2";
parsec_document *frag;
parsec_parse_fragment(rows, sizeof(rows) - 1, PARSEC_NS_HTML, "tbody", 5, 0, &frag);
char *f = parsec_inner_html(frag, parsec_root(), &len);   /* <tr><td>1</td><td>2</td></tr> */
parsec_string_free(f);
parsec_document_free(frag);

A leading byte order mark is dropped from a whole document and kept in a fragment, as browsers do.

Bytes in any encoding

A page off the network is bytes, and its encoding may be anything: Shift_JIS, windows-1251, UTF-16. parsec_parse_bytes decodes it the way a browser does, by the HTML Standard's encoding sniffing, and parses it:

  1. A byte order mark, if the bytes start with one.
  2. The transport layer's encoding, if you pass one: the charset of an HTTP Content-Type, by any of the Encoding Standard's labels ("shift_jis", "sjis", "latin1", any case). A label that names no encoding is passed over, as browsers pass over charset=utf8mb4.
  3. A <meta charset> or <meta http-equiv=Content-Type> in the first 1,024 bytes.
  4. UTF-8, if the bytes have anything beyond ASCII and are all valid UTF-8: the standard's autodetection step, as Firefox and Chrome take it.
  5. windows-1252, as in a browser set to English.

When the encoding was only a guess (steps 3 to 5) and the parser meets a <meta> naming another, it parses the page again in that one, once, as a browser reloads.

Function Does
parsec_status parsec_parse_bytes(const char *bytes, size_t len, const char *transport, size_t transport_len, uint32_t flags, parsec_document **out, const char **encoding) Decodes and parses a whole document. transport is NULL with a length of 0 for none. flags are parsec_parse's. If encoding isn't NULL, *encoding is the name of the encoding used.
const char *parsec_document_encoding(const parsec_document *doc) The name of the encoding a document's bytes were decoded from, in the Encoding Standard's spelling: "UTF-8", "Shift_JIS", "windows-1252". NUL-terminated, the document's until it's freed; NULL for a document parsed from text.
parsec_status parsec_byte_parser_new(const char *transport, size_t transport_len, uint32_t flags, parsec_byte_parser **out) Starts a parse of bytes that arrive in pieces.
parsec_status parsec_byte_parser_feed(parsec_byte_parser *parser, const char *bytes, size_t len) The next piece.
parsec_status parsec_byte_parser_finish(parsec_byte_parser *parser, parsec_document **out) The end of the page: the document, the same one parsec_parse_bytes gives for all the pieces joined, however they were cut, mid-character included.
void parsec_byte_parser_free(parsec_byte_parser *parser) Frees it, finished or not.
/* charset from the response's Content-Type, or NULL and 0 */
parsec_byte_parser *p;
parsec_byte_parser_new(charset, charset_len, PARSEC_SPANS, &p);
while ((n = read_some(conn, buf, sizeof buf)) > 0)
    parsec_byte_parser_feed(p, buf, n);
parsec_document *doc;
if (parsec_byte_parser_finish(p, &doc) == PARSEC_OK)
    printf("%s\n", parsec_document_encoding(doc));   /* Shift_JIS */
parsec_byte_parser_free(p);

A parser finishes once: after parsec_byte_parser_finish, feeding or finishing it again is PARSEC_ERR_INVALID, and it still has to be freed. Until the encoding is known it holds the bytes back: a byte order mark or a transport encoding decides at once, a <meta> as soon as the prescan has all of it, and otherwise it waits for 1,024 bytes. While the encoding is a guess it keeps every byte, in case a late <meta> means parsing again, so pass the transport encoding when you have it. Encoding has the sniffing in full.

With PARSEC_SPANS or PARSEC_ERRORS, spans and error offsets are byte offsets into the bytes you gave, in their own encoding, so bytes + start is where a tag was sent even in Shift_JIS or UTF-16, and parsec_line_col takes an offset into them. Lines and columns count characters of the decoded page.

The tree

Function Returns
parsec_node parsec_root(void) 0, the document node.
parsec_parent(doc, node) The parent, or PARSEC_NO_NODE for the root, a detached node and a removed one.
parsec_first_child(doc, node), parsec_last_child(doc, node) The first or last child.
parsec_next_sibling(doc, node), parsec_prev_sibling(doc, node) The next or previous node with the same parent.
parsec_template_contents(doc, node) A <template>'s contents, a fragment node holding what the template's markup had inside it; PARSEC_NO_NODE for anything else.
uint32_t parsec_node_type(doc, node) One of the PARSEC_NODE_* numbers below, or 0 for a number that isn't a node.
parsec_ns parsec_element_ns(doc, node) PARSEC_NS_HTML, PARSEC_NS_SVG or PARSEC_NS_MATHML for an element; 0 for anything else.
const char *parsec_node_name(doc, node, size_t *len) An element's name (lowercase for HTML, as the spec writes it for SVG, so foreignObject), a doctype's name, or a processing instruction's target. NULL for other nodes.
const char *parsec_node_value(doc, node, size_t *len) A text, comment or CDATA node's text, or a processing instruction's data. NULL for other nodes.
parsec_doctype_public_id(doc, node, size_t *len), parsec_doctype_system_id(doc, node, size_t *len) A doctype's identifiers, empty when it has none.

Every navigation function returns PARSEC_NO_NODE at the end of the line. A loop over an element's children:

for (parsec_node c = parsec_first_child(doc, el); c != PARSEC_NO_NODE; c = parsec_next_sibling(doc, c)) {
    if (parsec_node_type(doc, c) == PARSEC_NODE_TEXT) {
        size_t len;
        const char *t = parsec_node_value(doc, c, &len);
        printf("%.*s", (int) len, t);
    }
}

The node types use the DOM's nodeType numbers, which are Lexbor's LXB_DOM_NODE_TYPE_* numbers as well:

Constant Value
PARSEC_NODE_ELEMENT 1
PARSEC_NODE_TEXT 3
PARSEC_NODE_CDATA 4
PARSEC_NODE_PROCESSING_INSTRUCTION 7
PARSEC_NODE_COMMENT 8
PARSEC_NODE_DOCUMENT 9
PARSEC_NODE_DOCTYPE 10
PARSEC_NODE_FRAGMENT 11

As in a browser, a template's markup isn't among the template element's children. It's under parsec_template_contents, and selectors don't look inside it.

Attributes

Function Does
size_t parsec_attr_count(doc, node) How many attributes an element has; 0 for anything else.
parsec_status parsec_attr_at(doc, node, size_t index, const char **name, size_t *name_len, const char **value, size_t *value_len) The indexth attribute in source order, name as written (xlink:href, viewBox) and value, both borrowed. Any out pointer may be NULL. PARSEC_ERR_INVALID past the last one, PARSEC_ERR_NOT_AN_ELEMENT on anything but an element.
const char *parsec_attr_get(doc, node, const char *name, size_t name_len, size_t *value_len) The value of the attribute with that name as written, as getAttribute finds it: in any case on an HTML element, exactly on SVG and MathML. NULL if there isn't one.
parsec_status parsec_attr_set(doc, node, name, name_len, value, value_len) Replaces the first attribute with that name, or adds one at the end, as setAttribute does. HTML elements' attribute names are lowercased.
parsec_status parsec_attr_remove(doc, node, name, name_len, bool *removed) Removes it. *removed, if you pass a pointer, says whether there was one; there not being one isn't an error.
size_t vlen;
const char *cls = parsec_attr_get(doc, li, "class", 5, &vlen);
if (cls) printf("class: %.*s\n", (int) vlen, cls);

for (size_t i = 0; i < parsec_attr_count(doc, li); i++) {
    const char *k, *v;
    size_t klen;
    parsec_attr_at(doc, li, i, &k, &klen, &v, &vlen);
    printf("%.*s=%.*s\n", (int) klen, k, (int) vlen, v);
}

Text and markup

Function Gives, as an owned string
char *parsec_inner_html(doc, node, size_t *len) The node's children as markup, as innerHTML does.
char *parsec_outer_html(doc, node, size_t *len) The node and its children, as outerHTML does. On the root, the whole page.
char *parsec_text(doc, node, size_t *len) The text of the node and everything under it, as textContent does.
void parsec_string_free(char *s) Frees any of them.

Serialization has the rules the markup follows: which characters get escaped, void elements, raw text, foreign elements.

Selectors

Function Does
parsec_status parsec_selector_compile(const char *selector, size_t len, parsec_selector **out, char **message) Compiles a selector list. On PARSEC_ERR_SELECTOR, *message (if message isn't NULL) says what's wrong; free it with parsec_string_free.
void parsec_selector_free(parsec_selector *selector) Frees it.
parsec_status parsec_select(doc, selector, parsec_node scope, parsec_match_fn callback, void *ctx) Calls callback(node, ctx) for each match under scope, in document order, and stops when it returns nonzero.
parsec_node parsec_select_first(doc, selector, scope) The first match, without looking further; PARSEC_NO_NODE if none.
bool parsec_matches(doc, selector, node) Whether node matches, with the root element as :scope.

Compile a selector once and use it as often as you like, on as many documents, from as many threads. scope itself is never a match, and it's what :scope matches; as in a browser, combinators look past it, so article .price run on an article finds the prices inside it. Pass parsec_root() to search the whole document.

Don't change the document from inside the callback. Collect the nodes, then change it.

Everything Selectors lists works here, except :target and :local-link, which need the page's URL and have no C function to take it yet, so they match nothing. A selector Parsec doesn't support, such as a pseudo-element or Lexbor's :lexbor-contains(), is refused with PARSEC_ERR_SELECTOR rather than quietly matching nothing.

XPath

Function Does
parsec_status parsec_xpath_compile(const char *expr, size_t len, parsec_xpath **out, char **message) Compiles an XPath 1.0 expression. On PARSEC_ERR_XPATH, *message (if message isn't NULL) says what's wrong; free it with parsec_string_free.
void parsec_xpath_free(parsec_xpath *xpath) Frees it.
parsec_status parsec_xpath_evaluate(doc, xpath, parsec_node context, parsec_xpath_result **out, char **message) Evaluates it with context as the context node (parsec_root() for the document) into a result. Fails with PARSEC_ERR_XPATH, and a message, for a $variable or a query past the work limit.
void parsec_xpath_result_free(parsec_xpath_result *result) Frees a result.
parsec_xpath_type parsec_xpath_result_type(result) PARSEC_XPATH_NODES, PARSEC_XPATH_STRING, PARSEC_XPATH_NUMBER or PARSEC_XPATH_BOOLEAN; 0 for NULL.
size_t parsec_xpath_result_count(result) How many items a node-set holds; 0 for any other result.
parsec_status parsec_xpath_result_item(result, size_t index, parsec_node *node, uint32_t *attr) The indexth item, in document order. A node comes back in *node with *attr set to PARSEC_NO_ATTR; an attribute as its element in *node and its place among the element's attributes in *attr, ready for parsec_attr_at. PARSEC_ERR_INVALID past the last item or on a result that isn't a node-set.
const char *parsec_xpath_result_string(result, size_t *len) A string result, borrowed from the result; NULL for any other.
double parsec_xpath_result_number(result) A number result; NaN for any other.
bool parsec_xpath_result_boolean(result) A boolean result; false for any other.
parsec_xpath *x;
parsec_xpath_compile("//a[@rel='next']/@href", 22, &x, NULL);
parsec_xpath_result *r;
if (parsec_xpath_evaluate(doc, x, parsec_root(), &r, NULL) == PARSEC_OK) {
    for (size_t i = 0; i < parsec_xpath_result_count(r); i++) {
        parsec_node el;
        uint32_t attr;
        parsec_xpath_result_item(r, i, &el, &attr);
        const char *v;
        size_t vlen;
        parsec_attr_at(doc, el, attr, NULL, NULL, &v, &vlen);
        printf("next: %.*s\n", (int) vlen, v);
    }
    parsec_xpath_result_free(r);
}
parsec_xpath_free(x);

Names match as lxml matches them in HTML, lowercase and in no namespace: //div finds every div and //DIV none. A result is a copy, so it stays valid after the document changes or is freed; its node numbers mean what they meant when it was made. The C API binds no $variables and no namespace prefixes, so a query with a variable fails when evaluated.

The first query after a change indexes the document, which costs about a pass over it, and later queries reuse the index until the next change. Like any read, parsec_xpath_evaluate may run on many threads at once, and a compiled parsec_xpath may be shared by them. A query can start at a node you've detached: its subtree is a tree of its own, so //li from it finds the lis under it. One you've removed can't be a context node: that's PARSEC_ERR_REMOVED. The engine, its limits and its conformance are on XPath.

Source positions

With PARSEC_SPANS, the parser records where each node and attribute was written, as byte offsets into the input you gave it (for parsec_parse_bytes and the byte parser, into those bytes in their own encoding):

Function Does
bool parsec_node_span(doc, node, size_t *start, size_t *end) Where the node was written: an element's start tag from < to >, or the whole of a text node, comment, doctype or processing instruction.
bool parsec_end_span(doc, node, size_t *start, size_t *end) Where the end tag that closed an element was written.
bool parsec_attr_span(doc, node, size_t index, size_t *start, size_t *end) Where the indexth attribute (as parsec_attr_at counts) was written, from its name to the end of its value.
parsec_status parsec_line_col(doc, size_t offset, size_t *line, size_t *column) The line and column of any byte offset, both from 1, the column in characters.

The span functions return false, leaving *start and *end alone, when there's nothing to give: the document was parsed without PARSEC_SPANS, the parser implied the node (an <html>, <head>, <body> or <tbody> nobody wrote), an edit made it, it had no end tag, or the handle or node is bad. Either out pointer may be NULL. parsec_line_col reads the input up to offset each time, so call it when you report, not in a loop over every node.

parsec_parse(html, len, PARSEC_SPANS, &doc);
size_t start, end, line, col;
if (parsec_node_span(doc, el, &start, &end)) {
    parsec_line_col(doc, start, &line, &col);
    printf("%zu:%zu: %.*s\n", line, col, (int) (end - start), html + start);
}

Parsing has what each kind of node's span covers.

Parse errors

With PARSEC_ERRORS, the parser keeps each parse error it recovered from:

Function Does
size_t parsec_errors_count(doc) How many there were; 0 without PARSEC_ERRORS.
parsec_status parsec_errors_get(doc, size_t index, parsec_syntax_error *out) The indexth, in source order. PARSEC_ERR_INVALID past the last.
typedef struct {
    const char *code;   /* "unexpected-end-tag": static, code_len bytes, no NUL */
    size_t code_len;
    size_t offset;      /* bytes into the input */
    size_t line;        /* from 1 */
    size_t column;      /* from 1, in characters */
} parsec_syntax_error;
parsec_parse(html, len, PARSEC_ERRORS, &doc);
for (size_t i = 0; i < parsec_errors_count(doc); i++) {
    parsec_syntax_error e;
    parsec_errors_get(doc, i, &e);
    printf("%zu:%zu: %.*s\n", e.line, e.column, (int) e.code_len, e.code);
}

The codes are the HTML Standard's names (eof-in-tag, duplicate-attribute), and for the errors tree construction finds, which the standard leaves unnamed, html5lib's (unexpected-end-tag). Lexbor gives its errors as pointers into the input; these come with the line and column worked out. Parsing has the list.

Editing

Function Does
parsec_node parsec_create_element(doc, parsec_ns ns, const char *name, size_t len) A new element, not yet in the tree. HTML names are lowercased. PARSEC_NO_NODE for an unknown ns.
parsec_node parsec_create_text(doc, text, len) A new text node.
parsec_node parsec_create_comment(doc, text, len) A new comment.
parsec_status parsec_append(doc, parent, child) Moves child to the end of parent's children, taking it from wherever it was.
parsec_status parsec_insert_before(doc, parent, child, before) Moves child into parent just before before, which must be one of parent's children; PARSEC_NO_NODE puts it last.
parsec_status parsec_remove(doc, node) Takes the node and everything in it out for good, as lxb_dom_node_destroy_deep does. Their numbers read as nothing from then on. Removing the root, a template's contents, or a node already removed does nothing.
parsec_status parsec_detach(doc, node) Takes the node out of the tree, as lxb_dom_node_remove does. It and its subtree stay usable: insert it again to move it. PARSEC_ERR_REMOVED for a removed node.
bool parsec_node_is_removed(doc, node) Whether parsec_remove took the node out, or a node it was inside. False for a detached one.

An edit that would break the tree is refused and changes nothing: putting a node inside itself (PARSEC_ERR_CYCLE), giving children to text, a comment or a doctype (PARSEC_ERR_NOT_A_PARENT), a before that isn't the parent's child (PARSEC_ERR_NOT_A_CHILD), inserting a document or fragment node (PARSEC_ERR_NOT_INSERTABLE), and using a removed node as the child, the parent or before (PARSEC_ERR_REMOVED).

parsec_node li = parsec_create_element(doc, PARSEC_NS_HTML, "li", 2);
parsec_append(doc, li, parsec_create_text(doc, "zero", 4));
parsec_insert_before(doc, ul, li, parsec_first_child(doc, ul));

Edits work on the tree; they don't rerun the parser, so a <tr> you put straight into a <div> stays there. A removed node's memory goes when the document does. Editing has the rest of the rules.

Removed and detached nodes

There are two ways to take a node out, and you pick by what you'll do with it next.

parsec_detach is for moving. The node leaves the tree with its subtree still hanging off it, and you put it back with parsec_append or parsec_insert_before.

parsec_remove is for good. It's what fixes the bug Lexbor users know best: you hold a node, some other code removes it, and your next read still gets the old node's text as if nothing happened. After parsec_remove, the node and everything in it (a template's contents and a shadow tree too) read as nothing:

You call On a removed node you get
parsec_parent, _first_child, _last_child, _next_sibling, _prev_sibling, _template_contents PARSEC_NO_NODE
parsec_attr_count 0
parsec_attr_get NULL
parsec_attr_at, parsec_attr_set, parsec_attr_remove PARSEC_ERR_REMOVED
parsec_inner_html, parsec_outer_html, parsec_text "", which you still free
parsec_node_value "", for text, a comment or CDATA
parsec_node_span, parsec_end_span, parsec_attr_span false
parsec_matches, parsec_select_first, parsec_select from it false, PARSEC_NO_NODE, no matches
parsec_append, parsec_insert_before, parsec_detach, parsec_xpath_evaluate PARSEC_ERR_REMOVED
parsec_node_type, parsec_element_ns, parsec_node_name what it was, so you can tell
parsec_node two = parsec_next_sibling(doc, first);
parsec_remove(doc, two);
/* Somewhere else, still holding two: */
if (parsec_node_is_removed(doc, two)) {
    /* parsec_text(doc, two, &len) would give "" now, not its old text. */
}

Status codes

Constant Value Means
PARSEC_OK 0 It worked.
PARSEC_ERR_NULL 1 A pointer that must not be NULL was NULL.
PARSEC_ERR_INVALID 2 An argument was out of range: an unknown flag or namespace, a length over PTRDIFF_MAX, an attribute index past the last.
PARSEC_ERR_TOO_LARGE 3 The input is over 512 MiB.
PARSEC_ERR_TIMEOUT 4 The parse ran past its budget.
PARSEC_ERR_SELECTOR 5 The selector doesn't parse, or uses something Parsec doesn't support.
PARSEC_ERR_NO_SUCH_NODE 6 The number isn't a node of this document.
PARSEC_ERR_NOT_AN_ELEMENT 7 The call needs an element.
PARSEC_ERR_CYCLE 8 The node would end up inside itself.
PARSEC_ERR_NOT_A_PARENT 9 Only an element, a document or a fragment can have children.
PARSEC_ERR_NOT_A_CHILD 10 before isn't a child of the parent.
PARSEC_ERR_NOT_INSERTABLE 11 A document or fragment node can't be inserted.
PARSEC_ERR_PANIC 12 A bug in Parsec, caught before it reached C.
PARSEC_ERR_XPATH 13 The XPath expression doesn't parse, or couldn't be evaluated: it uses a $variable, or ran past the work limit.
PARSEC_ERR_REMOVED 14 The node was taken out with parsec_remove, or was inside one that was, so it can't be edited, inserted or queried.

parsec_status_message(status) gives each one as a static, NUL-terminated sentence, and parsec_version() gives the library's version the same way.

Threads

Any number of threads may read one document at once: every function that takes a const parsec_document *, which includes selecting, XPath and serializing. A selector or a compiled XPath may be used from any number of threads at once. A function that takes a non-const parsec_document * changes the document and needs it to itself, so lock around edits if other threads read the same document. Documents and selectors may be freed on a different thread from the one that made them. A parsec_byte_parser is used by one thread at a time, though it may move between threads.

That's the C side of what Rust checks at compile time: both types are Send and Sync. Thread safety and memory safety has more.

What isn't in it yet

Some of the Rust API has no C function yet: matching :target and :local-link with a URL, creating CDATA sections and processing instructions, renaming elements and attributes, adopt_template_contents, the start tag alone (html_alone), the quirks mode, and the tokenizer on its own. Text in pieces has no C call yet (bytes in pieces do: pass "utf-8" as the transport encoding for UTF-8), and neither does a fallback encoding other than windows-1252 or the sniffing's confidence, which Rust, Python and JavaScript have. Neither API copies nodes between documents. If your binding needs one of these from C, say so in Discussions.

How it's tested

crates/parsec-capi/tests/capi.c calls every function: it parses, selects, walks, edits and serializes, checks every reader on a removed node and moves a detached one, runs XPath before and after an edit, reads spans and parse errors, parses Shift_JIS bytes whole and in pieces with their spans checked against the bytes, and it tries each error path a binding could hit, NULL handles and out-of-range node numbers among them.

  • cargo test builds it with your C compiler and runs it, on Linux and macOS, built with HTML5LIB_ENCODING naming the html5lib-tests encoding/ folder: all 82 cases that don't need a script engine, through parsec_parse_bytes and through the byte parser in pieces of 1 to 7 bytes, pass. The sanitizer job below runs them too; the CMake runs, from a package with no test data, print that they didn't.
  • CI's capi job builds the package with package.sh on Linux, macOS (universal) and Windows, then builds the test through find_package(parsec) twice, against the shared and the static library, and runs both.
  • CI's capi-checks job builds it through pkg-config under AddressSanitizer, LeakSanitizer and UndefinedBehaviorSanitizer. Rust's allocations go through malloc, so a document or string the library failed to free would show up as a leak. The same job fails if parsec.h no longer matches what cbindgen generates from the source, and checks that the header compiles as C++.
  • The release workflow runs the same CMake test on each of the five packages before attaching it.

See also

Clone this wiki locally