tabnas-markdown (Rust)
A CommonMark parser for the tabnas
parsing engine, crate tabnas_markdown.
This parser is conformant to CommonMark 0.31.2: all 652 examples, across all 26 sections of the spec suite. The suite is vendored in this repository, so the claim is checkable rather than asserted:
&&
That run has the GFM extensions off, which is what measuring CommonMark
conformance means. On top of CommonMark the crate implements all five
GFM extensions (tables, task list items, autolink literals,
strikethrough and disallowed raw HTML), gated together on the single
gfm option, which is on by default. They score 24/24 on the vendored
GFM corpus:
&&
This is the Rust port of the canonical TypeScript implementation in
../ts; the TypeScript version is authoritative and this crate
tracks it, as the Go port in ../go does. All three runtimes
run the same shared AST fixtures, the same two HTML corpora, and the same
native-tree goldens, so they are held to one standard rather than to
each other.
The parser itself is engine-free: the block phase, the inline phase and
the renderer never touch the engine, and the AST projection needs only
its value type. The plugin in src/lib.rs is wiring around them, and
the engine path and the direct path are asserted to agree on every
example.
Use
Three outputs, and the AST is the primary one. parse_document returns
it as a tabnas::Value and runs no renderer:
use ;
to_json() hands back a serde_json::Value, the convenient shape for
reading the tree. Numbers in the AST are f64, so a heading's depth
reads as 1.0 there; the section on differences below has the detail.
The AST keeps references unresolved, as mdast does. A bracketed label is
a linkReference or an imageReference naming it, even where the
document does not define it, and each link reference definition is a
definition node where it stands, so the tree of a block depends on
nothing after it. resolve_references gives the tree back with the
references resolved, as CommonMark reads the document: a defined
reference as its link or image, the first definition of a label
winning, an undefined one as its source text, and the definitions gone.
use ;
Where a label with no definition decided how the text around it nests, the resolved tree is not the one CommonMark reads: five of the 652 CommonMark examples (512, 523, 528, 569, and 571). The HTML output resolves as CommonMark does.
HTML is opt-in, through to_html. The CommonMark suite scores HTML
output, so the renderer is what makes the 652/652 claim measurable; that
it is useful to callers is a consequence:
use ;
The HTML is not sanitised. Raw HTML blocks and inline tags pass
through verbatim, as CommonMark specifies. Put a sanitiser downstream of
any untrusted Markdown. GFM's disallowed-raw-HTML filter, on under the
default gfm: true, escapes the leading < of nine tag names (title,
textarea, style, xmp, iframe, noembed, noframes, script,
plaintext) and touches nothing else. It is not a sanitiser: it does
nothing about attributes or javascript: destinations.
use ;
The third output is the native CommonMark node tree, for callers who
want to walk or mutate before rendering. parse_tree returns it, with
sourcepos kept on block nodes, and render_html renders a tree back
to HTML, so parse, transform and render are three separate steps when
they need to be:
use ;
On an engine instance
The plugin path is what tabnas callers use, and the engine parse is
the parse: a custom matcher cuts the source a line at a time and feeds
each line to the same block algorithm, and the grammar's rules open and
close every node of the AST as the lines decide it. make builds an
instance with the plugin installed under the defaults, and its parse
returns the same AST:
Nothing but that matcher reads the source, so make declares
lex.window, and a parse from a reader holds the lines it has not
finished with rather than the whole text:
Reuse the instance: building it dominates a parse of a small document.
tabnas_markdown::parse keeps one shared default instance for the
one-off case:
make_with takes options. The only two, in every runtime, are gfm
(default true) and breaks (default false, which promotes soft line
breaks to hard breaks when set). Options::COMMONMARK is the pair with
gfm off, and the output is then plain CommonMark, byte for byte:
use ;
To install on an engine you are configuring yourself, hand the plugin
descriptor to use_plugin, or call markdown with typed options:
use ;
What is not implemented
Footnotes are not implemented. They are a GitHub product feature,
not part of the GFM spec suite. Because [^1] is a valid CommonMark
link label, a GitHub-authored footnote does not error: it renders
silently as a broken link. Nothing outside CommonMark and GFM is
implemented either: no math, front matter, definition lists, heading
attributes, admonitions, wiki links, emoji shortcodes, highlight or
sub/superscript. One collision follows from that: GFM's single-tilde
strikethrough takes the syntax other dialects use for subscript, so
under the default gfm: true a subscript becomes a deletion.
use ;
Install
The crate and the engine it runs on are both on crates.io, the engine as
tabnas-parser, whose library is named tabnas in code:
That is enough for the examples above: the crate re-exports
Tabnas and the error type (as MarkdownError), and the AST comes back
as a tabnas::Value whose methods need no import. Add the engine with
cargo add tabnas-parser as soon as your code names any other engine
type, because a crate's dependencies are not passed on to its dependents.
In this repository, Cargo.toml takes the engine by path from a sibling
checkout of https://github.com/tabnas/parser instead. Running the tests
needs a second sibling, https://github.com/tabnas/support, which holds
the shared fixture runner and is a dev-dependency only.
The crate needs Rust 1.85 or later.
Differences from the canonical TypeScript
Every example, fixture and golden agrees across the three runtimes, so the differences are in the surface and the machinery, never in the output:
- Options travel by reference, and
Optionsis a plainCopystruct.parse_document(src, &opts),to_html(src, &opts),parse_tree(src, &opts);Options::default()is the package defaults andOptions::COMMONMARKis plain CommonMark. The plugin descriptor still reads agfm/breaksoption bag, souse_plugin(plugin(), Some(bag))works the wayuse(Markdown, opts)does. - Numbers in the AST are
f64.tabnas::Valueholds every number as a float, soto_json()renders a heading'sdepthas1.0where the TypeScript prints1. The value is the same number, and the shared fixture runner compares numerically, so the fixtures pass unchanged; compare against1.0, or read it withas_f64(). - Errors are the engine's own. CommonMark defines an output for
every input, so the parser refuses nothing and the engine-free
functions return plain values.
parseandTabnas::parsereturnResult<Value, MarkdownError>because the engine can still fail on its own account (a budget exceeded, a panic in another plugin's callback);MarkdownErroris the engine'sTabnasError, re-exported. - The entity table is generated, not the standard library's.
src/entities.rsholds the same 2125 semicolon-terminated names asts/src/entities.ts, and a test reads the TypeScript table and asserts the two agree entry for entry. Unicode punctuation comes from theregexcrate's\p{P}and\p{S}tables, the same property escapes the TypeScript uses, and label case folding uses the full Unicode mappings, soßfolds as JavaScript folds it. - Per-parse state lives in a thread-local slab. The other runtimes
hang the live block parser on the engine context as an opaque object;
this engine's context holds only values, so the context carries a
slot index instead. The inline phase's own engine instance is built
once per install and shared by every parse, as in TypeScript (Go
builds one per parse), which is sound because the engine parses
through
&selfandTabnasisSend + Sync. - Token columns count characters. After an astral character (one
outside the Basic Multilingual Plane) the engine's token columns are
one character further left than the TypeScript engine's, which counts
UTF-16 units. That is the engine's recorded divergence, inherited
here; it is visible only on the token stream, never in the AST or the
native tree, whose
sourceposmatches the TypeScript goldens. - Nesting is capped. A document may nest
MAX_CONTAINER_NESTING(100) block quotes, lists and list items, andMAX_INLINE_NESTING(50) emphasis, link, and image wrappers. Deeper markers stay literal text. The canonical TypeScript has no such cap, so a document nested past either bound parses to a different tree here;DIVERGENCE.mdrecords it andtests/robust_test.rspins the boundary. The reason is the AST type rather than this crate: every phase here is iterative, but the AST is atabnas::Value, whoseto_json()and whose drop both recurse once per level, and an unbounded document aborted the process in the caller's own stack frame. The canonical runtime reaches the same wall as aRangeErrorfromJSON.stringify, which the caller can catch.
Build and test
The engine and the fixture runner are path dependencies on sibling checkouts, so there is nothing to fetch:
&&
Or, from the repository root, make test-rs, which adds cargo clippy.
For what CI would say, including formatting and the lockfile check, run
ci/rust/run.sh.
The suite runs the shared ../test/spec/*.tsv AST fixtures (111 rows in
11 files, through the same tabnas-support runner the TypeScript and Go
suites use), the native-tree goldens in ../test/spec/tree/, the
652-example CommonMark corpus and the 24-example GFM corpus, each graded
twice (engine-free and through the plugin), the differential gate
between those two paths, and the in-language tests: the plugin surface,
the pure recognisers, the entity table, adversarial input, token
columns, the inline driver's contract, scaling, a parse from a reader
at windows of a few characters, the rule depth of ten thousand repeated
blocks, the references and their resolution, and the version sites.
The Rust examples on this page run as doctests.
License
MIT.