Skip to content
James Conway edited this page Nov 19, 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. 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 · The tree · Attributes · Text and markup · Selectors · 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. No struct's layout is part of the API.

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. Removing a node only detaches it, 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. 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. 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
char * with *len parsec_inner_html, parsec_outer_html, parsec_text, and parsec_selector_compile's message 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 PARSEC_SCRIPTING.
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. 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.

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 and for a detached node.
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.

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) Detaches the node. Its number stays valid, and you can insert it again.

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), and inserting a document or fragment node (PARSEC_ERR_NOT_INSERTABLE).

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.

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_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 and serializing. A selector 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.

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. Neither API has chunked parsing (#6), bytes in with the encoding sniffed (#5), or copying 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, 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.
  • 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